]> git.sur5r.net Git - openldap/blobdiff - servers/slapd/back-meta/conn.c
don't lookup rootdn if the password is incorrect (ITS#4004)
[openldap] / servers / slapd / back-meta / conn.c
index c665a27165a94053aa30809ee2582edff99bcdc8..a0ae2801249fe69e0b607e747dff707e43900006 100644 (file)
@@ -1,73 +1,30 @@
-/*
- * Copyright 1998-2002 The OpenLDAP Foundation, All Rights Reserved.
- * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
- *
- * Copyright 2001, Pierangelo Masarati, All rights reserved. <ando@sys-net.it>
- *
- * This work has been developed to fulfill the requirements
- * of SysNet s.n.c. <http:www.sys-net.it> and it has been donated
- * to the OpenLDAP Foundation in the hope that it may be useful
- * to the Open Source community, but WITHOUT ANY WARRANTY.
- *
- * Permission is granted to anyone to use this software for any purpose
- * on any computer system, and to alter it and redistribute it, subject
- * to the following restrictions:
- *
- * 1. The author and SysNet s.n.c. are not responsible for the consequences
- *    of use of this software, no matter how awful, even if they arise from 
- *    flaws in it.
- *
- * 2. The origin of this software must not be misrepresented, either by
- *    explicit claim or by omission.  Since few users ever read sources,
- *    credits should appear in the documentation.
- *
- * 3. Altered versions must be plainly marked as such, and must not be
- *    misrepresented as being the original software.  Since few users
- *    ever read sources, credits should appear in the documentation.
- *    SysNet s.n.c. cannot be responsible for the consequences of the
- *    alterations.
- *
- * 4. This notice may not be removed or altered.
- *
+/* $OpenLDAP$ */
+/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
  *
- * This software is based on the backend back-ldap, implemented
- * by Howard Chu <hyc@highlandsun.com>, and modified by Mark Valence
- * <kurash@sassafras.com>, Pierangelo Masarati <ando@sys-net.it> and other
- * contributors. The contribution of the original software to the present
- * implementation is acknowledged in this copyright statement.
+ * Copyright 1999-2005 The OpenLDAP Foundation.
+ * Portions Copyright 2001-2003 Pierangelo Masarati.
+ * Portions Copyright 1999-2003 Howard Chu.
+ * All rights reserved.
  *
- * A special acknowledgement goes to Howard for the overall architecture
- * (and for borrowing large pieces of code), and to Mark, who implemented
- * from scratch the attribute/objectclass mapping.
- *
- * The original copyright statement follows.
- *
- * Copyright 1999, Howard Chu, All rights reserved. <hyc@highlandsun.com>
- *
- * Permission is granted to anyone to use this software for any purpose
- * on any computer system, and to alter it and redistribute it, subject
- * to the following restrictions:
- *
- * 1. The author is not responsible for the consequences of use of this
- *    software, no matter how awful, even if they arise from flaws in it.
- *
- * 2. The origin of this software must not be misrepresented, either by
- *    explicit claim or by omission.  Since few users ever read sources,
- *    credits should appear in the documentation.
- *
- * 3. Altered versions must be plainly marked as such, and must not be
- *    misrepresented as being the original software.  Since few users
- *    ever read sources, credits should appear in the
- *    documentation.
- *
- * 4. This notice may not be removed or altered.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted only as authorized by the OpenLDAP
+ * Public License.
  *
+ * A copy of this license is available in the file LICENSE in the
+ * top-level directory of the distribution or, alternatively, at
+ * <http://www.OpenLDAP.org/license.html>.
+ */
+/* ACKNOWLEDGEMENTS:
+ * This work was initially developed by the Howard Chu for inclusion
+ * in OpenLDAP Software and subsequently enhanced by Pierangelo
+ * Masarati.
  */
 
 #include "portable.h"
 
 #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 ( ( lc1->conn < lc2->conn ) ? -1 :
