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