]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/search.c
don't bail out if all targets are too lazy...
[openldap] / servers / slapd / back-meta / search.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1999-2007 The OpenLDAP Foundation.
5  * Portions Copyright 2001-2003 Pierangelo Masarati.
6  * Portions Copyright 1999-2003 Howard Chu.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by the Howard Chu for inclusion
19  * in OpenLDAP Software and subsequently enhanced by Pierangelo
20  * Masarati.
21  */
22
23 #include "portable.h"
24
25 #include <stdio.h>
26
27 #include <ac/socket.h>
28 #include <ac/string.h>
29 #include <ac/time.h>
30
31 #include "lutil.h"
32 #include "slap.h"
33 #include "../back-ldap/back-ldap.h"
34 #include "back-meta.h"
35 #undef ldap_debug       /* silence a warning in ldap-int.h */
36 #include "ldap_log.h"
37 #include "../../../libraries/libldap/ldap-int.h"
38
39 /* IGNORE means that target does not (no longer) participate
40  * in the search;
41  * NOTREADY means the search on that target has not been initialized yet
42  */
43 #define META_MSGID_IGNORE       (-1)
44 #define META_MSGID_NEED_BIND    (-2)
45 #define META_MSGID_CONNECTING   (-3)
46
47 static int
48 meta_send_entry(
49         Operation       *op,
50         SlapReply       *rs,
51         metaconn_t      *mc,
52         int             i,
53         LDAPMessage     *e );
54
55 typedef enum meta_search_candidate_t {
56         META_SEARCH_UNDEFINED = -2,
57         META_SEARCH_ERR = -1,
58         META_SEARCH_NOT_CANDIDATE,
59         META_SEARCH_CANDIDATE,
60         META_SEARCH_BINDING,
61         META_SEARCH_NEED_BIND,
62         META_SEARCH_CONNECTING
63 } meta_search_candidate_t;
64
65 /*
66  * meta_search_dobind_init()
67  *
68  * initiates bind for a candidate target of a search.
69  */
70 static meta_search_candidate_t
71 meta_search_dobind_init(
72         Operation               *op,
73         SlapReply               *rs,
74         metaconn_t              **mcp,
75         int                     candidate,
76         SlapReply               *candidates )
77 {
78         metaconn_t              *mc = *mcp;
79         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
80         metatarget_t            *mt = mi->mi_targets[ candidate ];
81         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
82
83         struct berval           binddn = msc->msc_bound_ndn,
84                                 cred = msc->msc_cred;
85         int                     method;
86
87         int                     rc;
88
89         meta_search_candidate_t retcode;
90
91         Debug( LDAP_DEBUG_TRACE, "%s >>> meta_search_dobind_init[%d]\n",
92                 op->o_log_prefix, candidate, 0 );
93
94         /*
95          * all the targets are already bound as pseudoroot
96          */
97         if ( mc->mc_authz_target == META_BOUND_ALL ) {
98                 return META_SEARCH_CANDIDATE;
99         }
100
101         retcode = META_SEARCH_BINDING;
102         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
103         if ( LDAP_BACK_CONN_ISBOUND( msc ) || LDAP_BACK_CONN_ISANON( msc ) ) {
104                 /* already bound (or anonymous) */
105
106 #ifdef DEBUG_205
107                 char    buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
108                 int     bound = 0;
109
110                 if ( LDAP_BACK_CONN_ISBOUND( msc ) ) {
111                         bound = 1;
112                 }
113
114                 snprintf( buf, sizeof( buf ), " mc=%p ld=%p%s DN=\"%s\"",
115                         (void *)mc, (void *)msc->msc_ld,
116                         bound ? " bound" : " anonymous",
117                         bound == 0 ? "" : msc->msc_bound_ndn.bv_val );
118                 Debug( LDAP_DEBUG_ANY, "### %s meta_search_dobind_init[%d]%s\n",
119                         op->o_log_prefix, candidate, buf );
120 #endif /* DEBUG_205 */
121
122                 retcode = META_SEARCH_CANDIDATE;
123
124         } else if ( META_BACK_CONN_CREATING( msc ) || LDAP_BACK_CONN_BINDING( msc ) ) {
125                 /* another thread is binding the target for this conn; wait */
126
127 #ifdef DEBUG_205
128                 char    buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
129
130                 snprintf( buf, sizeof( buf ), " mc=%p ld=%p needbind",
131                         (void *)mc, (void *)msc->msc_ld );
132                 Debug( LDAP_DEBUG_ANY, "### %s meta_search_dobind_init[%d]%s\n",
133                         op->o_log_prefix, candidate, buf );
134 #endif /* DEBUG_205 */
135
136                 candidates[ candidate ].sr_msgid = META_MSGID_NEED_BIND;
137                 retcode = META_SEARCH_NEED_BIND;
138
139         } else {
140                 /* we'll need to bind the target for this conn */
141
142 #ifdef DEBUG_205
143                 char buf[ SLAP_TEXT_BUFLEN ];
144
145                 snprintf( buf, sizeof( buf ), " mc=%p ld=%p binding",
146                         (void *)mc, (void *)msc->msc_ld );
147                 Debug( LDAP_DEBUG_ANY, "### %s meta_search_dobind_init[%d]%s\n",
148                         op->o_log_prefix, candidate, buf );
149 #endif /* DEBUG_205 */
150
151                 if ( msc->msc_ld == NULL ) {
152                         /* for some reason (e.g. because formerly in "binding"
153                          * state, with eventual connection expiration or invalidation)
154                          * it was not initialized as expected */
155
156                         Debug( LDAP_DEBUG_ANY, "%s meta_search_dobind_init[%d] mc=%p ld=NULL\n",
157                                 op->o_log_prefix, candidate, (void *)mc );
158
159                         rc = meta_back_init_one_conn( op, rs, *mcp, candidate,
160                                 LDAP_BACK_CONN_ISPRIV( *mcp ), LDAP_BACK_DONTSEND, 0 );
161                         switch ( rc ) {
162                         case LDAP_SUCCESS:
163                                 assert( msc->msc_ld != NULL );
164                                 break;
165
166                         case LDAP_SERVER_DOWN:
167                         case LDAP_UNAVAILABLE:
168                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
169                                 goto down;
170         
171                         default:
172                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
173                                 goto other;
174                         }
175                 }
176
177                 LDAP_BACK_CONN_BINDING_SET( msc );
178         }
179
180         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
181
182         if ( retcode != META_SEARCH_BINDING ) {
183                 return retcode;
184         }
185
186         /* NOTE: this obsoletes pseudorootdn */
187         if ( op->o_conn != NULL &&
188                 !op->o_do_not_cache &&
189                 ( BER_BVISNULL( &msc->msc_bound_ndn ) ||
190                         BER_BVISEMPTY( &msc->msc_bound_ndn ) ||
191                         ( mt->mt_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
192         {
193                 rc = meta_back_proxy_authz_cred( mc, candidate, op, rs, LDAP_BACK_DONTSEND, &binddn, &cred, &method );
194                 if ( rc != LDAP_SUCCESS ) {
195                         goto down;
196                 }
197
198                 /* NOTE: we copy things here, even if bind didn't succeed yet,
199                  * because the connection is not shared until bind is over */
200                 if ( !BER_BVISNULL( &binddn ) ) {
201                         ber_bvreplace( &msc->msc_bound_ndn, &binddn );
202                         if ( LDAP_BACK_SAVECRED( mi ) && !BER_BVISNULL( &cred ) ) {
203                                 if ( !BER_BVISNULL( &msc->msc_cred ) ) {
204                                         memset( msc->msc_cred.bv_val, 0,
205                                                 msc->msc_cred.bv_len );
206                                 }
207                                 ber_bvreplace( &msc->msc_cred, &cred );
208                         }
209                 }
210
211                 if ( LDAP_BACK_CONN_ISBOUND( msc ) ) {
212                         /* apparently, idassert was configured with SASL bind,
213                          * so bind occurred inside meta_back_proxy_authz_cred() */
214                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
215                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
216                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
217                         return META_SEARCH_CANDIDATE;
218                 }
219
220                 /* paranoid */
221                 switch ( method ) {
222                 case LDAP_AUTH_NONE:
223                 case LDAP_AUTH_SIMPLE:
224                         /* do a simple bind with binddn, cred */
225                         break;
226
227                 default:
228                         assert( 0 );
229                         break;
230                 }
231         }
232
233         assert( msc->msc_ld != NULL );
234
235         /* connect must be async */
236 retry:;
237         ldap_set_option( msc->msc_ld, LDAP_OPT_CONNECT_ASYNC, LDAP_OPT_ON );
238
239         rc = ldap_sasl_bind( msc->msc_ld, binddn.bv_val, LDAP_SASL_SIMPLE, &cred,
240                         NULL, NULL, &candidates[ candidate ].sr_msgid );
241
242 #ifdef DEBUG_205
243         {
244                 char buf[ SLAP_TEXT_BUFLEN ];
245
246                 snprintf( buf, sizeof( buf ), "meta_search_dobind_init[%d] mc=%p ld=%p rc=%d",
247                         candidate, (void *)mc, (void *)mc->mc_conns[ candidate ].msc_ld, rc );
248                 Debug( LDAP_DEBUG_ANY, "### %s %s\n",
249                         op->o_log_prefix, buf, 0 );
250         }
251 #endif /* DEBUG_205 */
252
253         switch ( rc ) {
254         case LDAP_SUCCESS:
255                 assert( candidates[ candidate ].sr_msgid >= 0 );
256                 META_BINDING_SET( &candidates[ candidate ] );
257                 return META_SEARCH_BINDING;
258
259         case LDAP_X_CONNECTING:
260                 /* must retry, same conn */
261                 candidates[ candidate ].sr_msgid = META_MSGID_CONNECTING;
262                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
263                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
264                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
265                 return META_SEARCH_CONNECTING;
266
267         case LDAP_SERVER_DOWN:
268 down:;
269                 /* This is the worst thing that could happen:
270                  * the search will wait until the retry is over. */
271                 if ( !META_IS_RETRYING( &candidates[ candidate ] ) ) {
272                         META_RETRYING_SET( &candidates[ candidate ] );
273
274                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
275
276                         assert( mc->mc_refcnt > 0 );
277                         if ( LogTest( LDAP_DEBUG_ANY ) ) {
278                                 char    buf[ SLAP_TEXT_BUFLEN ];
279
280                                 /* this lock is required; however,
281                                  * it's invoked only when logging is on */
282                                 ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
283                                 snprintf( buf, sizeof( buf ),
284                                         "retrying URI=\"%s\" DN=\"%s\"",
285                                         mt->mt_uri,
286                                         BER_BVISNULL( &msc->msc_bound_ndn ) ?
287                                                 "" : msc->msc_bound_ndn.bv_val );
288                                 ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
289
290                                 Debug( LDAP_DEBUG_ANY,
291                                         "%s meta_search_dobind_init[%d]: %s.\n",
292                                         op->o_log_prefix, candidate, buf );
293                         }
294
295                         meta_clear_one_candidate( op, mc, candidate );
296                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
297
298                         ( void )rewrite_session_delete( mt->mt_rwmap.rwm_rw, op->o_conn );
299
300                         /* mc here must be the regular mc, reset and ready for init */
301                         rc = meta_back_init_one_conn( op, rs, mc, candidate,
302                                 LDAP_BACK_CONN_ISPRIV( mc ), LDAP_BACK_DONTSEND, 0 );
303
304                         if ( rc == LDAP_SUCCESS ) {
305                                 LDAP_BACK_CONN_BINDING_SET( msc );
306                         }
307
308                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
309
310                         if ( rc == LDAP_SUCCESS ) {
311                                 candidates[ candidate ].sr_msgid = META_MSGID_IGNORE;
312                                 goto retry;
313                         }
314                 }
315
316                 if ( *mcp == NULL ) {
317                         retcode = META_SEARCH_ERR;
318                         rs->sr_err = LDAP_UNAVAILABLE;
319                         break;
320                 }
321                 /* fall thru */
322
323         default:
324 other:;
325                 rs->sr_err = rc;
326                 rc = slap_map_api2result( rs );
327
328                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
329                 meta_clear_one_candidate( op, mc, candidate );
330                 candidates[ candidate ].sr_err = rc;
331                 if ( META_BACK_ONERR_STOP( mi ) ) {
332                         LDAP_BACK_CONN_TAINTED_SET( mc );
333                         meta_back_release_conn_lock( mi, mc, 0 );
334                         *mcp = NULL;
335                         rs->sr_err = rc;
336
337                         retcode = META_SEARCH_ERR;
338
339                 } else {
340                         retcode = META_SEARCH_NOT_CANDIDATE;
341                 }
342                 candidates[ candidate ].sr_msgid = META_MSGID_IGNORE;
343                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
344                 break;
345         }
346
347         return retcode;
348 }
349
350 static meta_search_candidate_t
351 meta_search_dobind_result(
352         Operation               *op,
353         SlapReply               *rs,
354         metaconn_t              **mcp,
355         int                     candidate,
356         SlapReply               *candidates,
357         LDAPMessage             *res )
358 {
359         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
360         metaconn_t              *mc = *mcp;
361         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
362
363         meta_search_candidate_t retcode = META_SEARCH_NOT_CANDIDATE;
364         int                     rc;
365
366         assert( msc->msc_ld != NULL );
367
368         /* FIXME: matched? referrals? response controls? */
369         rc = ldap_parse_result( msc->msc_ld, res,
370                 &candidates[ candidate ].sr_err,
371                 NULL, NULL, NULL, NULL, 0 );
372         if ( rc != LDAP_SUCCESS ) {
373                 candidates[ candidate ].sr_err = rc;
374
375         } else {
376                 rc = slap_map_api2result( &candidates[ candidate ] );
377         }
378
379         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
380         LDAP_BACK_CONN_BINDING_CLEAR( msc );
381         if ( rc != LDAP_SUCCESS ) {
382                 meta_clear_one_candidate( op, mc, candidate );
383                 candidates[ candidate ].sr_err = rc;
384                 if ( META_BACK_ONERR_STOP( mi ) ) {
385                         LDAP_BACK_CONN_TAINTED_SET( mc );
386                         meta_back_release_conn_lock( mi, mc, 0 );
387                         *mcp = NULL;
388                         retcode = META_SEARCH_ERR;
389                         rs->sr_err = rc;
390                 }
391
392         } else {
393                 /* FIXME: check if bound as idassert authcDN! */
394                 if ( BER_BVISNULL( &msc->msc_bound_ndn )
395                         || BER_BVISEMPTY( &msc->msc_bound_ndn ) )
396                 {
397                         LDAP_BACK_CONN_ISANON_SET( msc );
398
399                 } else {
400                         LDAP_BACK_CONN_ISBOUND_SET( msc );
401                 }
402                 retcode = META_SEARCH_CANDIDATE;
403
404                 /* connect must be async */
405                 ldap_set_option( msc->msc_ld, LDAP_OPT_CONNECT_ASYNC, LDAP_OPT_OFF );
406         }
407
408         candidates[ candidate ].sr_msgid = META_MSGID_IGNORE;
409         META_BINDING_CLEAR( &candidates[ candidate ] );
410
411         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
412
413         return retcode;
414 }
415
416 static meta_search_candidate_t
417 meta_back_search_start(
418         Operation               *op,
419         SlapReply               *rs,
420         dncookie                *dc,
421         metaconn_t              **mcp,
422         int                     candidate,
423         SlapReply               *candidates )
424 {
425         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
426         metatarget_t            *mt = mi->mi_targets[ candidate ];
427         metasingleconn_t        *msc = &(*mcp)->mc_conns[ candidate ];
428         struct berval           realbase = op->o_req_dn;
429         int                     realscope = op->ors_scope;
430         struct berval           mbase = BER_BVNULL; 
431         struct berval           mfilter = BER_BVNULL;
432         char                    **mapped_attrs = NULL;
433         int                     rc;
434         meta_search_candidate_t retcode;
435         struct timeval          tv, *tvp = NULL;
436         int                     nretries = 1;
437         LDAPControl             **ctrls = NULL;
438
439         /* this should not happen; just in case... */
440         if ( msc->msc_ld == NULL ) {
441                 Debug( LDAP_DEBUG_ANY,
442                         "%s: meta_back_search_start candidate=%d ld=NULL%s.\n",
443                         op->o_log_prefix, candidate,
444                         META_BACK_ONERR_STOP( mi ) ? "" : " (ignored)" );
445                 candidates[ candidate ].sr_err = LDAP_OTHER;
446                 if ( META_BACK_ONERR_STOP( mi ) ) {
447                         return META_SEARCH_ERR;
448                 }
449                 candidates[ candidate ].sr_msgid = META_MSGID_IGNORE;
450                 return META_SEARCH_NOT_CANDIDATE;
451         }
452
453         Debug( LDAP_DEBUG_TRACE, "%s >>> meta_back_search_start[%d]\n", op->o_log_prefix, candidate, 0 );
454
455         /*
456          * modifies the base according to the scope, if required
457          */
458         if ( mt->mt_nsuffix.bv_len > op->o_req_ndn.bv_len ) {
459                 switch ( op->ors_scope ) {
460                 case LDAP_SCOPE_SUBTREE:
461                         /*
462                          * make the target suffix the new base
463                          * FIXME: this is very forgiving, because
464                          * "illegal" searchBases may be turned
465                          * into the suffix of the target; however,
466                          * the requested searchBase already passed
467                          * thru the candidate analyzer...
468                          */
469                         if ( dnIsSuffix( &mt->mt_nsuffix, &op->o_req_ndn ) ) {
470                                 realbase = mt->mt_nsuffix;
471                                 if ( mt->mt_scope == LDAP_SCOPE_SUBORDINATE ) {
472                                         realscope = LDAP_SCOPE_SUBORDINATE;
473                                 }
474
475                         } else {
476                                 /*
477                                  * this target is no longer candidate
478                                  */
479                                 retcode = META_SEARCH_NOT_CANDIDATE;
480                                 goto doreturn;
481                         }
482                         break;
483
484                 case LDAP_SCOPE_SUBORDINATE:
485                 case LDAP_SCOPE_ONELEVEL:
486                 {
487                         struct berval   rdn = mt->mt_nsuffix;
488                         rdn.bv_len -= op->o_req_ndn.bv_len + STRLENOF( "," );
489                         if ( dnIsOneLevelRDN( &rdn )
490                                         && dnIsSuffix( &mt->mt_nsuffix, &op->o_req_ndn ) )
491                         {
492                                 /*
493                                  * if there is exactly one level,
494                                  * make the target suffix the new
495                                  * base, and make scope "base"
496                                  */
497                                 realbase = mt->mt_nsuffix;
498                                 if ( op->ors_scope == LDAP_SCOPE_SUBORDINATE ) {
499                                         if ( mt->mt_scope == LDAP_SCOPE_SUBORDINATE ) {
500                                                 realscope = LDAP_SCOPE_SUBORDINATE;
501                                         } else {
502                                                 realscope = LDAP_SCOPE_SUBTREE;
503                                         }
504                                 } else {
505                                         realscope = LDAP_SCOPE_BASE;
506                                 }
507                                 break;
508                         } /* else continue with the next case */
509                 }
510
511                 case LDAP_SCOPE_BASE:
512                         /*
513                          * this target is no longer candidate
514                          */
515                         retcode = META_SEARCH_NOT_CANDIDATE;
516                         goto doreturn;
517                 }
518         }
519
520         /* initiate dobind */
521         retcode = meta_search_dobind_init( op, rs, mcp, candidate, candidates );
522
523         Debug( LDAP_DEBUG_TRACE, "%s <<< meta_search_dobind_init[%d]=%d\n", op->o_log_prefix, candidate, retcode );
524
525         if ( retcode != META_SEARCH_CANDIDATE ) {
526                 goto doreturn;
527         }
528
529         /*
530          * Rewrite the search base, if required
531          */
532         dc->target = mt;
533         dc->ctx = "searchBase";
534         switch ( ldap_back_dn_massage( dc, &realbase, &mbase ) ) {
535         case LDAP_SUCCESS:
536                 break;
537
538         case LDAP_UNWILLING_TO_PERFORM:
539                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
540                 rs->sr_text = "Operation not allowed";
541                 send_ldap_result( op, rs );
542                 retcode = META_SEARCH_ERR;
543                 goto doreturn;
544
545         default:
546
547                 /*
548                  * this target is no longer candidate
549                  */
550                 retcode = META_SEARCH_NOT_CANDIDATE;
551                 goto doreturn;
552         }
553
554         /*
555          * Maps filter
556          */
557         rc = ldap_back_filter_map_rewrite( dc, op->ors_filter,
558                         &mfilter, BACKLDAP_MAP );
559         switch ( rc ) {
560         case LDAP_SUCCESS:
561                 break;
562
563         case LDAP_COMPARE_FALSE:
564         default:
565                 /*
566                  * this target is no longer candidate
567                  */
568                 retcode = META_SEARCH_NOT_CANDIDATE;
569                 goto done;
570         }
571
572         /*
573          * Maps required attributes
574          */
575         rc = ldap_back_map_attrs( &mt->mt_rwmap.rwm_at,
576                         op->ors_attrs, BACKLDAP_MAP, &mapped_attrs );
577         if ( rc != LDAP_SUCCESS ) {
578                 /*
579                  * this target is no longer candidate
580                  */
581                 retcode = META_SEARCH_NOT_CANDIDATE;
582                 goto done;
583         }
584
585         /* should we check return values? */
586         if ( op->ors_deref != -1 ) {
587                 assert( msc->msc_ld != NULL );
588                 (void)ldap_set_option( msc->msc_ld, LDAP_OPT_DEREF,
589                                 ( void * )&op->ors_deref );
590         }
591
592         if ( op->ors_tlimit != SLAP_NO_LIMIT ) {
593                 tv.tv_sec = op->ors_tlimit > 0 ? op->ors_tlimit : 1;
594                 tv.tv_usec = 0;
595                 tvp = &tv;
596         }
597
598 retry:;
599         ctrls = op->o_ctrls;
600         if ( ldap_back_proxy_authz_ctrl( &msc->msc_bound_ndn,
601                 mt->mt_version, &mt->mt_idassert, op, rs, &ctrls )
602                 != LDAP_SUCCESS )
603         {
604                 candidates[ candidate ].sr_msgid = META_MSGID_IGNORE;
605                 retcode = META_SEARCH_NOT_CANDIDATE;
606                 goto done;
607         }
608
609         /*
610          * Starts the search
611          */
612         assert( msc->msc_ld != NULL );
613         rc = ldap_search_ext( msc->msc_ld,
614                         mbase.bv_val, realscope, mfilter.bv_val,
615                         mapped_attrs, op->ors_attrsonly,
616                         ctrls, NULL, tvp, op->ors_slimit,
617                         &candidates[ candidate ].sr_msgid ); 
618         switch ( rc ) {
619         case LDAP_SUCCESS:
620                 retcode = META_SEARCH_CANDIDATE;
621                 break;
622         
623         case LDAP_SERVER_DOWN:
624                 if ( nretries && meta_back_retry( op, rs, mcp, candidate, LDAP_BACK_DONTSEND ) ) {
625                         nretries = 0;
626                         /* if the identity changed, there might be need to re-authz */
627                         (void)ldap_back_proxy_authz_ctrl_free( op, &ctrls );
628                         goto retry;
629                 }
630
631                 if ( *mcp == NULL ) {
632                         retcode = META_SEARCH_ERR;
633                         break;
634                 }
635                 /* fall thru */
636
637         default:
638                 candidates[ candidate ].sr_msgid = META_MSGID_IGNORE;
639                 retcode = META_SEARCH_NOT_CANDIDATE;
640         }
641
642 done:;
643         (void)ldap_back_proxy_authz_ctrl_free( op, &ctrls );
644
645         if ( mapped_attrs ) {
646                 free( mapped_attrs );
647         }
648         if ( mfilter.bv_val != op->ors_filterstr.bv_val ) {
649                 free( mfilter.bv_val );
650         }
651         if ( mbase.bv_val != realbase.bv_val ) {
652                 free( mbase.bv_val );
653         }
654
655 doreturn:;
656         Debug( LDAP_DEBUG_TRACE, "%s <<< meta_back_search_start[%d]=%d\n", op->o_log_prefix, candidate, retcode );
657
658         return retcode;
659 }
660
661 int
662 meta_back_search( Operation *op, SlapReply *rs )
663 {
664         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
665         metaconn_t      *mc;
666         struct timeval  save_tv = { 0, 0 },
667                         tv;
668         time_t          stoptime = (time_t)-1;
669         int             rc = 0, sres = LDAP_SUCCESS;
670         char            *matched = NULL;
671         int             last = 0, ncandidates = 0,
672                         initial_candidates = 0, candidate_match = 0,
673                         needbind = 0;
674         ldap_back_send_t        sendok = LDAP_BACK_SENDERR;
675         long            i;
676         dncookie        dc;
677         int             is_ok = 0;
678         void            *savepriv;
679         SlapReply       *candidates = meta_back_candidates_get( op );
680
681         /*
682          * controls are set in ldap_back_dobind()
683          * 
684          * FIXME: in case of values return filter, we might want
685          * to map attrs and maybe rewrite value
686          */
687 getconn:;
688         mc = meta_back_getconn( op, rs, NULL, sendok );
689         if ( !mc ) {
690                 return rs->sr_err;
691         }
692
693         dc.conn = op->o_conn;
694         dc.rs = rs;
695
696         /*
697          * Inits searches
698          */
699         for ( i = 0; i < mi->mi_ntargets; i++ ) {
700                 /* reset sr_msgid; it is used in most loops
701                  * to check if that target is still to be considered */
702                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
703
704                 /* a target is marked as candidate by meta_back_getconn();
705                  * if for any reason (an error, it's over or so) it is
706                  * no longer active, sr_msgid is set to META_MSGID_IGNORE
707                  * but it remains candidate, which means it has been active
708                  * at some point during the operation.  This allows to 
709                  * use its response code and more to compute the final
710                  * response */
711                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
712                         continue;
713                 }
714
715                 candidates[ i ].sr_matched = NULL;
716                 candidates[ i ].sr_text = NULL;
717                 candidates[ i ].sr_ref = NULL;
718                 candidates[ i ].sr_ctrls = NULL;
719         }
720
721         for ( i = 0; i < mi->mi_ntargets; i++ ) {
722                 if ( !META_IS_CANDIDATE( &candidates[ i ] )
723                         || candidates[ i ].sr_err != LDAP_SUCCESS )
724                 {
725                         continue;
726                 }
727
728                 switch ( meta_back_search_start( op, rs, &dc, &mc, i, candidates ) )
729                 {
730                 case META_SEARCH_NOT_CANDIDATE:
731                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
732                         break;
733
734                 case META_SEARCH_NEED_BIND:
735                         ++needbind;
736                         /* fallthru */
737
738                 case META_SEARCH_CONNECTING:
739                 case META_SEARCH_CANDIDATE:
740                 case META_SEARCH_BINDING:
741                         candidates[ i ].sr_type = REP_INTERMEDIATE;
742                         ++ncandidates;
743                         break;
744
745                 case META_SEARCH_ERR:
746                         savepriv = op->o_private;
747                         op->o_private = (void *)i;
748                         send_ldap_result( op, rs );
749                         op->o_private = savepriv;
750                         rc = -1;
751                         goto finish;
752
753                 default:
754                         assert( 0 );
755                         break;
756                 }
757         }
758
759         if ( ncandidates > 0 && needbind == ncandidates ) {
760                 /*
761                  * give up the second time...
762                  *
763                  * NOTE: this should not occur the second time, since a fresh
764                  * connection has ben created; however, targets may also
765                  * need bind because the bind timed out or so.
766                  */
767                 if ( sendok & LDAP_BACK_BINDING ) {
768                         Debug( LDAP_DEBUG_ANY,
769                                 "%s meta_back_search: unable to initialize conn\n",
770                                 op->o_log_prefix, 0, 0 );
771                         rs->sr_err = LDAP_UNAVAILABLE;
772                         rs->sr_text = "unable to initialize connection to remote targets";
773                         send_ldap_result( op, rs );
774                         rc = -1;
775                         goto finish;
776                 }
777
778                 /* FIXME: better create a separate connection? */
779                 sendok |= LDAP_BACK_BINDING;
780
781 #ifdef DEBUG_205
782                 Debug( LDAP_DEBUG_ANY, "*** %s drop mc=%p create new connection\n",
783                         op->o_log_prefix, (void *)mc, 0 );
784 #endif /* DEBUG_205 */
785
786                 meta_back_release_conn( mi, mc );
787                 mc = NULL;
788
789                 needbind = 0;
790                 ncandidates = 0;
791
792                 goto getconn;
793         }
794
795         initial_candidates = ncandidates;
796
797         if ( LogTest( LDAP_DEBUG_TRACE ) ) {
798                 char    cnd[ SLAP_TEXT_BUFLEN ];
799                 int     c;
800
801                 for ( c = 0; c < mi->mi_ntargets; c++ ) {
802                         if ( META_IS_CANDIDATE( &candidates[ c ] ) ) {
803                                 cnd[ c ] = '*';
804                         } else {
805                                 cnd[ c ] = ' ';
806                         }
807                 }
808                 cnd[ c ] = '\0';
809
810                 Debug( LDAP_DEBUG_TRACE, "%s meta_back_search: ncandidates=%d "
811                         "cnd=\"%s\"\n", op->o_log_prefix, ncandidates, cnd );
812         }
813
814         if ( initial_candidates == 0 ) {
815                 /* NOTE: here we are not sending any matchedDN;
816                  * this is intended, because if the back-meta
817                  * is serving this search request, but no valid
818                  * candidate could be looked up, it means that
819                  * there is a hole in the mapping of the targets
820                  * and thus no knowledge of any remote superior
821                  * is available */
822                 Debug( LDAP_DEBUG_ANY, "%s meta_back_search: "
823                         "base=\"%s\" scope=%d: "
824                         "no candidate could be selected\n",
825                         op->o_log_prefix, op->o_req_dn.bv_val,
826                         op->ors_scope );
827
828                 /* FIXME: we're sending the first error we encounter;
829                  * maybe we should pick the worst... */
830                 rc = LDAP_NO_SUCH_OBJECT;
831                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
832                         if ( META_IS_CANDIDATE( &candidates[ i ] )
833                                 && candidates[ i ].sr_err != LDAP_SUCCESS )
834                         {
835                                 rc = candidates[ i ].sr_err;
836                                 break;
837                         }
838                 }
839
840                 send_ldap_error( op, rs, rc, NULL );
841
842                 goto finish;
843         }
844
845         /* We pull apart the ber result, stuff it into a slapd entry, and
846          * let send_search_entry stuff it back into ber format. Slow & ugly,
847          * but this is necessary for version matching, and for ACL processing.
848          */
849
850         if ( op->ors_tlimit != SLAP_NO_LIMIT ) {
851                 stoptime = op->o_time + op->ors_tlimit;
852         }
853
854         /*
855          * In case there are no candidates, no cycle takes place...
856          *
857          * FIXME: we might use a queue, to better balance the load 
858          * among the candidates
859          */
860         for ( rc = 0; ncandidates > 0; ) {
861                 int     gotit = 0,
862                         doabandon = 0,
863                         alreadybound = ncandidates;
864
865                 /* check time limit */
866                 if ( op->ors_tlimit != SLAP_NO_LIMIT
867                                 && slap_get_time() > stoptime )
868                 {
869                         doabandon = 1;
870                         rc = rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
871                         savepriv = op->o_private;
872                         op->o_private = (void *)i;
873                         send_ldap_result( op, rs );
874                         op->o_private = savepriv;
875                         goto finish;
876                 }
877
878                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
879                         meta_search_candidate_t retcode = META_SEARCH_UNDEFINED;
880                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
881                         LDAPMessage             *res = NULL, *msg;
882
883                         /* if msgid is invalid, don't ldap_result() */
884                         if ( candidates[ i ].sr_msgid == META_MSGID_IGNORE ) {
885                                 continue;
886                         }
887
888                         /* if target still needs bind, retry */
889                         if ( candidates[ i ].sr_msgid == META_MSGID_NEED_BIND
890                                 || candidates[ i ].sr_msgid == META_MSGID_CONNECTING )
891                         {
892                                 /* initiate dobind */
893                                 retcode = meta_search_dobind_init( op, rs, &mc, i, candidates );
894
895                                 Debug( LDAP_DEBUG_TRACE, "%s <<< meta_search_dobind_init[%ld]=%d\n",
896                                         op->o_log_prefix, i, retcode );
897
898                                 switch ( retcode ) {
899                                 case META_SEARCH_NEED_BIND:
900                                         alreadybound--;
901                                         /* fallthru */
902
903                                 case META_SEARCH_CONNECTING:
904                                 case META_SEARCH_BINDING:
905                                         break;
906
907                                 case META_SEARCH_ERR:
908                                         candidates[ i ].sr_err = rs->sr_err;
909                                         if ( META_BACK_ONERR_STOP( mi ) ) {
910                                                 savepriv = op->o_private;
911                                                 op->o_private = (void *)i;
912                                                 send_ldap_result( op, rs );
913                                                 op->o_private = savepriv;
914                                                 goto finish;
915                                         }
916                                         /* fallthru */
917
918                                 case META_SEARCH_NOT_CANDIDATE:
919                                         /*
920                                          * When no candidates are left,
921                                          * the outer cycle finishes
922                                          */
923                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
924                                         assert( ncandidates > 0 );
925                                         --ncandidates;
926                                         break;
927
928                                 case META_SEARCH_CANDIDATE:
929                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
930                                         switch ( meta_back_search_start( op, rs, &dc, &mc, i, candidates ) )
931                                         {
932                                         case META_SEARCH_CANDIDATE:
933                                                 assert( candidates[ i ].sr_msgid >= 0 );
934                                                 break;
935
936                                         case META_SEARCH_ERR:
937                                                 candidates[ i ].sr_err = rs->sr_err;
938                                                 if ( META_BACK_ONERR_STOP( mi ) ) {
939                                                         savepriv = op->o_private;
940                                                         op->o_private = (void *)i;
941                                                         send_ldap_result( op, rs );
942                                                         op->o_private = savepriv;
943                                                         goto finish;
944                                                 }
945                                                 /* fallthru */
946
947                                         case META_SEARCH_NOT_CANDIDATE:
948                                                 /* means that meta_back_search_start()
949                                                  * failed but onerr == continue */
950                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
951                                                 assert( ncandidates > 0 );
952                                                 --ncandidates;
953                                                 break;
954
955                                         default:
956                                                 /* impossible */
957                                                 assert( 0 );
958                                                 break;
959                                         }
960                                         break;
961
962                                 default:
963                                         /* impossible */
964                                         assert( 0 );
965                                         break;
966                                 }
967                                 continue;
968                         }
969
970                         /* check for abandon */
971                         if ( op->o_abandon || LDAP_BACK_CONN_ABANDON( mc ) ) {
972                                 break;
973                         }
974
975 #ifdef DEBUG_205
976                         if ( msc->msc_ld == NULL ) {
977                                 char    buf[ SLAP_TEXT_BUFLEN ];
978
979                                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
980                                 snprintf( buf, sizeof( buf ),
981                                         "%s meta_back_search[%ld] mc=%p msgid=%d%s%s%s\n",
982                                         op->o_log_prefix, (long)i, (void *)mc,
983                                         candidates[ i ].sr_msgid,
984                                         META_IS_BINDING( &candidates[ i ] ) ? " binding" : "",
985                                         LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) ? " connbinding" : "",
986                                         META_BACK_CONN_CREATING( &mc->mc_conns[ i ] ) ? " conncreating" : "" );
987                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
988                                         
989                                 Debug( LDAP_DEBUG_ANY, "!!! %s\n", buf, 0, 0 );
990                         }
991 #endif /* DEBUG_205 */
992                         
993                         /*
994                          * FIXME: handle time limit as well?
995                          * Note that target servers are likely 
996                          * to handle it, so at some time we'll
997                          * get a LDAP_TIMELIMIT_EXCEEDED from
998                          * one of them ...
999                          */
1000                         tv = save_tv;
1001                         rc = ldap_result( msc->msc_ld, candidates[ i ].sr_msgid,
1002                                         LDAP_MSG_RECEIVED, &tv, &res );
1003                         switch ( rc ) {
1004                         case 0:
1005                                 /* FIXME: res should not need to be freed */
1006                                 assert( res == NULL );
1007                                 continue;
1008
1009                         case -1:
1010 really_bad:;
1011                                 /* something REALLY bad happened! */
1012                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1013                                         candidates[ i ].sr_type = REP_RESULT;
1014
1015                                         if ( meta_back_retry( op, rs, &mc, i, LDAP_BACK_DONTSEND ) ) {
1016                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1017                                                 switch ( meta_back_search_start( op, rs, &dc, &mc, i, candidates ) )
1018                                                 {
1019                                                         /* means that failed but onerr == continue */
1020                                                 case META_SEARCH_NOT_CANDIDATE:
1021                                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1022
1023                                                         assert( ncandidates > 0 );
1024                                                         --ncandidates;
1025
1026                                                         candidates[ i ].sr_err = rs->sr_err;
1027                                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1028                                                                 savepriv = op->o_private;
1029                                                                 op->o_private = (void *)i;
1030                                                                 send_ldap_result( op, rs );
1031                                                                 op->o_private = savepriv;
1032                                                                 goto finish;
1033                                                         }
1034                                                         /* fall thru */
1035
1036                                                 case META_SEARCH_CANDIDATE:
1037                                                         /* get back into business... */
1038                                                         continue;
1039
1040                                                 case META_SEARCH_BINDING:
1041                                                 case META_SEARCH_CONNECTING:
1042                                                 case META_SEARCH_NEED_BIND:
1043                                                 case META_SEARCH_UNDEFINED:
1044                                                         assert( 0 );
1045
1046                                                 default:
1047                                                         /* unrecoverable error */
1048                                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1049                                                         rc = rs->sr_err = LDAP_OTHER;
1050                                                         goto finish;
1051                                                 }
1052                                         }
1053
1054                                         candidates[ i ].sr_err = rs->sr_err;
1055                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1056                                                 savepriv = op->o_private;
1057                                                 op->o_private = (void *)i;
1058                                                 send_ldap_result( op, rs );
1059                                                 op->o_private = savepriv;
1060                                                 goto finish;
1061                                         }
1062                                 }
1063
1064                                 /*
1065                                  * When no candidates are left,
1066                                  * the outer cycle finishes
1067                                  */
1068                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1069                                 assert( ncandidates > 0 );
1070                                 --ncandidates;
1071                                 rs->sr_err = candidates[ i ].sr_err;
1072                                 continue;
1073
1074                         default:
1075                                 /* only touch when activity actually took place... */
1076                                 if ( mi->mi_idle_timeout != 0 && msc->msc_time < op->o_time ) {
1077                                         msc->msc_time = op->o_time;
1078                                 }
1079                                 break;
1080                         }
1081
1082                         for ( msg = ldap_first_message( msc->msc_ld, res );
1083                                 msg != NULL;
1084                                 msg = ldap_next_message( msc->msc_ld, msg ) )
1085                         {
1086                                 rc = ldap_msgtype( msg );
1087                                 if ( rc == LDAP_RES_SEARCH_ENTRY ) {
1088                                         LDAPMessage     *e;
1089
1090                                         if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1091                                                 /* don't retry any more... */
1092                                                 candidates[ i ].sr_type = REP_RESULT;
1093                                         }
1094
1095                                         is_ok++;
1096
1097                                         e = ldap_first_entry( msc->msc_ld, msg );
1098                                         savepriv = op->o_private;
1099                                         op->o_private = (void *)i;
1100                                         rs->sr_err = meta_send_entry( op, rs, mc, i, e );
1101
1102                                         switch ( rs->sr_err ) {
1103                                         case LDAP_SIZELIMIT_EXCEEDED:
1104                                                 savepriv = op->o_private;
1105                                                 op->o_private = (void *)i;
1106                                                 send_ldap_result( op, rs );
1107                                                 op->o_private = savepriv;
1108                                                 rs->sr_err = LDAP_SUCCESS;
1109                                                 ldap_msgfree( res );
1110                                                 res = NULL;
1111                                                 goto finish;
1112
1113                                         case LDAP_UNAVAILABLE:
1114                                                 rs->sr_err = LDAP_OTHER;
1115                                                 ldap_msgfree( res );
1116                                                 res = NULL;
1117                                                 goto finish;
1118                                         }
1119                                         op->o_private = savepriv;
1120
1121                                         /* don't wait any longer... */
1122                                         gotit = 1;
1123                                         save_tv.tv_sec = 0;
1124                                         save_tv.tv_usec = 0;
1125
1126                                 } else if ( rc == LDAP_RES_SEARCH_REFERENCE ) {
1127                                         char            **references = NULL;
1128                                         int             cnt;
1129
1130                                         if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1131                                                 /* don't retry any more... */
1132                                                 candidates[ i ].sr_type = REP_RESULT;
1133                                         }
1134         
1135                                         is_ok++;
1136         
1137                                         rc = ldap_parse_reference( msc->msc_ld, msg,
1138                                                         &references, &rs->sr_ctrls, 0 );
1139         
1140                                         if ( rc != LDAP_SUCCESS ) {
1141                                                 continue;
1142                                         }
1143         
1144                                         if ( references == NULL ) {
1145                                                 continue;
1146                                         }
1147
1148 #ifdef ENABLE_REWRITE
1149                                         dc.ctx = "referralDN";
1150 #else /* ! ENABLE_REWRITE */
1151                                         dc.tofrom = 0;
1152                                         dc.normalized = 0;
1153 #endif /* ! ENABLE_REWRITE */
1154
1155                                         /* FIXME: merge all and return at the end */
1156         
1157                                         for ( cnt = 0; references[ cnt ]; cnt++ )
1158                                                 ;
1159         
1160                                         rs->sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
1161         
1162                                         for ( cnt = 0; references[ cnt ]; cnt++ ) {
1163                                                 ber_str2bv( references[ cnt ], 0, 1, &rs->sr_ref[ cnt ] );
1164                                         }
1165                                         BER_BVZERO( &rs->sr_ref[ cnt ] );
1166         
1167                                         ( void )ldap_back_referral_result_rewrite( &dc, rs->sr_ref );
1168
1169                                         if ( rs->sr_ref != NULL && !BER_BVISNULL( &rs->sr_ref[ 0 ] ) ) {
1170                                                 /* ignore return value by now */
1171                                                 savepriv = op->o_private;
1172                                                 op->o_private = (void *)i;
1173                                                 ( void )send_search_reference( op, rs );
1174                                                 op->o_private = savepriv;
1175         
1176                                                 ber_bvarray_free( rs->sr_ref );
1177                                                 rs->sr_ref = NULL;
1178                                         }
1179
1180                                         /* cleanup */
1181                                         if ( references ) {
1182                                                 ber_memvfree( (void **)references );
1183                                         }
1184
1185                                         if ( rs->sr_ctrls ) {
1186                                                 ldap_controls_free( rs->sr_ctrls );
1187                                                 rs->sr_ctrls = NULL;
1188                                         }
1189
1190                                 } else if ( rc == LDAP_RES_SEARCH_RESULT ) {
1191                                         char            buf[ SLAP_TEXT_BUFLEN ];
1192                                         char            **references = NULL;
1193
1194                                         if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1195                                                 /* don't retry any more... */
1196                                                 candidates[ i ].sr_type = REP_RESULT;
1197                                         }
1198         
1199                                         /* NOTE: ignores response controls
1200                                          * (and intermediate response controls
1201                                          * as well, except for those with search
1202                                          * references); this may not be correct,
1203                                          * but if they're not ignored then
1204                                          * back-meta would need to merge them
1205                                          * consistently (think of pagedResults...)
1206                                          */
1207                                         /* FIXME: response controls? */
1208                                         rs->sr_err = ldap_parse_result( msc->msc_ld,
1209                                                 msg,
1210                                                 &candidates[ i ].sr_err,
1211                                                 (char **)&candidates[ i ].sr_matched,
1212                                                 NULL /* (char **)&candidates[ i ].sr_text */ ,
1213                                                 &references,
1214                                                 NULL /* &candidates[ i ].sr_ctrls (unused) */ ,
1215                                                 0 );
1216                                         if ( rs->sr_err != LDAP_SUCCESS ) {
1217                                                 ldap_get_option( msc->msc_ld,
1218                                                         LDAP_OPT_ERROR_NUMBER,
1219                                                         &rs->sr_err );
1220                                                 sres = slap_map_api2result( rs );
1221                                                 candidates[ i ].sr_type = REP_RESULT;
1222                                                 ldap_msgfree( res );
1223                                                 res = NULL;
1224                                                 goto really_bad;
1225                                         }
1226
1227                                         /* massage matchedDN if need be */
1228                                         if ( candidates[ i ].sr_matched != NULL ) {
1229                                                 struct berval   match, mmatch;
1230
1231                                                 ber_str2bv( candidates[ i ].sr_matched,
1232                                                         0, 0, &match );
1233                                                 candidates[ i ].sr_matched = NULL;
1234
1235                                                 dc.ctx = "matchedDN";
1236                                                 dc.target = mi->mi_targets[ i ];
1237                                                 if ( !ldap_back_dn_massage( &dc, &match, &mmatch ) ) {
1238                                                         if ( mmatch.bv_val == match.bv_val ) {
1239                                                                 candidates[ i ].sr_matched
1240                                                                         = ch_strdup( mmatch.bv_val );
1241
1242                                                         } else {
1243                                                                 candidates[ i ].sr_matched = mmatch.bv_val;
1244                                                         }
1245
1246                                                         candidate_match++;
1247                                                 } 
1248                                                 ldap_memfree( match.bv_val );
1249                                         }
1250
1251                                         /* add references to array */
1252                                         if ( references ) {
1253                                                 BerVarray       sr_ref;
1254                                                 int             cnt;
1255         
1256                                                 for ( cnt = 0; references[ cnt ]; cnt++ )
1257                                                         ;
1258         
1259                                                 sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
1260         
1261                                                 for ( cnt = 0; references[ cnt ]; cnt++ ) {
1262                                                         ber_str2bv( references[ cnt ], 0, 1, &sr_ref[ cnt ] );
1263                                                 }
1264                                                 BER_BVZERO( &sr_ref[ cnt ] );
1265         
1266                                                 ( void )ldap_back_referral_result_rewrite( &dc, sr_ref );
1267                                         
1268                                                 /* cleanup */
1269                                                 ber_memvfree( (void **)references );
1270         
1271                                                 if ( rs->sr_v2ref == NULL ) {
1272                                                         rs->sr_v2ref = sr_ref;
1273
1274                                                 } else {
1275                                                         for ( cnt = 0; !BER_BVISNULL( &sr_ref[ cnt ] ); cnt++ ) {
1276                                                                 ber_bvarray_add( &rs->sr_v2ref, &sr_ref[ cnt ] );
1277                                                         }
1278                                                         ber_memfree( sr_ref );
1279                                                 }
1280                                         }
1281         
1282                                         rs->sr_err = candidates[ i ].sr_err;
1283                                         sres = slap_map_api2result( rs );
1284         
1285                                         if ( LogTest( LDAP_DEBUG_TRACE | LDAP_DEBUG_ANY ) ) {
1286                                                 snprintf( buf, sizeof( buf ),
1287                                                         "%s meta_back_search[%ld] "
1288                                                         "match=\"%s\" err=%ld",
1289                                                         op->o_log_prefix, i,
1290                                                         candidates[ i ].sr_matched ? candidates[ i ].sr_matched : "",
1291                                                         (long) candidates[ i ].sr_err );
1292                                                 if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
1293                                                         Debug( LDAP_DEBUG_TRACE, "%s.\n", buf, 0, 0 );
1294         
1295                                                 } else {
1296                                                         Debug( LDAP_DEBUG_ANY, "%s (%s).\n",
1297                                                                 buf, ldap_err2string( candidates[ i ].sr_err ), 0 );
1298                                                 }
1299                                         }
1300         
1301                                         switch ( sres ) {
1302                                         case LDAP_NO_SUCH_OBJECT:
1303                                                 /* is_ok is touched any time a valid
1304                                                  * (even intermediate) result is
1305                                                  * returned; as a consequence, if
1306                                                  * a candidate returns noSuchObject
1307                                                  * it is ignored and the candidate
1308                                                  * is simply demoted. */
1309                                                 if ( is_ok ) {
1310                                                         sres = LDAP_SUCCESS;
1311                                                 }
1312                                                 break;
1313         
1314                                         case LDAP_SUCCESS:
1315                                         case LDAP_REFERRAL:
1316                                                 is_ok++;
1317                                                 break;
1318         
1319                                         case LDAP_SIZELIMIT_EXCEEDED:
1320                                                 /* if a target returned sizelimitExceeded
1321                                                  * and the entry count is equal to the
1322                                                  * proxy's limit, the target would have
1323                                                  * returned more, and the error must be
1324                                                  * propagated to the client; otherwise,
1325                                                  * the target enforced a limit lower
1326                                                  * than what requested by the proxy;
1327                                                  * ignore it */
1328                                                 candidates[ i ].sr_err = rs->sr_err;
1329                                                 if ( rs->sr_nentries == op->ors_slimit
1330                                                         || META_BACK_ONERR_STOP( mi ) )
1331                                                 {
1332                                                         savepriv = op->o_private;
1333                                                         op->o_private = (void *)i;
1334                                                         send_ldap_result( op, rs );
1335                                                         op->o_private = savepriv;
1336                                                         ldap_msgfree( res );
1337                                                         res = NULL;
1338                                                         goto finish;
1339                                                 }
1340                                                 break;
1341         
1342                                         default:
1343                                                 candidates[ i ].sr_err = rs->sr_err;
1344                                                 if ( META_BACK_ONERR_STOP( mi ) ) {
1345                                                         savepriv = op->o_private;
1346                                                         op->o_private = (void *)i;
1347                                                         send_ldap_result( op, rs );
1348                                                         op->o_private = savepriv;
1349                                                         ldap_msgfree( res );
1350                                                         res = NULL;
1351                                                         goto finish;
1352                                                 }
1353                                                 break;
1354                                         }
1355         
1356                                         last = i;
1357                                         rc = 0;
1358         
1359                                         /*
1360                                          * When no candidates are left,
1361                                          * the outer cycle finishes
1362                                          */
1363                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1364                                         assert( ncandidates > 0 );
1365                                         --ncandidates;
1366         
1367                                 } else if ( rc == LDAP_RES_BIND ) {
1368                                         meta_search_candidate_t retcode;
1369         
1370                                         retcode = meta_search_dobind_result( op, rs, &mc, i, candidates, msg );
1371                                         if ( retcode == META_SEARCH_CANDIDATE ) {
1372                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1373                                                 retcode = meta_back_search_start( op, rs, &dc, &mc, i, candidates );
1374                                         }
1375         
1376                                         switch ( retcode ) {
1377                                         case META_SEARCH_CANDIDATE:
1378                                                 break;
1379         
1380                                                 /* means that failed but onerr == continue */
1381                                         case META_SEARCH_NOT_CANDIDATE:
1382                                         case META_SEARCH_ERR:
1383                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1384                                                 assert( ncandidates > 0 );
1385                                                 --ncandidates;
1386         
1387                                                 candidates[ i ].sr_err = rs->sr_err;
1388                                                 if ( META_BACK_ONERR_STOP( mi ) ) {
1389                                                         savepriv = op->o_private;
1390                                                         op->o_private = (void *)i;
1391                                                         send_ldap_result( op, rs );
1392                                                         op->o_private = savepriv;
1393                                                         ldap_msgfree( res );
1394                                                         res = NULL;
1395                                                         goto finish;
1396                                                 }
1397                                                 goto free_message;
1398         
1399                                         default:
1400                                                 assert( 0 );
1401                                                 break;
1402                                         }
1403         
1404                                 } else {
1405                                         assert( 0 );
1406                                         ldap_msgfree( res );
1407                                         res = NULL;
1408                                         goto really_bad;
1409                                 }
1410                         }
1411
1412 free_message:;
1413                         ldap_msgfree( res );
1414                         res = NULL;
1415                 }
1416
1417                 /* check for abandon */
1418                 if ( op->o_abandon || LDAP_BACK_CONN_ABANDON( mc ) ) {
1419                         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1420                                 if ( candidates[ i ].sr_msgid >= 0 ) {
1421                                         if ( META_IS_BINDING( &candidates[ i ] ) ) {
1422                                                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1423                                                 if ( LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) ) {
1424                                                         /* if still binding, destroy */
1425
1426 #ifdef DEBUG_205
1427                                                         char buf[ SLAP_TEXT_BUFLEN ];
1428
1429                                                         snprintf( buf, sizeof( buf), "%s meta_back_search(abandon) "
1430                                                                 "ldap_unbind_ext[%ld] mc=%p ld=%p",
1431                                                                 op->o_log_prefix, i, (void *)mc,
1432                                                                 (void *)mc->mc_conns[i].msc_ld );
1433
1434                                                         Debug( LDAP_DEBUG_ANY, "### %s\n", buf, 0, 0 );
1435 #endif /* DEBUG_205 */
1436
1437                                                         meta_clear_one_candidate( op, mc, i );
1438                                                 }
1439                                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1440                                                 META_BINDING_CLEAR( &candidates[ i ] );
1441                                                 
1442                                         } else {
1443                                                 (void)meta_back_cancel( mc, op, rs,
1444                                                         candidates[ i ].sr_msgid, i,
1445                                                         LDAP_BACK_DONTSEND );
1446                                         }
1447
1448                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1449                                         assert( ncandidates > 0 );
1450                                         --ncandidates;
1451                                 }
1452                         }
1453
1454                         if ( op->o_abandon ) {
1455                                 rc = SLAPD_ABANDON;
1456                         }
1457
1458                         /* let send_ldap_result play cleanup handlers (ITS#4645) */
1459                         break;
1460                 }
1461
1462                 /* if no entry was found during this loop,
1463                  * set a minimal timeout */
1464                 if ( ncandidates > 0 && gotit == 0 ) {
1465                         if ( save_tv.tv_sec == 0 && save_tv.tv_usec == 0 ) {
1466                                 save_tv.tv_usec = LDAP_BACK_RESULT_UTIMEOUT/initial_candidates;
1467
1468                                 /* arbitrarily limit to something between 1 and 2 minutes */
1469                         } else if ( ( stoptime == -1 && save_tv.tv_sec < 60 )
1470                                 || save_tv.tv_sec < ( stoptime - slap_get_time() ) / ( 2 * ncandidates ) )
1471                         {
1472                                 /* double the timeout */
1473                                 lutil_timermul( &save_tv, 2, &save_tv );
1474                         }
1475
1476                         if ( alreadybound == 0 ) {
1477                                 tv = save_tv;
1478                                 (void)select( 0, NULL, NULL, NULL, &tv );
1479
1480                         } else {
1481                                 ldap_pvt_thread_yield();
1482                         }
1483                 }
1484         }
1485
1486         if ( rc == -1 ) {
1487                 /*
1488                  * FIXME: need a better strategy to handle errors
1489                  */
1490                 if ( mc ) {
1491                         rc = meta_back_op_result( mc, op, rs, META_TARGET_NONE,
1492                                 -1, stoptime != -1 ? (stoptime - slap_get_time()) : 0,
1493                                 LDAP_BACK_SENDERR );
1494                 } else {
1495                         rc = rs->sr_err;
1496                 }
1497                 goto finish;
1498         }
1499
1500         /*
1501          * Rewrite the matched portion of the search base, if required
1502          * 
1503          * FIXME: only the last one gets caught!
1504          */
1505         savepriv = op->o_private;
1506         op->o_private = (void *)(long)mi->mi_ntargets;
1507         if ( candidate_match > 0 ) {
1508                 struct berval   pmatched = BER_BVNULL;
1509
1510                 /* we use the first one */
1511                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1512                         if ( META_IS_CANDIDATE( &candidates[ i ] )
1513                                         && candidates[ i ].sr_matched != NULL )
1514                         {
1515                                 struct berval   bv, pbv;
1516                                 int             rc;
1517
1518                                 /* if we got success, and this target
1519                                  * returned noSuchObject, and its suffix
1520                                  * is a superior of the searchBase,
1521                                  * ignore the matchedDN */
1522                                 if ( sres == LDAP_SUCCESS
1523                                         && candidates[ i ].sr_err == LDAP_NO_SUCH_OBJECT
1524                                         && op->o_req_ndn.bv_len > mi->mi_targets[ i ]->mt_nsuffix.bv_len )
1525                                 {
1526                                         free( (char *)candidates[ i ].sr_matched );
1527                                         candidates[ i ].sr_matched = NULL;
1528                                         continue;
1529                                 }
1530
1531                                 ber_str2bv( candidates[ i ].sr_matched, 0, 0, &bv );
1532                                 rc = dnPretty( NULL, &bv, &pbv, op->o_tmpmemctx );
1533
1534                                 if ( rc == LDAP_SUCCESS ) {
1535
1536                                         /* NOTE: if they all are superiors
1537                                          * of the baseDN, the shorter is also 
1538                                          * superior of the longer... */
1539                                         if ( pbv.bv_len > pmatched.bv_len ) {
1540                                                 if ( !BER_BVISNULL( &pmatched ) ) {
1541                                                         op->o_tmpfree( pmatched.bv_val, op->o_tmpmemctx );
1542                                                 }
1543                                                 pmatched = pbv;
1544                                                 op->o_private = (void *)i;
1545
1546                                         } else {
1547                                                 op->o_tmpfree( pbv.bv_val, op->o_tmpmemctx );
1548                                         }
1549                                 }
1550
1551                                 if ( candidates[ i ].sr_matched != NULL ) {
1552                                         free( (char *)candidates[ i ].sr_matched );
1553                                         candidates[ i ].sr_matched = NULL;
1554                                 }
1555                         }
1556                 }
1557
1558                 if ( !BER_BVISNULL( &pmatched ) ) {
1559                         matched = pmatched.bv_val;
1560                 }
1561
1562         } else if ( sres == LDAP_NO_SUCH_OBJECT ) {
1563                 matched = op->o_bd->be_suffix[ 0 ].bv_val;
1564         }
1565
1566         /*
1567          * In case we returned at least one entry, we return LDAP_SUCCESS
1568          * otherwise, the latter error code we got
1569          */
1570
1571         if ( sres == LDAP_SUCCESS ) {
1572                 if ( rs->sr_v2ref ) {
1573                         sres = LDAP_REFERRAL;
1574                 }
1575
1576                 if ( META_BACK_ONERR_REPORT( mi ) ) {
1577                         /*
1578                          * Report errors, if any
1579                          *
1580                          * FIXME: we should handle error codes and return the more 
1581                          * important/reasonable
1582                          */
1583                         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1584                                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
1585                                         continue;
1586                                 }
1587
1588                                 if ( candidates[ i ].sr_err != LDAP_SUCCESS
1589                                         && candidates[ i ].sr_err != LDAP_NO_SUCH_OBJECT )
1590                                 {
1591                                         sres = candidates[ i ].sr_err;
1592                                         break;
1593                                 }
1594                         }
1595                 }
1596         }
1597
1598         rs->sr_err = sres;
1599         rs->sr_matched = matched;
1600         rs->sr_ref = ( sres == LDAP_REFERRAL ? rs->sr_v2ref : NULL );
1601         send_ldap_result( op, rs );
1602         op->o_private = savepriv;
1603         rs->sr_matched = NULL;
1604         rs->sr_ref = NULL;
1605
1606 finish:;
1607         if ( matched && matched != op->o_bd->be_suffix[ 0 ].bv_val ) {
1608                 op->o_tmpfree( matched, op->o_tmpmemctx );
1609         }
1610
1611         if ( rs->sr_v2ref ) {
1612                 ber_bvarray_free( rs->sr_v2ref );
1613         }
1614
1615         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1616                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
1617                         continue;
1618                 }
1619
1620                 if ( mc && META_IS_BINDING( &candidates[ i ] ) ) {
1621                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1622                         if ( LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) ) {
1623                                 assert( candidates[ i ].sr_msgid >= 0 );
1624                                 assert( mc->mc_conns[ i ].msc_ld != NULL );
1625
1626 #ifdef DEBUG_205
1627                                 Debug( LDAP_DEBUG_ANY, "### %s meta_back_search(cleanup) "
1628                                         "ldap_unbind_ext[%ld] ld=%p\n",
1629                                         op->o_log_prefix, i, (void *)mc->mc_conns[i].msc_ld );
1630 #endif /* DEBUG_205 */
1631
1632                                 /* if still binding, destroy */
1633                                 meta_clear_one_candidate( op, mc, i );
1634                         }
1635                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1636                         META_BINDING_CLEAR( &candidates[ i ] );
1637                 }
1638
1639                 if ( candidates[ i ].sr_matched ) {
1640                         free( (char *)candidates[ i ].sr_matched );
1641                         candidates[ i ].sr_matched = NULL;
1642                 }
1643
1644                 if ( candidates[ i ].sr_text ) {
1645                         ldap_memfree( (char *)candidates[ i ].sr_text );
1646                         candidates[ i ].sr_text = NULL;
1647                 }
1648
1649                 if ( candidates[ i ].sr_ref ) {
1650                         ber_bvarray_free( candidates[ i ].sr_ref );
1651                         candidates[ i ].sr_ref = NULL;
1652                 }
1653
1654                 if ( candidates[ i ].sr_ctrls ) {
1655                         ldap_controls_free( candidates[ i ].sr_ctrls );
1656                         candidates[ i ].sr_ctrls = NULL;
1657                 }
1658
1659                 if ( META_BACK_TGT_QUARANTINE( mi->mi_targets[ i ] ) ) {
1660                         meta_back_quarantine( op, &candidates[ i ], i );
1661                 }
1662
1663                 /* only in case of timelimit exceeded, if the timelimit exceeded because
1664                  * one contacted target never responded, invalidate the connection
1665                  * NOTE: should we quarantine the target as well?  right now, the connection
1666                  * is invalidated; the next time it will be recreated and the target
1667                  * will be quarantined if it cannot be contacted */
1668                 if ( mi->mi_idle_timeout != 0
1669                         && rs->sr_err == LDAP_TIMELIMIT_EXCEEDED
1670                         && op->o_time > mc->mc_conns[ i ].msc_time )
1671                 {
1672                         /* don't let anyone else use this expired connection */
1673                         LDAP_BACK_CONN_TAINTED_SET( mc );
1674                 }
1675         }
1676
1677         if ( mc ) {
1678                 meta_back_release_conn( mi, mc );
1679         }
1680
1681         return rs->sr_err;
1682 }
1683
1684 static int
1685 meta_send_entry(
1686         Operation       *op,
1687         SlapReply       *rs,
1688         metaconn_t      *mc,
1689         int             target,
1690         LDAPMessage     *e )
1691 {
1692         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
1693         struct berval           a, mapped;
1694         Entry                   ent = { 0 };
1695         BerElement              ber = *e->lm_ber;
1696         Attribute               *attr, **attrp;
1697         struct berval           bdn,
1698                                 dn = BER_BVNULL;
1699         const char              *text;
1700         dncookie                dc;
1701         int                     rc;
1702
1703         if ( ber_scanf( &ber, "{m{", &bdn ) == LBER_ERROR ) {
1704                 return LDAP_DECODING_ERROR;
1705         }
1706
1707         /*
1708          * Rewrite the dn of the result, if needed
1709          */
1710         dc.target = mi->mi_targets[ target ];
1711         dc.conn = op->o_conn;
1712         dc.rs = rs;
1713         dc.ctx = "searchResult";
1714
1715         rs->sr_err = ldap_back_dn_massage( &dc, &bdn, &dn );
1716         if ( rs->sr_err != LDAP_SUCCESS) {
1717                 return rs->sr_err;
1718         }
1719
1720         /*
1721          * Note: this may fail if the target host(s) schema differs
1722          * from the one known to the meta, and a DN with unknown
1723          * attributes is returned.
1724          * 
1725          * FIXME: should we log anything, or delegate to dnNormalize?
1726          */
1727         rc = dnPrettyNormal( NULL, &dn, &ent.e_name, &ent.e_nname,
1728                 op->o_tmpmemctx );
1729         if ( dn.bv_val != bdn.bv_val ) {
1730                 free( dn.bv_val );
1731         }
1732         BER_BVZERO( &dn );
1733
1734         if ( rc != LDAP_SUCCESS ) {
1735                 return LDAP_INVALID_DN_SYNTAX;
1736         }
1737
1738         /*
1739          * cache dn
1740          */
1741         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
1742                 ( void )meta_dncache_update_entry( &mi->mi_cache,
1743                                 &ent.e_nname, target );
1744         }
1745
1746         attrp = &ent.e_attrs;
1747
1748         dc.ctx = "searchAttrDN";
1749         while ( ber_scanf( &ber, "{m", &a ) != LBER_ERROR ) {
1750                 int                             last = 0;
1751                 slap_syntax_validate_func       *validate;
1752                 slap_syntax_transform_func      *pretty;
1753
1754                 ldap_back_map( &mi->mi_targets[ target ]->mt_rwmap.rwm_at, 
1755                                 &a, &mapped, BACKLDAP_REMAP );
1756                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0' ) {
1757                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1758                         continue;
1759                 }
1760                 attr = attr_alloc( NULL );
1761                 if ( attr == NULL ) {
1762                         continue;
1763                 }
1764                 if ( slap_bv2ad( &mapped, &attr->a_desc, &text )
1765                                 != LDAP_SUCCESS) {
1766                         if ( slap_bv2undef_ad( &mapped, &attr->a_desc, &text,
1767                                 SLAP_AD_PROXIED ) != LDAP_SUCCESS )
1768                         {
1769                                 char    buf[ SLAP_TEXT_BUFLEN ];
1770
1771                                 snprintf( buf, sizeof( buf ),
1772                                         "%s meta_send_entry(\"%s\"): "
1773                                         "slap_bv2undef_ad(%s): %s\n",
1774                                         op->o_log_prefix, ent.e_name.bv_val,
1775                                         mapped.bv_val, text );
1776
1777                                 Debug( LDAP_DEBUG_ANY, "%s", buf, 0, 0 );
1778                                 attr_free( attr );
1779                                 continue;
1780                         }
1781                 }
1782
1783                 /* no subschemaSubentry */
1784                 if ( attr->a_desc == slap_schema.si_ad_subschemaSubentry
1785                         || attr->a_desc == slap_schema.si_ad_entryDN )
1786                 {
1787
1788                         /* 
1789                          * We eat target's subschemaSubentry because
1790                          * a search for this value is likely not
1791                          * to resolve to the appropriate backend;
1792                          * later, the local subschemaSubentry is
1793                          * added.
1794                          *
1795                          * We also eat entryDN because the frontend
1796                          * will reattach it without checking if already
1797                          * present...
1798                          */
1799                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1800
1801                         attr_free(attr);
1802                         continue;
1803                 }
1804
1805                 if ( ber_scanf( &ber, "[W]", &attr->a_vals ) == LBER_ERROR 
1806                                 || attr->a_vals == NULL )
1807                 {
1808                         attr->a_vals = (struct berval *)&slap_dummy_bv;
1809
1810                 } else {
1811                         for ( last = 0; !BER_BVISNULL( &attr->a_vals[ last ] ); ++last )
1812                                 ;
1813                 }
1814
1815                 validate = attr->a_desc->ad_type->sat_syntax->ssyn_validate;
1816                 pretty = attr->a_desc->ad_type->sat_syntax->ssyn_pretty;
1817
1818                 if ( !validate && !pretty ) {
1819                         attr_free( attr );
1820                         goto next_attr;
1821                 }
1822
1823                 if ( attr->a_desc == slap_schema.si_ad_objectClass
1824                                 || attr->a_desc == slap_schema.si_ad_structuralObjectClass )
1825                 {
1826                         struct berval   *bv;
1827
1828                         for ( bv = attr->a_vals; !BER_BVISNULL( bv ); bv++ ) {
1829                                 ldap_back_map( &mi->mi_targets[ target ]->mt_rwmap.rwm_oc,
1830                                                 bv, &mapped, BACKLDAP_REMAP );
1831                                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0') {
1832                                         free( bv->bv_val );
1833                                         BER_BVZERO( bv );
1834                                         if ( --last < 0 ) {
1835                                                 break;
1836                                         }
1837                                         *bv = attr->a_vals[ last ];
1838                                         BER_BVZERO( &attr->a_vals[ last ] );
1839                                         bv--;
1840
1841                                 } else if ( mapped.bv_val != bv->bv_val ) {
1842                                         free( bv->bv_val );
1843                                         ber_dupbv( bv, &mapped );
1844                                 }
1845                         }
1846                 /*
1847                  * It is necessary to try to rewrite attributes with
1848                  * dn syntax because they might be used in ACLs as
1849                  * members of groups; since ACLs are applied to the
1850                  * rewritten stuff, no dn-based subecj clause could
1851                  * be used at the ldap backend side (see
1852                  * http://www.OpenLDAP.org/faq/data/cache/452.html)
1853                  * The problem can be overcome by moving the dn-based
1854                  * ACLs to the target directory server, and letting
1855                  * everything pass thru the ldap backend.
1856                  */
1857                 } else {
1858                         int     i;
1859
1860                         if ( attr->a_desc->ad_type->sat_syntax ==
1861                                 slap_schema.si_syn_distinguishedName )
1862                         {
1863                                 ldap_dnattr_result_rewrite( &dc, attr->a_vals );
1864
1865                         } else if ( attr->a_desc == slap_schema.si_ad_ref ) {
1866                                 ldap_back_referral_result_rewrite( &dc, attr->a_vals );
1867
1868                         }
1869
1870                         for ( i = 0; i < last; i++ ) {
1871                                 struct berval   pval;
1872                                 int             rc;
1873
1874                                 if ( pretty ) {
1875                                         rc = pretty( attr->a_desc->ad_type->sat_syntax,
1876                                                 &attr->a_vals[i], &pval, NULL );
1877
1878                                 } else {
1879                                         rc = validate( attr->a_desc->ad_type->sat_syntax,
1880                                                 &attr->a_vals[i] );
1881                                 }
1882
1883                                 if ( rc ) {
1884                                         LBER_FREE( attr->a_vals[i].bv_val );
1885                                         if ( --last == i ) {
1886                                                 BER_BVZERO( &attr->a_vals[ i ] );
1887                                                 break;
1888                                         }
1889                                         attr->a_vals[i] = attr->a_vals[last];
1890                                         BER_BVZERO( &attr->a_vals[last] );
1891                                         i--;
1892                                         continue;
1893                                 }
1894
1895                                 if ( pretty ) {
1896                                         LBER_FREE( attr->a_vals[i].bv_val );
1897                                         attr->a_vals[i] = pval;
1898                                 }
1899                         }
1900
1901                         if ( last == 0 && attr->a_vals != &slap_dummy_bv ) {
1902                                 attr_free( attr );
1903                                 goto next_attr;
1904                         }
1905                 }
1906
1907                 if ( last && attr->a_desc->ad_type->sat_equality &&
1908                         attr->a_desc->ad_type->sat_equality->smr_normalize )
1909                 {
1910                         int i;
1911
1912                         attr->a_nvals = ch_malloc( ( last + 1 ) * sizeof( struct berval ) );
1913                         for ( i = 0; i<last; i++ ) {
1914                                 attr->a_desc->ad_type->sat_equality->smr_normalize(
1915                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1916                                         attr->a_desc->ad_type->sat_syntax,
1917                                         attr->a_desc->ad_type->sat_equality,
1918                                         &attr->a_vals[i], &attr->a_nvals[i],
1919                                         NULL );
1920                         }
1921                         BER_BVZERO( &attr->a_nvals[i] );
1922
1923                 } else {
1924                         attr->a_nvals = attr->a_vals;
1925                 }
1926
1927                 *attrp = attr;
1928                 attrp = &attr->a_next;
1929 next_attr:;
1930         }
1931         rs->sr_entry = &ent;
1932         rs->sr_attrs = op->ors_attrs;
1933         rs->sr_flags = 0;
1934         rs->sr_err = LDAP_SUCCESS;
1935         rc = send_search_entry( op, rs );
1936         switch ( rc ) {
1937         case LDAP_UNAVAILABLE:
1938                 rc = LDAP_OTHER;
1939                 break;
1940         }
1941         rs->sr_entry = NULL;
1942         rs->sr_attrs = NULL;
1943         
1944         if ( !BER_BVISNULL( &ent.e_name ) ) {
1945                 free( ent.e_name.bv_val );
1946                 BER_BVZERO( &ent.e_name );
1947         }
1948         if ( !BER_BVISNULL( &ent.e_nname ) ) {
1949                 free( ent.e_nname.bv_val );
1950                 BER_BVZERO( &ent.e_nname );
1951         }
1952         entry_clean( &ent );
1953
1954         return rc;
1955 }
1956