-                       ( ( lc1->conn > lc2-> conn ) ? 1 : 0 ) );
+       return SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
 }
 
 /*
@@ -110,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->conn == lc2->conn ) ? -1 : 0 );
+       return( ( mc1->mc_conn == mc2->mc_conn ) ? -1 : 0 );
 }
 
 /*
@@ -132,15 +86,15 @@ ravl_print( Avlnode *root, int depth )
                return;
        }
        
-       ravl_print( root->avl_right, depth+1 );
+       ravl_print( root->avl_right, depth + 1 );
        
        for ( i = 0; i < depth; i++ ) {
                printf( "    " );
        }
 
-       printf( "c(%d) %d\n", ( ( struct metaconn * )root->avl_data )->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 );
+       ravl_print( root->avl_left, depth + 1 );
 }
 
 static void
@@ -166,167 +120,488 @@ 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;
-       int i;
+       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 ) {
-               return NULL;
-       }
-       
-       /*
-        * make it a null-terminated array ...
-        */
-       lc->conns = ch_calloc( sizeof( struct metasingleconn * ), ntargets+1 );
-       if ( lc->conns == NULL ) {
-               free( lc );
+       /* malloc all in one */
+       mc = ( metaconn_t * )ch_malloc( sizeof( metaconn_t )
+                       + sizeof( metasingleconn_t ) * ntargets );
+       if ( mc == NULL ) {
                return NULL;
        }
 
        for ( i = 0; i < ntargets; i++ ) {
-               lc->conns[ i ] =
-                       ch_calloc( sizeof( struct metasingleconn ), 1 );
-               if ( lc->conns[ i ] == NULL ) {
-                       charray_free( ( char ** )lc->conns );
-                       free( lc->conns );
-                       free( lc );
-                       return NULL;
-               }
+               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->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->conns ) {
-               int i;
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
 
-               for ( i = 0; lc->conns[ i ] != NULL; ++i ) {
-                       free( lc->conns[ i ] );
-               }
-               charray_free( ( char ** )lc->conns );
+       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(
-               Connection *conn, 
-               Operation *op, 
-               struct metatarget *lt, 
-               int vers,
-               struct metasingleconn *lsc
-               )
+int
+meta_back_init_one_conn(
+       Operation               *op,
+       SlapReply               *rs,
+       metatarget_t            *mt, 
+       metasingleconn_t        *msc,
+       ldap_back_send_t        sendok )
 {
-       int err;
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
+       int             vers;
+       dncookie        dc;
 
        /*
         * Already init'ed
         */
-       if ( lsc->ld != NULL ) {
-               return LDAP_SUCCESS;
+       if ( msc->msc_ld != NULL ) {
+               return rs->sr_err = LDAP_SUCCESS;
        }
        
        /*
         * Attempts to initialize the connection to the target ds
         */
-       err = ldap_initialize( &lsc->ld, lt->uri );
-       if ( err != LDAP_SUCCESS ) {
-               return ldap_back_map_result( err );
+       rs->sr_err = ldap_initialize( &msc->msc_ld, mt->mt_uri );
+       if ( rs->sr_err != LDAP_SUCCESS ) {
+               goto error_return;
        }
-       
+
        /*
         * Set LDAP version. This will always succeed: If the client
         * bound with a particular version, then so can we.
         */
-       ldap_set_option( lsc->ld, LDAP_OPT_PROTOCOL_VERSION, &vers );
+       vers = op->o_conn->c_protocol;
+       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( mi ) ) {
+               ldap_set_option( msc->msc_ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON );
+       }
+
+#ifdef HAVE_TLS
+       /* 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
+                * FIXME: OpenLDAP does not return referral on StartTLS yet
+                */
+               int             msgid;
+
+               rs->sr_err = ldap_start_tls( msc->msc_ld, NULL, NULL, &msgid );
+               if ( rs->sr_err == LDAP_SUCCESS ) {
+                       LDAPMessage     *res = NULL;
+                       int             rc, nretries = mt->mt_nretries;
+                       struct timeval  tv = { 0, 0 };
+
+retry:;
+                       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 ( nretries != 0 ) {
+                                       if ( nretries > 0 ) {
+                                               nretries--;
+                                       }
+                                       tv.tv_sec = 0;
+                                       tv.tv_usec = 100000;
+                                       goto retry;
+                               }
+                               rs->sr_err = LDAP_OTHER;
+
+                       } else if ( rc == LDAP_RES_EXTENDED ) {
+                               struct berval   *data = NULL;
+
+                               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( msc->msc_ld, res, 1 );
+                                       res = NULL;
+                                       
+                                       /* FIXME: in case a referral 
+                                        * is returned, should we try
+                                        * using it instead of the 
+                                        * configured URI? */
+                                       if ( rs->sr_err == LDAP_SUCCESS ) {
+                                               ldap_install_tls( msc->msc_ld );
+
+                                       } else if ( rs->sr_err == LDAP_REFERRAL ) {
+                                               rs->sr_err = LDAP_OTHER;
+                                               rs->sr_text = "unwilling to chase referral returned by Start TLS exop";
+                                       }
+
+                                       if ( data ) {
+                                               if ( data->bv_val ) {
+                                                       ber_memfree( data->bv_val );
+                                               }
+                                               ber_memfree( data );
+                                       }
+                               }
+
+                       } else {
+                               rs->sr_err = LDAP_OTHER;
+                       }
+
+                       if ( res != NULL ) {
+                               ldap_msgfree( res );
+                       }
+               }
+#else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
+               /*
+                * use synchronous StartTLS
+                */
+               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
+                * is not "ldaps://"; this may occur not only in case
+                * 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( mi ) ) )
+               {
+                       ldap_unbind_ext_s( msc->msc_ld, NULL, NULL );
+                       goto error_return;
+               }
+       }
+#endif /* HAVE_TLS */
 
        /*
-        * Sets a cookie for the rewrite session
+        * Set the network timeout if set
         */
