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