-       ( void )rewrite_session_init( lt->rwinfo, conn );
+       if ( mi->mi_network_timeout != 0 ) {
+               struct timeval  network_timeout;
+
+               network_timeout.tv_usec = 0;
+               network_timeout.tv_sec = mi->mi_network_timeout;
+
+               ldap_set_option( msc->msc_ld, LDAP_OPT_NETWORK_TIMEOUT,
+                               (void *)&network_timeout );
+       }
 
        /*
-        * If the connection dn is not null, an attempt to rewrite it is made
+        * If the connection DN is not null, an attempt to rewrite it is made
         */
-       if ( conn->c_cdn != 0 ) {
+       if ( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
+               dc.target = mt;
+               dc.conn = op->o_conn;
+               dc.rs = rs;
+               dc.ctx = "bindDN";
                
                /*
                 * Rewrite the bind dn if needed
                 */
-               lsc->bound_dn.bv_val = NULL;
-               switch ( rewrite_session( lt->rwinfo, "bindDn",
-                                       conn->c_cdn, conn, 
-                                       &lsc->bound_dn.bv_val ) ) {
-               case REWRITE_REGEXEC_OK:
-                       if ( lsc->bound_dn.bv_val == NULL ) {
-                               ber_str2bv( conn->c_cdn, 0, 1, &lsc->bound_dn );
-                       }
-#ifdef NEW_LOGGING
-                       LDAP_LOG(( "backend", LDAP_LEVEL_DETAIL1,
-                                       "[rw] bindDn: \"%s\" -> \"%s\"\n",
-                                       conn->c_cdn, lsc->bound_dn.bv_val ));
-#else /* !NEW_LOGGING */
-                       Debug( LDAP_DEBUG_ARGS,
-                                       "rw> bindDn: \"%s\" -> \"%s\"\n",
-                                       conn->c_cdn, lsc->bound_dn.bv_val, 0 );
-#endif /* !NEW_LOGGING */
-                       break;
-                       
-               case REWRITE_REGEXEC_UNWILLING:
-                       send_ldap_result( conn, op,
-                                       LDAP_UNWILLING_TO_PERFORM,
-                                       NULL, "Unwilling to perform",
-                                       NULL, NULL );
-                       return LDAP_UNWILLING_TO_PERFORM;
-                       
-               case REWRITE_REGEXEC_ERR:
-                       send_ldap_result( conn, op,
-                                       LDAP_OPERATIONS_ERROR,
-                                       NULL, "Operations error",
-                                       NULL, NULL );
-                       return LDAP_OPERATIONS_ERROR;
+               if ( ldap_back_dn_massage( &dc, &op->o_conn->c_dn,
+                                       &msc->msc_bound_ndn ) )
+               {
+                       goto error_return;
                }
 
-               assert( lsc->bound_dn.bv_val );
+               /* copy the DN idf needed */
+               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( &msc->msc_bound_ndn ) );
 
        } else {
-               ber_str2bv( "", 0, 1, &lsc->bound_dn );
+               ber_str2bv( "", 0, 1, &msc->msc_bound_ndn );
+       }
+
+       msc->msc_bound = META_UNBOUND;
+
+error_return:;
+       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;
+               }
+       }
+
+       return rs->sr_err;
+}
+
+/*
+ * 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 );
+       }
+
+       ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
+
+       return rc == LDAP_SUCCESS ? 1 : 0;
+}
+
+/*
+ * callback for unique candidate selection
+ */
+static int
+meta_back_conn_cb( Operation *op, SlapReply *rs )
+{
+       assert( op->o_tag == LDAP_REQ_SEARCH );
+
+       switch ( rs->sr_type ) {
+       case REP_SEARCH:
+               ((int *)op->o_callback->sc_private)[0] = (int)op->o_private;
+               break;
+
+       case REP_SEARCHREF:
+       case REP_RESULT:
+               break;
+
+       default:
+               return rs->sr_err;
        }
 
-       lsc->bound = META_UNBOUND;
+       return 0;
+}
+
+
+static int
+meta_back_get_candidate(
+       Operation       *op,
+       SlapReply       *rs,
+       struct berval   *ndn )
+{
+       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( mi, ndn );
 
        /*
-        * The candidate is activated
+        * if any is found, inits the connection
         */
-       lsc->candidate = META_CANDIDATE;
-       return LDAP_SUCCESS;
+       if ( candidate == META_TARGET_NONE ) {
+               rs->sr_err = LDAP_NO_SUCH_OBJECT;
+               rs->sr_text = "no suitable candidate target found";
+
+       } else if ( candidate == META_TARGET_MULTIPLE ) {
+               Filter          f = { 0 };
+               Operation       op2 = *op;
+               SlapReply       rs2 = { 0 };
+               slap_callback   cb2 = { 0 };
+               int             rc;
+
+               /* try to get a unique match for the request ndn
+                * among the multiple candidates available */
+               op2.o_tag = LDAP_REQ_SEARCH;
+               op2.o_req_dn = *ndn;
+               op2.o_req_ndn = *ndn;
+               op2.ors_scope = LDAP_SCOPE_BASE;
+               op2.ors_deref = LDAP_DEREF_NEVER;
+               op2.ors_attrs = slap_anlist_no_attrs;
+               op2.ors_attrsonly = 0;
+               op2.ors_limit = NULL;
+               op2.ors_slimit = 1;
+               op2.ors_tlimit = SLAP_NO_LIMIT;
+
+               f.f_choice = LDAP_FILTER_PRESENT;
+               f.f_desc = slap_schema.si_ad_objectClass;
+               op2.ors_filter = &f;
+               BER_BVSTR( &op2.ors_filterstr, "(objectClass=*)" );
+
+               op2.o_callback = &cb2;
+               cb2.sc_response = meta_back_conn_cb;
+               cb2.sc_private = (void *)&candidate;
+
+               rc = op->o_bd->be_search( &op2, &rs2 );
+
+               switch ( rs2.sr_err ) {
+               case LDAP_SUCCESS:
+               default:
+                       rs->sr_err = rs2.sr_err;
+                       break;
+
+               case LDAP_SIZELIMIT_EXCEEDED:
+                       /* if multiple candidates can serve the operation,
+                        * and a default target is defined, and it is
+                        * a candidate, try using it (FIXME: YMMV) */
+                       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 = mi->mi_defaulttarget;
+                               rs->sr_err = LDAP_SUCCESS;
+                               rs->sr_text = NULL;
+
+                       } else {
+                               rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
+                               rs->sr_text = "cannot select unique candidate target";
+                       }
+                       break;
+               }
+
+       } else {
+               rs->sr_err = LDAP_SUCCESS;
+       }
+
+       return candidate;
+}
+
+static void    *meta_back_candidates_dummy;
+
+static void
+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 );
+}
+
+SlapReply *
+meta_back_candidates_get( Operation *op )
+{
+       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_candidates_dummy, &data, NULL );
+               mc = (metacandidates_t *)data;
+
+       } else {
+               mc = mi->mi_candidates;
+       }
+
+       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_candidates_dummy, data,
+                                       meta_back_candidates_keyfree );
+
+               } else {
+                       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 mc->mc_candidates;
 }
 
 /*
@@ -334,215 +609,446 @@ init_one_conn(
  * 
  * Prepares the connection structure
  * 
- * FIXME: This function needs to receive some info on the type of operation
- * it is invoked by, so that only the correct pool of candidate targets
- * is initialized in case no connection was available yet.
- * 
- * At present a flag that says whether the candidate target must be unique
- * is passed; eventually an operation agent will be used.
+ * RATIONALE:
+ *
+ * - determine what DN is being requested:
+ *
+ *     op      requires candidate      checks
+ *
+ *     add     unique                  parent of o_req_ndn
+ *     bind    unique^*[/all]          o_req_ndn [no check]
+ *     compare unique^+                o_req_ndn
+ *     delete  unique                  o_req_ndn
+ *     modify  unique                  o_req_ndn
+ *     search  any                     o_req_ndn
+ *     modrdn  unique[, unique]        o_req_ndn[, orr_nnewSup]
+ *
+ * - for ops that require the candidate to be unique, in case of multiple
+ *   occurrences an internal search with sizeLimit=1 is performed
+ *   if a unique candidate can actually be determined.  If none is found,
+ *   the operation aborts; if multiple are found, the default target
+ *   is used if defined and candidate; otherwise the operation aborts.
+ *
+ * *^note: actually, the bind operation is handled much like a search;
+ *   i.e. the bind is broadcast to all candidate targets.
+ *
+ * +^note: actually, the compare operation is handled much like a search;
+ *   i.e. the compare is broadcast to all candidate targets, while checking
+ *   that exactly none (noSuchObject) or one (TRUE/FALSE/UNDEFINED) is
+ *   returned.
  */
-struct metaconn *
+metaconn_t *
 meta_back_getconn(
-               struct metainfo *li,
-               Connection      *conn,
-               Operation       *op,
-               int             op_type,
-               struct berval   *ndn,
-               int             *candidate )
+               Operation               *op,
+       SlapReply               *rs,
+       int                     *candidate,
+       ldap_back_send_t        sendok )
 {
-       struct metaconn *lc, lc_curr;
-       int vers, cached = -1, i = -1, err = LDAP_SUCCESS;
-       int new_conn = 0;
+       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,
+                       ncandidates = 0;
+
+
+       meta_op_type    op_type = META_OP_REQUIRE_SINGLE;
+       int             parent = 0,
+                       newparent = 0;
+       struct berval   ndn = op->o_req_ndn,
+                       pndn;
+
+       SlapReply       *candidates = meta_back_candidates_get( op );
 
        /* Searches for a metaconn in the avl tree */
-       lc_curr.conn = conn;
-       ldap_pvt_thread_mutex_lock( &li->conn_mutex );
-       lc = (struct metaconn *)avl_find( li->conntree, 
-               (caddr_t)&lc_curr, meta_back_conn_cmp );
-       ldap_pvt_thread_mutex_unlock( &li->conn_mutex );
-
-       /* Looks like we didn't get a bind. Open a new session... */
-       if ( !lc ) {
-               lc = metaconn_alloc( li->ntargets );
-               lc->conn = conn;
-               new_conn = 1;
+       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, &pndn );
+               break;
+
+       case LDAP_REQ_MODRDN:
+               /* if nnewSuperior is not NULL, it must resolve
+                * to the same candidate as the req_ndn */
+               if ( op->orr_nnewSup ) {
+                       newparent = 1;
+               }
+               break;
 
-       vers = conn->c_protocol;
+       case LDAP_REQ_BIND:
+               /* if bound as rootdn, the backend must bind to all targets
+                * with the administrative identity */
+               if ( op->orb_method == LDAP_AUTH_SIMPLE && be_isroot_pw( op ) ) {
+                       op_type = META_OP_REQUIRE_ALL;
+               }
+               break;
+
+       case LDAP_REQ_DELETE:
+       case LDAP_REQ_MODIFY:
+               /* just a unique candidate */
+               break;
+
+       case LDAP_REQ_COMPARE:
+       case LDAP_REQ_SEARCH:
+               /* allow multiple candidates for the searchBase */
+               op_type = META_OP_ALLOW_MULTIPLE;
+               break;
+
+       default:
+               /* right now, just break (exop?) */
+               break;
+       }
 
+       /*
+        * require all connections ...
+        */
+       if ( op_type == META_OP_REQUIRE_ALL ) {
+
+               /* 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;
+               }
+
+               for ( i = 0; i < mi->mi_ntargets; i++ ) {
+
+                       /*
+                        * The target is activated; if needed, it is
+                        * also init'd
+                        */
+                       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 ].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->cache.ttl != META_DNCACHE_DISABLED ) {
-               cached = i = meta_dncache_get_target( &li->cache, 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;
+
+               for ( j = 0; j < mi->mi_ntargets; j++ ) {
+                       candidates[ j ].sr_tag = META_NOT_CANDIDATE;
+               }
 
                /*
                 * tries to get a unique candidate
-                * (takes care of default target 
+                * (takes care of default target)
                 */
-               if ( i < 0 ) {
-                       i = meta_back_select_unique_candidate( li, ndn );
+               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 any is found, inits the connection
-                */
-               if ( i < 0 ) {
-                       if ( new_conn ) {
-                               metaconn_free( lc );
+               if ( newparent && meta_back_get_candidate( op, rs, op->orr_nnewSup ) != i )
+               {
+                       if ( mc != NULL ) {
+                               meta_back_release_conn( op, mc );
                        }
 
-                       send_ldap_result( conn, op, LDAP_NO_SUCH_OBJECT,
-                               NULL, "", NULL, NULL );
+                       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;
                }
-                               
-#ifdef NEW_LOGGING
-               LDAP_LOG(( "backend", LDAP_LEVEL_INFO,
-                               "meta_back_getconn: got target %d"
-                               " for ndn=\"%s\" from cache\n", 
-                               i, ndn->bv_val ));
-#else /* !NEW_LOGGING */
-               Debug( LDAP_DEBUG_CACHE,
-       "==>meta_back_getconn: got target %d for ndn=\"%s\" from cache\n%s",
-                               i, ndn->bv_val, "" );
-#endif /* !NEW_LOGGING */
+
+               Debug( LDAP_DEBUG_TRACE,
+       "==>meta_back_getconn: got target %d for ndn=\"%s\" from cache\n",
+                               i, op->o_req_ndn.bv_val, 0 );
+
+               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 ( mc == NULL ) {
+                               mc = metaconn_alloc( op );
+                               mc->mc_conn = op->o_conn;
+                               new_conn = 1;
+                       }
+               }
 
                /*
                 * Clear all other candidates
                 */
-               ( void )meta_clear_unused_candidates( li, lc, i, 0 );
+               ( 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( conn, op, li->targets[ i ],
-                               vers, lc->conns[ i ] );
+               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?
                         */
-                       ( void )meta_clear_one_candidate( lc->conns[ i ], 1 );
-                       if ( new_conn ) {
-                               metaconn_free( lc );
+                       candidates[ i ].sr_tag = META_NOT_CANDIDATE;
+                       if ( new_conn ) {
+                               (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;
                }
 
        /*
-        * require all connections ...
+        * if no unique candidate ...
         */
-       } else if (op_type == META_OP_REQUIRE_ALL) {
-               for ( i = 0; i < li->ntargets; i++ ) {
+       } else {
 
-                       /*
-                        * The target is activated; if needed, it is
-                        * also init'd
-                        */
-                       int lerr = init_one_conn( conn, op, li->targets[ i ],
-                                       vers, lc->conns[ i ] );
-                       if ( lerr != LDAP_SUCCESS ) {
-                               
-                               /*
-                                * FIXME: in case one target cannot
-                                * be init'd, should the other ones
-                                * be tried?
-                                */
-                               ( void )meta_clear_one_candidate( lc->conns[ i ], 1 );
-                               err = lerr;
-                               continue;
-                       }
+               /* 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;
                }
 
-       /*
-        * if no unique candidate ...
-        */
-       } else {
-               for ( i = 0; i < li->ntargets; i++ ) {
+               for ( i = 0; i < mi->mi_ntargets; i++ ) {
                        if ( i == cached 
-               || meta_back_is_candidate( &li->targets[ i ]->suffix, 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( conn, op,
-                                               li->targets[ i ],
-                                               vers, lc->conns[ i ] );
-                               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?
                                         */
-                                       ( void )meta_clear_one_candidate( lc->conns[ i ], 1 );
+                                       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 {
+                               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 meta_back_init_one_conn non-fatal errors */
+       rs->sr_err = LDAP_SUCCESS;
+       rs->sr_text = NULL;
+
        if ( new_conn ) {
                
                /*
                 * Inserts the newly created metaconn in the avl tree
                 */
-               ldap_pvt_thread_mutex_lock( &li->conn_mutex );
-               err = avl_insert( &li->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->conntree );
+               myprint( mi->mi_conntree );
 #endif /* PRINT_CONNTREE */
                
-               ldap_pvt_thread_mutex_unlock( &li->conn_mutex );
+               ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
 
-#ifdef NEW_LOGGING
-               LDAP_LOG(( "backend", LDAP_LEVEL_INFO,
-                               "meta_back_getconn: conn %ld inserted\n",
-                               lc->conn->c_connid ));
-#else /* !NEW_LOGGING */
-               Debug( LDAP_DEBUG_TRACE,
-                       "=>meta_back_getconn: conn %ld inserted\n%s%s",
-                       lc->conn->c_connid, "", "" );
-#endif /* !NEW_LOGGING */
-               
                /*
                 * 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 ) {
-                       send_ldap_result( conn, op, LDAP_OPERATIONS_ERROR,
-                       NULL, "Internal server error", NULL, NULL );
-                       metaconn_free( lc );
+                       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";
+                       meta_back_freeconn( op, mc );
+                       if ( sendok & LDAP_BACK_SENDERR ) {
+                               send_ldap_result( op, rs );
+                               rs->sr_text = NULL;
+                       }
                        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 {
-#ifdef NEW_LOGGING
-               LDAP_LOG(( "backend", LDAP_LEVEL_INFO,
-                               "meta_back_getconn: conn %ld fetched\n",
-                               lc->conn->c_connid ));
-#else /* !NEW_LOGGING */
                Debug( LDAP_DEBUG_TRACE,
-                       "=>meta_back_getconn: conn %ld fetched\n%s%s",
-                       lc->conn->c_connid, "", "" );
-#endif /* !NEW_LOGGING */
+                       "%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 );
+}