]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/search.c
5d6c7ea471d6bd2ee82317ffc2ad0fe7384d8528
[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                         lastres_time = slap_get_time(),
654                         timeout = 0;
655         int             rc = 0, sres = LDAP_SUCCESS;
656         char            *matched = NULL;
657         int             last = 0, ncandidates = 0,
658                         initial_candidates = 0, candidate_match = 0,
659                         needbind = 0;
660         ldap_back_send_t        sendok = LDAP_BACK_SENDERR;
661         long            i;
662         dncookie        dc;
663         int             is_ok = 0;
664         void            *savepriv;
665         SlapReply       *candidates = meta_back_candidates_get( op );
666
667         /*
668          * controls are set in ldap_back_dobind()
669          * 
670          * FIXME: in case of values return filter, we might want
671          * to map attrs and maybe rewrite value
672          */
673 getconn:;
674         mc = meta_back_getconn( op, rs, NULL, sendok );
675         if ( !mc ) {
676                 return rs->sr_err;
677         }
678
679         dc.conn = op->o_conn;
680         dc.rs = rs;
681
682         /*
683          * Inits searches
684          */
685         for ( i = 0; i < mi->mi_ntargets; i++ ) {
686                 /* reset sr_msgid; it is used in most loops
687                  * to check if that target is still to be considered */
688                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
689
690                 /* a target is marked as candidate by meta_back_getconn();
691                  * if for any reason (an error, it's over or so) it is
692                  * no longer active, sr_msgid is set to META_MSGID_IGNORE
693                  * but it remains candidate, which means it has been active
694                  * at some point during the operation.  This allows to 
695                  * use its response code and more to compute the final
696                  * response */
697                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
698                         continue;
699                 }
700
701                 candidates[ i ].sr_matched = NULL;
702                 candidates[ i ].sr_text = NULL;
703                 candidates[ i ].sr_ref = NULL;
704                 candidates[ i ].sr_ctrls = NULL;
705
706                 /* get largest timeout among candidates */
707                 if ( mi->mi_targets[ i ]->mt_timeout[ SLAP_OP_SEARCH ]
708                         && mi->mi_targets[ i ]->mt_timeout[ SLAP_OP_SEARCH ] > timeout )
709                 {
710                         timeout = mi->mi_targets[ i ]->mt_timeout[ SLAP_OP_SEARCH ];
711                 }
712         }
713
714         for ( i = 0; i < mi->mi_ntargets; i++ ) {
715                 if ( !META_IS_CANDIDATE( &candidates[ i ] )
716                         || candidates[ i ].sr_err != LDAP_SUCCESS )
717                 {
718                         continue;
719                 }
720
721                 switch ( meta_back_search_start( op, rs, &dc, &mc, i, candidates ) )
722                 {
723                 case META_SEARCH_NOT_CANDIDATE:
724                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
725                         break;
726
727                 case META_SEARCH_NEED_BIND:
728                         ++needbind;
729                         /* fallthru */
730
731                 case META_SEARCH_CANDIDATE:
732                 case META_SEARCH_BINDING:
733                         candidates[ i ].sr_type = REP_INTERMEDIATE;
734                         ++ncandidates;
735                         break;
736
737                 case META_SEARCH_ERR:
738                         savepriv = op->o_private;
739                         op->o_private = (void *)i;
740                         send_ldap_result( op, rs );
741                         op->o_private = savepriv;
742                         rc = -1;
743                         goto finish;
744
745                 default:
746                         assert( 0 );
747                         break;
748                 }
749         }
750
751         if ( ncandidates > 0 && needbind == ncandidates ) {
752                 /*
753                  * give up the second time...
754                  *
755                  * NOTE: this should not occur the second time, since a fresh
756                  * connection has ben created; however, targets may also
757                  * need bind because the bind timed out or so.
758                  */
759                 if ( sendok & LDAP_BACK_BINDING ) {
760                         Debug( LDAP_DEBUG_ANY,
761                                 "%s meta_back_search: unable to initialize conn\n",
762                                 op->o_log_prefix, 0, 0 );
763                         rs->sr_err = LDAP_UNAVAILABLE;
764                         rs->sr_text = "unable to initialize connection to remote targets";
765                         send_ldap_result( op, rs );
766                         rc = -1;
767                         goto finish;
768                 }
769
770                 /* FIXME: better create a separate connection? */
771                 sendok |= LDAP_BACK_BINDING;
772
773 #ifdef DEBUG_205
774                 Debug( LDAP_DEBUG_ANY, "*** %s drop mc=%p create new connection\n",
775                         op->o_log_prefix, (void *)mc, 0 );
776 #endif /* DEBUG_205 */
777
778                 meta_back_release_conn( mi, mc );
779                 mc = NULL;
780
781                 needbind = 0;
782                 ncandidates = 0;
783
784                 goto getconn;
785         }
786
787         initial_candidates = ncandidates;
788
789         if ( StatslogTest( LDAP_DEBUG_TRACE ) ) {
790                 char    cnd[ SLAP_TEXT_BUFLEN ];
791                 int     c;
792
793                 for ( c = 0; c < mi->mi_ntargets; c++ ) {
794                         if ( META_IS_CANDIDATE( &candidates[ c ] ) ) {
795                                 cnd[ c ] = '*';
796                         } else {
797                                 cnd[ c ] = ' ';
798                         }
799                 }
800                 cnd[ c ] = '\0';
801
802                 Debug( LDAP_DEBUG_TRACE, "%s meta_back_search: ncandidates=%d "
803                         "cnd=\"%s\"\n", op->o_log_prefix, ncandidates, cnd );
804         }
805
806         if ( initial_candidates == 0 ) {
807                 /* NOTE: here we are not sending any matchedDN;
808                  * this is intended, because if the back-meta
809                  * is serving this search request, but no valid
810                  * candidate could be looked up, it means that
811                  * there is a hole in the mapping of the targets
812                  * and thus no knowledge of any remote superior
813                  * is available */
814                 Debug( LDAP_DEBUG_ANY, "%s meta_back_search: "
815                         "base=\"%s\" scope=%d: "
816                         "no candidate could be selected\n",
817                         op->o_log_prefix, op->o_req_dn.bv_val,
818                         op->ors_scope );
819
820                 /* FIXME: we're sending the first error we encounter;
821                  * maybe we should pick the worst... */
822                 rc = LDAP_NO_SUCH_OBJECT;
823                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
824                         if ( META_IS_CANDIDATE( &candidates[ i ] )
825                                 && candidates[ i ].sr_err != LDAP_SUCCESS )
826                         {
827                                 rc = candidates[ i ].sr_err;
828                                 break;
829                         }
830                 }
831
832                 send_ldap_error( op, rs, rc, NULL );
833
834                 goto finish;
835         }
836
837         /* We pull apart the ber result, stuff it into a slapd entry, and
838          * let send_search_entry stuff it back into ber format. Slow & ugly,
839          * but this is necessary for version matching, and for ACL processing.
840          */
841
842         if ( op->ors_tlimit != SLAP_NO_LIMIT ) {
843                 stoptime = op->o_time + op->ors_tlimit;
844         }
845
846         /*
847          * In case there are no candidates, no cycle takes place...
848          *
849          * FIXME: we might use a queue, to better balance the load 
850          * among the candidates
851          */
852         for ( rc = 0; ncandidates > 0; ) {
853                 int     gotit = 0,
854                         doabandon = 0,
855                         alreadybound = ncandidates;
856
857                 /* check timeout */
858                 if ( timeout && lastres_time > 0
859                         && ( slap_get_time() - lastres_time ) > timeout )
860                 {
861                         doabandon = 1;
862                         rs->sr_text = "Operation timed out";
863                         rc = rs->sr_err = op->o_protocol >= LDAP_VERSION3 ?
864                                 LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
865                         savepriv = op->o_private;
866                         op->o_private = (void *)i;
867                         send_ldap_result( op, rs );
868                         op->o_private = savepriv;
869                         goto finish;
870                 }
871
872                 /* check time limit */
873                 if ( op->ors_tlimit != SLAP_NO_LIMIT
874                                 && slap_get_time() > stoptime )
875                 {
876                         doabandon = 1;
877                         rc = rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
878                         savepriv = op->o_private;
879                         op->o_private = (void *)i;
880                         send_ldap_result( op, rs );
881                         op->o_private = savepriv;
882                         goto finish;
883                 }
884
885                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
886                         meta_search_candidate_t retcode = META_SEARCH_UNDEFINED;
887                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
888                         LDAPMessage             *res = NULL, *msg;
889
890                         /* if msgid is invalid, don't ldap_result() */
891                         if ( candidates[ i ].sr_msgid == META_MSGID_IGNORE ) {
892                                 continue;
893                         }
894
895                         /* if target still needs bind, retry */
896                         if ( candidates[ i ].sr_msgid == META_MSGID_NEED_BIND ) {
897                                 /* initiate dobind */
898                                 retcode = meta_search_dobind_init( op, rs, &mc, i, candidates );
899
900                                 Debug( LDAP_DEBUG_TRACE, "%s <<< meta_search_dobind_init[%ld]=%d\n",
901                                         op->o_log_prefix, i, retcode );
902
903                                 switch ( retcode ) {
904                                 case META_SEARCH_NEED_BIND:
905                                         alreadybound--;
906                                         /* fallthru */
907
908                                 case META_SEARCH_BINDING:
909                                         break;
910
911                                 case META_SEARCH_ERR:
912                                         candidates[ i ].sr_err = rs->sr_err;
913                                         if ( META_BACK_ONERR_STOP( mi ) ) {
914                                                 savepriv = op->o_private;
915                                                 op->o_private = (void *)i;
916                                                 send_ldap_result( op, rs );
917                                                 op->o_private = savepriv;
918                                                 goto finish;
919                                         }
920                                         /* fallthru */
921
922                                 case META_SEARCH_NOT_CANDIDATE:
923                                         /*
924                                          * When no candidates are left,
925                                          * the outer cycle finishes
926                                          */
927                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
928                                         assert( ncandidates > 0 );
929                                         --ncandidates;
930                                         break;
931
932                                 case META_SEARCH_CANDIDATE:
933                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
934                                         switch ( meta_back_search_start( op, rs, &dc, &mc, i, candidates ) )
935                                         {
936                                         case META_SEARCH_CANDIDATE:
937                                                 assert( candidates[ i ].sr_msgid >= 0 );
938                                                 break;
939
940                                         case META_SEARCH_ERR:
941                                                 candidates[ i ].sr_err = rs->sr_err;
942                                                 if ( META_BACK_ONERR_STOP( mi ) ) {
943                                                         savepriv = op->o_private;
944                                                         op->o_private = (void *)i;
945                                                         send_ldap_result( op, rs );
946                                                         op->o_private = savepriv;
947                                                         goto finish;
948                                                 }
949                                                 /* fallthru */
950
951                                         case META_SEARCH_NOT_CANDIDATE:
952                                                 /* means that meta_back_search_start()
953                                                  * failed but onerr == continue */
954                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
955                                                 assert( ncandidates > 0 );
956                                                 --ncandidates;
957                                                 break;
958
959                                         default:
960                                                 /* impossible */
961                                                 assert( 0 );
962                                                 break;
963                                         }
964                                         break;
965
966                                 default:
967                                         /* impossible */
968                                         assert( 0 );
969                                         break;
970                                 }
971                                 continue;
972                         }
973
974                         /* check for abandon */
975                         if ( op->o_abandon || LDAP_BACK_CONN_ABANDON( mc ) ) {
976                                 break;
977                         }
978
979 #ifdef DEBUG_205
980                         if ( msc->msc_ld == NULL ) {
981                                 char    buf[ SLAP_TEXT_BUFLEN ];
982
983                                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
984                                 snprintf( buf, sizeof( buf ),
985                                         "%s meta_back_search[%ld] mc=%p msgid=%d%s%s%s\n",
986                                         op->o_log_prefix, (long)i, (void *)mc,
987                                         candidates[ i ].sr_msgid,
988                                         META_IS_BINDING( &candidates[ i ] ) ? " binding" : "",
989                                         LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) ? " connbinding" : "",
990                                         META_BACK_CONN_CREATING( &mc->mc_conns[ i ] ) ? " conncreating" : "" );
991                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
992                                         
993                                 Debug( LDAP_DEBUG_ANY, "!!! %s\n", buf, 0, 0 );
994                         }
995 #endif /* DEBUG_205 */
996                         
997                         /*
998                          * FIXME: handle time limit as well?
999                          * Note that target servers are likely 
1000                          * to handle it, so at some time we'll
1001                          * get a LDAP_TIMELIMIT_EXCEEDED from
1002                          * one of them ...
1003                          */
1004                         tv = save_tv;
1005                         rc = ldap_result( msc->msc_ld, candidates[ i ].sr_msgid,
1006                                         LDAP_MSG_RECEIVED, &tv, &res );
1007                         switch ( rc ) {
1008                         case 0:
1009                                 /* FIXME: res should not need to be freed */
1010                                 assert( res == NULL );
1011                                 continue;
1012
1013                         case -1:
1014 really_bad:;
1015                                 /* something REALLY bad happened! */
1016                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1017                                         candidates[ i ].sr_type = REP_RESULT;
1018
1019                                         if ( meta_back_retry( op, rs, &mc, i, LDAP_BACK_DONTSEND ) ) {
1020                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1021                                                 switch ( meta_back_search_start( op, rs, &dc, &mc, i, candidates ) )
1022                                                 {
1023                                                         /* means that failed but onerr == continue */
1024                                                 case META_SEARCH_NOT_CANDIDATE:
1025                                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1026
1027                                                         assert( ncandidates > 0 );
1028                                                         --ncandidates;
1029
1030                                                         candidates[ i ].sr_err = rs->sr_err;
1031                                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1032                                                                 savepriv = op->o_private;
1033                                                                 op->o_private = (void *)i;
1034                                                                 send_ldap_result( op, rs );
1035                                                                 op->o_private = savepriv;
1036                                                                 goto finish;
1037                                                         }
1038                                                         /* fall thru */
1039
1040                                                 case META_SEARCH_CANDIDATE:
1041                                                         /* get back into business... */
1042                                                         continue;
1043
1044                                                 case META_SEARCH_BINDING:
1045                                                 case META_SEARCH_NEED_BIND:
1046                                                 case META_SEARCH_UNDEFINED:
1047                                                         assert( 0 );
1048
1049                                                 default:
1050                                                         /* unrecoverable error */
1051                                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1052                                                         rc = rs->sr_err = LDAP_OTHER;
1053                                                         goto finish;
1054                                                 }
1055                                         }
1056
1057                                         candidates[ i ].sr_err = rs->sr_err;
1058                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1059                                                 savepriv = op->o_private;
1060                                                 op->o_private = (void *)i;
1061                                                 send_ldap_result( op, rs );
1062                                                 op->o_private = savepriv;
1063                                                 goto finish;
1064                                         }
1065                                 }
1066
1067                                 /*
1068                                  * When no candidates are left,
1069                                  * the outer cycle finishes
1070                                  */
1071                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1072                                 assert( ncandidates > 0 );
1073                                 --ncandidates;
1074                                 rs->sr_err = candidates[ i ].sr_err;
1075                                 continue;
1076
1077                         default:
1078                                 lastres_time = slap_get_time();
1079
1080                                 /* only touch when activity actually took place... */
1081                                 if ( mi->mi_idle_timeout != 0 && msc->msc_time < lastres_time ) {
1082                                         msc->msc_time = lastres_time;
1083                                 }
1084                                 break;
1085                         }
1086
1087                         for ( msg = ldap_first_message( msc->msc_ld, res );
1088                                 msg != NULL;
1089                                 msg = ldap_next_message( msc->msc_ld, msg ) )
1090                         {
1091                                 rc = ldap_msgtype( msg );
1092                                 if ( rc == LDAP_RES_SEARCH_ENTRY ) {
1093                                         LDAPMessage     *e;
1094
1095                                         if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1096                                                 /* don't retry any more... */
1097                                                 candidates[ i ].sr_type = REP_RESULT;
1098                                         }
1099
1100                                         is_ok++;
1101
1102                                         e = ldap_first_entry( msc->msc_ld, msg );
1103                                         savepriv = op->o_private;
1104                                         op->o_private = (void *)i;
1105                                         rs->sr_err = meta_send_entry( op, rs, mc, i, e );
1106
1107                                         switch ( rs->sr_err ) {
1108                                         case LDAP_SIZELIMIT_EXCEEDED:
1109                                                 savepriv = op->o_private;
1110                                                 op->o_private = (void *)i;
1111                                                 send_ldap_result( op, rs );
1112                                                 op->o_private = savepriv;
1113                                                 rs->sr_err = LDAP_SUCCESS;
1114                                                 ldap_msgfree( res );
1115                                                 res = NULL;
1116                                                 goto finish;
1117
1118                                         case LDAP_UNAVAILABLE:
1119                                                 rs->sr_err = LDAP_OTHER;
1120                                                 ldap_msgfree( res );
1121                                                 res = NULL;
1122                                                 goto finish;
1123                                         }
1124                                         op->o_private = savepriv;
1125
1126                                         /* don't wait any longer... */
1127                                         gotit = 1;
1128                                         save_tv.tv_sec = 0;
1129                                         save_tv.tv_usec = 0;
1130
1131                                 } else if ( rc == LDAP_RES_SEARCH_REFERENCE ) {
1132                                         char            **references = NULL;
1133                                         int             cnt;
1134
1135                                         if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1136                                                 /* don't retry any more... */
1137                                                 candidates[ i ].sr_type = REP_RESULT;
1138                                         }
1139         
1140                                         is_ok++;
1141         
1142                                         rc = ldap_parse_reference( msc->msc_ld, msg,
1143                                                         &references, &rs->sr_ctrls, 0 );
1144         
1145                                         if ( rc != LDAP_SUCCESS ) {
1146                                                 continue;
1147                                         }
1148         
1149                                         if ( references == NULL ) {
1150                                                 continue;
1151                                         }
1152
1153 #ifdef ENABLE_REWRITE
1154                                         dc.ctx = "referralDN";
1155 #else /* ! ENABLE_REWRITE */
1156                                         dc.tofrom = 0;
1157                                         dc.normalized = 0;
1158 #endif /* ! ENABLE_REWRITE */
1159
1160                                         /* FIXME: merge all and return at the end */
1161         
1162                                         for ( cnt = 0; references[ cnt ]; cnt++ )
1163                                                 ;
1164         
1165                                         rs->sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
1166         
1167                                         for ( cnt = 0; references[ cnt ]; cnt++ ) {
1168                                                 ber_str2bv( references[ cnt ], 0, 1, &rs->sr_ref[ cnt ] );
1169                                         }
1170                                         BER_BVZERO( &rs->sr_ref[ cnt ] );
1171         
1172                                         ( void )ldap_back_referral_result_rewrite( &dc, rs->sr_ref );
1173
1174                                         if ( rs->sr_ref != NULL && !BER_BVISNULL( &rs->sr_ref[ 0 ] ) ) {
1175                                                 /* ignore return value by now */
1176                                                 savepriv = op->o_private;
1177                                                 op->o_private = (void *)i;
1178                                                 ( void )send_search_reference( op, rs );
1179                                                 op->o_private = savepriv;
1180         
1181                                                 ber_bvarray_free( rs->sr_ref );
1182                                                 rs->sr_ref = NULL;
1183                                         }
1184
1185                                         /* cleanup */
1186                                         if ( references ) {
1187                                                 ber_memvfree( (void **)references );
1188                                         }
1189
1190                                         if ( rs->sr_ctrls ) {
1191                                                 ldap_controls_free( rs->sr_ctrls );
1192                                                 rs->sr_ctrls = NULL;
1193                                         }
1194
1195                                 } else if ( rc == LDAP_RES_SEARCH_RESULT ) {
1196                                         char            buf[ SLAP_TEXT_BUFLEN ];
1197                                         char            **references = NULL;
1198
1199                                         if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
1200                                                 /* don't retry any more... */
1201                                                 candidates[ i ].sr_type = REP_RESULT;
1202                                         }
1203         
1204                                         /* NOTE: ignores response controls
1205                                          * (and intermediate response controls
1206                                          * as well, except for those with search
1207                                          * references); this may not be correct,
1208                                          * but if they're not ignored then
1209                                          * back-meta would need to merge them
1210                                          * consistently (think of pagedResults...)
1211                                          */
1212                                         /* FIXME: response controls? */
1213                                         rs->sr_err = ldap_parse_result( msc->msc_ld,
1214                                                 msg,
1215                                                 &candidates[ i ].sr_err,
1216                                                 (char **)&candidates[ i ].sr_matched,
1217                                                 NULL /* (char **)&candidates[ i ].sr_text */ ,
1218                                                 &references,
1219                                                 NULL /* &candidates[ i ].sr_ctrls (unused) */ ,
1220                                                 0 );
1221                                         if ( rs->sr_err != LDAP_SUCCESS ) {
1222                                                 sres = slap_map_api2result( &candidates[ i ] );
1223                                                 candidates[ i ].sr_type = REP_RESULT;
1224                                                 ldap_msgfree( res );
1225                                                 res = NULL;
1226                                                 goto really_bad;
1227                                         }
1228
1229                                         rs->sr_err = candidates[ i ].sr_err;
1230
1231                                         /* massage matchedDN if need be */
1232                                         if ( candidates[ i ].sr_matched != NULL ) {
1233                                                 struct berval   match, mmatch;
1234
1235                                                 ber_str2bv( candidates[ i ].sr_matched,
1236                                                         0, 0, &match );
1237                                                 candidates[ i ].sr_matched = NULL;
1238
1239                                                 dc.ctx = "matchedDN";
1240                                                 dc.target = mi->mi_targets[ i ];
1241                                                 if ( !ldap_back_dn_massage( &dc, &match, &mmatch ) ) {
1242                                                         if ( mmatch.bv_val == match.bv_val ) {
1243                                                                 candidates[ i ].sr_matched
1244                                                                         = ch_strdup( mmatch.bv_val );
1245
1246                                                         } else {
1247                                                                 candidates[ i ].sr_matched = mmatch.bv_val;
1248                                                         }
1249
1250                                                         candidate_match++;
1251                                                 } 
1252                                                 ldap_memfree( match.bv_val );
1253                                         }
1254
1255                                         /* add references to array */
1256                                         /* RFC 4511: referrals can only appear
1257                                          * if result code is LDAP_REFERRAL */
1258                                         if ( references != NULL
1259                                                 && references[ 0 ] != NULL
1260                                                 && references[ 0 ][ 0 ] != '\0' )
1261                                         {
1262                                                 if ( rs->sr_err != LDAP_REFERRAL ) {
1263                                                         Debug( LDAP_DEBUG_ANY,
1264                                                                 "%s meta_back_search[%ld]: "
1265                                                                 "got referrals with err=%d\n",
1266                                                                 op->o_log_prefix,
1267                                                                 i, rs->sr_err );
1268
1269                                                 } else {
1270                                                         BerVarray       sr_ref;
1271                                                         int             cnt;
1272         
1273                                                         for ( cnt = 0; references[ cnt ]; cnt++ )
1274                                                                 ;
1275         
1276                                                         sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
1277         
1278                                                         for ( cnt = 0; references[ cnt ]; cnt++ ) {
1279                                                                 ber_str2bv( references[ cnt ], 0, 1, &sr_ref[ cnt ] );
1280                                                         }
1281                                                         BER_BVZERO( &sr_ref[ cnt ] );
1282         
1283                                                         ( void )ldap_back_referral_result_rewrite( &dc, sr_ref );
1284                                         
1285                                                         if ( rs->sr_v2ref == NULL ) {
1286                                                                 rs->sr_v2ref = sr_ref;
1287
1288                                                         } else {
1289                                                                 for ( cnt = 0; !BER_BVISNULL( &sr_ref[ cnt ] ); cnt++ ) {
1290                                                                         ber_bvarray_add( &rs->sr_v2ref, &sr_ref[ cnt ] );
1291                                                                 }
1292                                                                 ber_memfree( sr_ref );
1293                                                         }
1294                                                 }
1295
1296                                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
1297                                                 Debug( LDAP_DEBUG_ANY,
1298                                                         "%s meta_back_search[%ld]: "
1299                                                         "got err=%d with null "
1300                                                         "or empty referrals\n",
1301                                                         op->o_log_prefix,
1302                                                         i, rs->sr_err );
1303
1304                                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
1305                                         }
1306
1307                                         /* cleanup */
1308                                         ber_memvfree( (void **)references );
1309         
1310                                         sres = slap_map_api2result( rs );
1311         
1312                                         if ( StatslogTest( LDAP_DEBUG_TRACE | LDAP_DEBUG_ANY ) ) {
1313                                                 snprintf( buf, sizeof( buf ),
1314                                                         "%s meta_back_search[%ld] "
1315                                                         "match=\"%s\" err=%ld",
1316                                                         op->o_log_prefix, i,
1317                                                         candidates[ i ].sr_matched ? candidates[ i ].sr_matched : "",
1318                                                         (long) candidates[ i ].sr_err );
1319                                                 if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
1320                                                         Debug( LDAP_DEBUG_TRACE, "%s.\n", buf, 0, 0 );
1321         
1322                                                 } else {
1323                                                         Debug( LDAP_DEBUG_ANY, "%s (%s).\n",
1324                                                                 buf, ldap_err2string( candidates[ i ].sr_err ), 0 );
1325                                                 }
1326                                         }
1327         
1328                                         switch ( sres ) {
1329                                         case LDAP_NO_SUCH_OBJECT:
1330                                                 /* is_ok is touched any time a valid
1331                                                  * (even intermediate) result is
1332                                                  * returned; as a consequence, if
1333                                                  * a candidate returns noSuchObject
1334                                                  * it is ignored and the candidate
1335                                                  * is simply demoted. */
1336                                                 if ( is_ok ) {
1337                                                         sres = LDAP_SUCCESS;
1338                                                 }
1339                                                 break;
1340         
1341                                         case LDAP_SUCCESS:
1342                                         case LDAP_REFERRAL:
1343                                                 is_ok++;
1344                                                 break;
1345         
1346                                         case LDAP_SIZELIMIT_EXCEEDED:
1347                                                 /* if a target returned sizelimitExceeded
1348                                                  * and the entry count is equal to the
1349                                                  * proxy's limit, the target would have
1350                                                  * returned more, and the error must be
1351                                                  * propagated to the client; otherwise,
1352                                                  * the target enforced a limit lower
1353                                                  * than what requested by the proxy;
1354                                                  * ignore it */
1355                                                 candidates[ i ].sr_err = rs->sr_err;
1356                                                 if ( rs->sr_nentries == op->ors_slimit
1357                                                         || META_BACK_ONERR_STOP( mi ) )
1358                                                 {
1359                                                         savepriv = op->o_private;
1360                                                         op->o_private = (void *)i;
1361                                                         send_ldap_result( op, rs );
1362                                                         op->o_private = savepriv;
1363                                                         ldap_msgfree( res );
1364                                                         res = NULL;
1365                                                         goto finish;
1366                                                 }
1367                                                 break;
1368         
1369                                         default:
1370                                                 candidates[ i ].sr_err = rs->sr_err;
1371                                                 if ( META_BACK_ONERR_STOP( mi ) ) {
1372                                                         savepriv = op->o_private;
1373                                                         op->o_private = (void *)i;
1374                                                         send_ldap_result( op, rs );
1375                                                         op->o_private = savepriv;
1376                                                         ldap_msgfree( res );
1377                                                         res = NULL;
1378                                                         goto finish;
1379                                                 }
1380                                                 break;
1381                                         }
1382         
1383                                         last = i;
1384                                         rc = 0;
1385         
1386                                         /*
1387                                          * When no candidates are left,
1388                                          * the outer cycle finishes
1389                                          */
1390                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1391                                         assert( ncandidates > 0 );
1392                                         --ncandidates;
1393         
1394                                 } else if ( rc == LDAP_RES_BIND ) {
1395                                         meta_search_candidate_t retcode;
1396         
1397                                         retcode = meta_search_dobind_result( op, rs, &mc, i, candidates, msg );
1398                                         if ( retcode == META_SEARCH_CANDIDATE ) {
1399                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1400                                                 retcode = meta_back_search_start( op, rs, &dc, &mc, i, candidates );
1401                                         }
1402         
1403                                         switch ( retcode ) {
1404                                         case META_SEARCH_CANDIDATE:
1405                                                 break;
1406         
1407                                                 /* means that failed but onerr == continue */
1408                                         case META_SEARCH_NOT_CANDIDATE:
1409                                         case META_SEARCH_ERR:
1410                                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1411                                                 assert( ncandidates > 0 );
1412                                                 --ncandidates;
1413         
1414                                                 candidates[ i ].sr_err = rs->sr_err;
1415                                                 if ( META_BACK_ONERR_STOP( mi ) ) {
1416                                                         savepriv = op->o_private;
1417                                                         op->o_private = (void *)i;
1418                                                         send_ldap_result( op, rs );
1419                                                         op->o_private = savepriv;
1420                                                         ldap_msgfree( res );
1421                                                         res = NULL;
1422                                                         goto finish;
1423                                                 }
1424                                                 goto free_message;
1425         
1426                                         default:
1427                                                 assert( 0 );
1428                                                 break;
1429                                         }
1430         
1431                                 } else {
1432                                         assert( 0 );
1433                                         ldap_msgfree( res );
1434                                         res = NULL;
1435                                         goto really_bad;
1436                                 }
1437                         }
1438
1439 free_message:;
1440                         ldap_msgfree( res );
1441                         res = NULL;
1442                 }
1443
1444                 /* check for abandon */
1445                 if ( op->o_abandon || LDAP_BACK_CONN_ABANDON( mc ) ) {
1446                         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1447                                 if ( candidates[ i ].sr_msgid >= 0 ) {
1448                                         if ( META_IS_BINDING( &candidates[ i ] ) ) {
1449                                                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1450                                                 if ( LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) ) {
1451                                                         /* if still binding, destroy */
1452
1453 #ifdef DEBUG_205
1454                                                         char buf[ SLAP_TEXT_BUFLEN ];
1455
1456                                                         snprintf( buf, sizeof( buf), "%s meta_back_search(abandon) "
1457                                                                 "ldap_unbind_ext[%ld] mc=%p ld=%p",
1458                                                                 op->o_log_prefix, i, (void *)mc,
1459                                                                 (void *)mc->mc_conns[i].msc_ld );
1460
1461                                                         Debug( LDAP_DEBUG_ANY, "### %s\n", buf, 0, 0 );
1462 #endif /* DEBUG_205 */
1463
1464                                                         meta_clear_one_candidate( op, mc, i );
1465                                                 }
1466                                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1467                                                 META_BINDING_CLEAR( &candidates[ i ] );
1468                                                 
1469                                         } else {
1470                                                 (void)meta_back_cancel( mc, op, rs,
1471                                                         candidates[ i ].sr_msgid, i,
1472                                                         LDAP_BACK_DONTSEND );
1473                                         }
1474
1475                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1476                                         assert( ncandidates > 0 );
1477                                         --ncandidates;
1478                                 }
1479                         }
1480
1481                         if ( op->o_abandon ) {
1482                                 rc = SLAPD_ABANDON;
1483                         }
1484
1485                         /* let send_ldap_result play cleanup handlers (ITS#4645) */
1486                         break;
1487                 }
1488
1489                 /* if no entry was found during this loop,
1490                  * set a minimal timeout */
1491                 if ( ncandidates > 0 && gotit == 0 ) {
1492                         if ( save_tv.tv_sec == 0 && save_tv.tv_usec == 0 ) {
1493                                 save_tv.tv_usec = LDAP_BACK_RESULT_UTIMEOUT/initial_candidates;
1494
1495                                 /* arbitrarily limit to something between 1 and 2 minutes */
1496                         } else if ( ( stoptime == -1 && save_tv.tv_sec < 60 )
1497                                 || save_tv.tv_sec < ( stoptime - slap_get_time() ) / ( 2 * ncandidates ) )
1498                         {
1499                                 /* double the timeout */
1500                                 lutil_timermul( &save_tv, 2, &save_tv );
1501                         }
1502
1503                         if ( alreadybound == 0 ) {
1504                                 tv = save_tv;
1505                                 (void)select( 0, NULL, NULL, NULL, &tv );
1506
1507                         } else {
1508                                 ldap_pvt_thread_yield();
1509                         }
1510                 }
1511         }
1512
1513         if ( rc == -1 ) {
1514                 /*
1515                  * FIXME: need a better strategy to handle errors
1516                  */
1517                 if ( mc ) {
1518                         rc = meta_back_op_result( mc, op, rs, META_TARGET_NONE,
1519                                 -1, stoptime != -1 ? (stoptime - slap_get_time()) : 0,
1520                                 LDAP_BACK_SENDERR );
1521                 } else {
1522                         rc = rs->sr_err;
1523                 }
1524                 goto finish;
1525         }
1526
1527         /*
1528          * Rewrite the matched portion of the search base, if required
1529          * 
1530          * FIXME: only the last one gets caught!
1531          */
1532         savepriv = op->o_private;
1533         op->o_private = (void *)(long)mi->mi_ntargets;
1534         if ( candidate_match > 0 ) {
1535                 struct berval   pmatched = BER_BVNULL;
1536
1537                 /* we use the first one */
1538                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1539                         if ( META_IS_CANDIDATE( &candidates[ i ] )
1540                                         && candidates[ i ].sr_matched != NULL )
1541                         {
1542                                 struct berval   bv, pbv;
1543                                 int             rc;
1544
1545                                 /* if we got success, and this target
1546                                  * returned noSuchObject, and its suffix
1547                                  * is a superior of the searchBase,
1548                                  * ignore the matchedDN */
1549                                 if ( sres == LDAP_SUCCESS
1550                                         && candidates[ i ].sr_err == LDAP_NO_SUCH_OBJECT
1551                                         && op->o_req_ndn.bv_len > mi->mi_targets[ i ]->mt_nsuffix.bv_len )
1552                                 {
1553                                         free( (char *)candidates[ i ].sr_matched );
1554                                         candidates[ i ].sr_matched = NULL;
1555                                         continue;
1556                                 }
1557
1558                                 ber_str2bv( candidates[ i ].sr_matched, 0, 0, &bv );
1559                                 rc = dnPretty( NULL, &bv, &pbv, op->o_tmpmemctx );
1560
1561                                 if ( rc == LDAP_SUCCESS ) {
1562
1563                                         /* NOTE: if they all are superiors
1564                                          * of the baseDN, the shorter is also 
1565                                          * superior of the longer... */
1566                                         if ( pbv.bv_len > pmatched.bv_len ) {
1567                                                 if ( !BER_BVISNULL( &pmatched ) ) {
1568                                                         op->o_tmpfree( pmatched.bv_val, op->o_tmpmemctx );
1569                                                 }
1570                                                 pmatched = pbv;
1571                                                 op->o_private = (void *)i;
1572
1573                                         } else {
1574                                                 op->o_tmpfree( pbv.bv_val, op->o_tmpmemctx );
1575                                         }
1576                                 }
1577
1578                                 if ( candidates[ i ].sr_matched != NULL ) {
1579                                         free( (char *)candidates[ i ].sr_matched );
1580                                         candidates[ i ].sr_matched = NULL;
1581                                 }
1582                         }
1583                 }
1584
1585                 if ( !BER_BVISNULL( &pmatched ) ) {
1586                         matched = pmatched.bv_val;
1587                 }
1588
1589         } else if ( sres == LDAP_NO_SUCH_OBJECT ) {
1590                 matched = op->o_bd->be_suffix[ 0 ].bv_val;
1591         }
1592
1593         /*
1594          * In case we returned at least one entry, we return LDAP_SUCCESS
1595          * otherwise, the latter error code we got
1596          */
1597
1598         if ( sres == LDAP_SUCCESS ) {
1599                 if ( rs->sr_v2ref ) {
1600                         sres = LDAP_REFERRAL;
1601                 }
1602
1603                 if ( META_BACK_ONERR_REPORT( mi ) ) {
1604                         /*
1605                          * Report errors, if any
1606                          *
1607                          * FIXME: we should handle error codes and return the more 
1608                          * important/reasonable
1609                          */
1610                         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1611                                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
1612                                         continue;
1613                                 }
1614
1615                                 if ( candidates[ i ].sr_err != LDAP_SUCCESS
1616                                         && candidates[ i ].sr_err != LDAP_NO_SUCH_OBJECT )
1617                                 {
1618                                         sres = candidates[ i ].sr_err;
1619                                         break;
1620                                 }
1621                         }
1622                 }
1623         }
1624
1625         rs->sr_err = sres;
1626         rs->sr_matched = matched;
1627         rs->sr_ref = ( sres == LDAP_REFERRAL ? rs->sr_v2ref : NULL );
1628         send_ldap_result( op, rs );
1629         op->o_private = savepriv;
1630         rs->sr_matched = NULL;
1631         rs->sr_ref = NULL;
1632
1633 finish:;
1634         if ( matched && matched != op->o_bd->be_suffix[ 0 ].bv_val ) {
1635                 op->o_tmpfree( matched, op->o_tmpmemctx );
1636         }
1637
1638         if ( rs->sr_v2ref ) {
1639                 ber_bvarray_free( rs->sr_v2ref );
1640         }
1641
1642         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1643                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
1644                         continue;
1645                 }
1646
1647                 if ( mc && META_IS_BINDING( &candidates[ i ] ) ) {
1648                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1649                         if ( LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) ) {
1650                                 assert( candidates[ i ].sr_msgid >= 0 );
1651                                 assert( mc->mc_conns[ i ].msc_ld != NULL );
1652
1653 #ifdef DEBUG_205
1654                                 Debug( LDAP_DEBUG_ANY, "### %s meta_back_search(cleanup) "
1655                                         "ldap_unbind_ext[%ld] ld=%p\n",
1656                                         op->o_log_prefix, i, (void *)mc->mc_conns[i].msc_ld );
1657 #endif /* DEBUG_205 */
1658
1659                                 /* if still binding, destroy */
1660                                 meta_clear_one_candidate( op, mc, i );
1661                         }
1662                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1663                         META_BINDING_CLEAR( &candidates[ i ] );
1664                 }
1665
1666                 if ( candidates[ i ].sr_matched ) {
1667                         free( (char *)candidates[ i ].sr_matched );
1668                         candidates[ i ].sr_matched = NULL;
1669                 }
1670
1671                 if ( candidates[ i ].sr_text ) {
1672                         ldap_memfree( (char *)candidates[ i ].sr_text );
1673                         candidates[ i ].sr_text = NULL;
1674                 }
1675
1676                 if ( candidates[ i ].sr_ref ) {
1677                         ber_bvarray_free( candidates[ i ].sr_ref );
1678                         candidates[ i ].sr_ref = NULL;
1679                 }
1680
1681                 if ( candidates[ i ].sr_ctrls ) {
1682                         ldap_controls_free( candidates[ i ].sr_ctrls );
1683                         candidates[ i ].sr_ctrls = NULL;
1684                 }
1685
1686                 if ( META_BACK_TGT_QUARANTINE( mi->mi_targets[ i ] ) ) {
1687                         meta_back_quarantine( op, &candidates[ i ], i );
1688                 }
1689
1690                 /* only in case of timelimit exceeded, if the timelimit exceeded because
1691                  * one contacted target never responded, invalidate the connection
1692                  * NOTE: should we quarantine the target as well?  right now, the connection
1693                  * is invalidated; the next time it will be recreated and the target
1694                  * will be quarantined if it cannot be contacted */
1695                 if ( mi->mi_idle_timeout != 0
1696                         && rs->sr_err == LDAP_TIMELIMIT_EXCEEDED
1697                         && op->o_time > mc->mc_conns[ i ].msc_time )
1698                 {
1699                         /* don't let anyone else use this expired connection */
1700                         LDAP_BACK_CONN_TAINTED_SET( mc );
1701                 }
1702         }
1703
1704         if ( mc ) {
1705                 meta_back_release_conn( mi, mc );
1706         }
1707
1708         return rs->sr_err;
1709 }
1710
1711 static int
1712 meta_send_entry(
1713         Operation       *op,
1714         SlapReply       *rs,
1715         metaconn_t      *mc,
1716         int             target,
1717         LDAPMessage     *e )
1718 {
1719         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
1720         struct berval           a, mapped;
1721         Entry                   ent = { 0 };
1722         BerElement              ber = *e->lm_ber;
1723         Attribute               *attr, **attrp;
1724         struct berval           bdn,
1725                                 dn = BER_BVNULL;
1726         const char              *text;
1727         dncookie                dc;
1728         int                     rc;
1729
1730         if ( ber_scanf( &ber, "{m{", &bdn ) == LBER_ERROR ) {
1731                 return LDAP_DECODING_ERROR;
1732         }
1733
1734         /*
1735          * Rewrite the dn of the result, if needed
1736          */
1737         dc.target = mi->mi_targets[ target ];
1738         dc.conn = op->o_conn;
1739         dc.rs = rs;
1740         dc.ctx = "searchResult";
1741
1742         rs->sr_err = ldap_back_dn_massage( &dc, &bdn, &dn );
1743         if ( rs->sr_err != LDAP_SUCCESS) {
1744                 return rs->sr_err;
1745         }
1746
1747         /*
1748          * Note: this may fail if the target host(s) schema differs
1749          * from the one known to the meta, and a DN with unknown
1750          * attributes is returned.
1751          * 
1752          * FIXME: should we log anything, or delegate to dnNormalize?
1753          */
1754         rc = dnPrettyNormal( NULL, &dn, &ent.e_name, &ent.e_nname,
1755                 op->o_tmpmemctx );
1756         if ( dn.bv_val != bdn.bv_val ) {
1757                 free( dn.bv_val );
1758         }
1759         BER_BVZERO( &dn );
1760
1761         if ( rc != LDAP_SUCCESS ) {
1762                 return LDAP_INVALID_DN_SYNTAX;
1763         }
1764
1765         /*
1766          * cache dn
1767          */
1768         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
1769                 ( void )meta_dncache_update_entry( &mi->mi_cache,
1770                                 &ent.e_nname, target );
1771         }
1772
1773         attrp = &ent.e_attrs;
1774
1775         dc.ctx = "searchAttrDN";
1776         while ( ber_scanf( &ber, "{m", &a ) != LBER_ERROR ) {
1777                 int                             last = 0;
1778                 slap_syntax_validate_func       *validate;
1779                 slap_syntax_transform_func      *pretty;
1780
1781                 ldap_back_map( &mi->mi_targets[ target ]->mt_rwmap.rwm_at, 
1782                                 &a, &mapped, BACKLDAP_REMAP );
1783                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0' ) {
1784                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1785                         continue;
1786                 }
1787                 attr = ( Attribute * )ch_calloc( 1, sizeof( Attribute ) );
1788                 if ( attr == NULL ) {
1789                         continue;
1790                 }
1791                 if ( slap_bv2ad( &mapped, &attr->a_desc, &text )
1792                                 != LDAP_SUCCESS) {
1793                         if ( slap_bv2undef_ad( &mapped, &attr->a_desc, &text,
1794                                 SLAP_AD_PROXIED ) != LDAP_SUCCESS )
1795                         {
1796                                 char    buf[ SLAP_TEXT_BUFLEN ];
1797
1798                                 snprintf( buf, sizeof( buf ),
1799                                         "%s meta_send_entry(\"%s\"): "
1800                                         "slap_bv2undef_ad(%s): %s\n",
1801                                         op->o_log_prefix, ent.e_name.bv_val,
1802                                         mapped.bv_val, text );
1803
1804                                 Debug( LDAP_DEBUG_ANY, "%s", buf, 0, 0 );
1805                                 ch_free( attr );
1806                                 continue;
1807                         }
1808                 }
1809
1810                 /* no subschemaSubentry */
1811                 if ( attr->a_desc == slap_schema.si_ad_subschemaSubentry
1812                         || attr->a_desc == slap_schema.si_ad_entryDN )
1813                 {
1814
1815                         /* 
1816                          * We eat target's subschemaSubentry because
1817                          * a search for this value is likely not
1818                          * to resolve to the appropriate backend;
1819                          * later, the local subschemaSubentry is
1820                          * added.
1821                          *
1822                          * We also eat entryDN because the frontend
1823                          * will reattach it without checking if already
1824                          * present...
1825                          */
1826                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1827
1828                         ch_free(attr);
1829                         continue;
1830                 }
1831
1832                 if ( ber_scanf( &ber, "[W]", &attr->a_vals ) == LBER_ERROR 
1833                                 || attr->a_vals == NULL )
1834                 {
1835                         attr->a_vals = (struct berval *)&slap_dummy_bv;
1836
1837                 } else {
1838                         for ( last = 0; !BER_BVISNULL( &attr->a_vals[ last ] ); ++last )
1839                                 ;
1840                 }
1841
1842                 validate = attr->a_desc->ad_type->sat_syntax->ssyn_validate;
1843                 pretty = attr->a_desc->ad_type->sat_syntax->ssyn_pretty;
1844
1845                 if ( !validate && !pretty ) {
1846                         attr_free( attr );
1847                         goto next_attr;
1848                 }
1849
1850                 if ( attr->a_desc == slap_schema.si_ad_objectClass
1851                                 || attr->a_desc == slap_schema.si_ad_structuralObjectClass )
1852                 {
1853                         struct berval   *bv;
1854
1855                         for ( bv = attr->a_vals; !BER_BVISNULL( bv ); bv++ ) {
1856                                 ldap_back_map( &mi->mi_targets[ target ]->mt_rwmap.rwm_oc,
1857                                                 bv, &mapped, BACKLDAP_REMAP );
1858                                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0') {
1859                                         free( bv->bv_val );
1860                                         BER_BVZERO( bv );
1861                                         if ( --last < 0 ) {
1862                                                 break;
1863                                         }
1864                                         *bv = attr->a_vals[ last ];
1865                                         BER_BVZERO( &attr->a_vals[ last ] );
1866                                         bv--;
1867
1868                                 } else if ( mapped.bv_val != bv->bv_val ) {
1869                                         free( bv->bv_val );
1870                                         ber_dupbv( bv, &mapped );
1871                                 }
1872                         }
1873                 /*
1874                  * It is necessary to try to rewrite attributes with
1875                  * dn syntax because they might be used in ACLs as
1876                  * members of groups; since ACLs are applied to the
1877                  * rewritten stuff, no dn-based subecj clause could
1878                  * be used at the ldap backend side (see
1879                  * http://www.OpenLDAP.org/faq/data/cache/452.html)
1880                  * The problem can be overcome by moving the dn-based
1881                  * ACLs to the target directory server, and letting
1882                  * everything pass thru the ldap backend.
1883                  */
1884                 } else {
1885                         int     i;
1886
1887                         if ( attr->a_desc->ad_type->sat_syntax ==
1888                                 slap_schema.si_syn_distinguishedName )
1889                         {
1890                                 ldap_dnattr_result_rewrite( &dc, attr->a_vals );
1891
1892                         } else if ( attr->a_desc == slap_schema.si_ad_ref ) {
1893                                 ldap_back_referral_result_rewrite( &dc, attr->a_vals );
1894
1895                         }
1896
1897                         for ( i = 0; i < last; i++ ) {
1898                                 struct berval   pval;
1899                                 int             rc;
1900
1901                                 if ( pretty ) {
1902                                         rc = pretty( attr->a_desc->ad_type->sat_syntax,
1903                                                 &attr->a_vals[i], &pval, NULL );
1904
1905                                 } else {
1906                                         rc = validate( attr->a_desc->ad_type->sat_syntax,
1907                                                 &attr->a_vals[i] );
1908                                 }
1909
1910                                 if ( rc ) {
1911                                         LBER_FREE( attr->a_vals[i].bv_val );
1912                                         if ( --last == i ) {
1913                                                 BER_BVZERO( &attr->a_vals[ i ] );
1914                                                 break;
1915                                         }
1916                                         attr->a_vals[i] = attr->a_vals[last];
1917                                         BER_BVZERO( &attr->a_vals[last] );
1918                                         i--;
1919                                         continue;
1920                                 }
1921
1922                                 if ( pretty ) {
1923                                         LBER_FREE( attr->a_vals[i].bv_val );
1924                                         attr->a_vals[i] = pval;
1925                                 }
1926                         }
1927
1928                         if ( last == 0 && attr->a_vals != &slap_dummy_bv ) {
1929                                 attr_free( attr );
1930                                 goto next_attr;
1931                         }
1932                 }
1933
1934                 if ( last && attr->a_desc->ad_type->sat_equality &&
1935                         attr->a_desc->ad_type->sat_equality->smr_normalize )
1936                 {
1937                         int i;
1938
1939                         attr->a_nvals = ch_malloc( ( last + 1 ) * sizeof( struct berval ) );
1940                         for ( i = 0; i<last; i++ ) {
1941                                 attr->a_desc->ad_type->sat_equality->smr_normalize(
1942                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1943                                         attr->a_desc->ad_type->sat_syntax,
1944                                         attr->a_desc->ad_type->sat_equality,
1945                                         &attr->a_vals[i], &attr->a_nvals[i],
1946                                         NULL );
1947                         }
1948                         BER_BVZERO( &attr->a_nvals[i] );
1949
1950                 } else {
1951                         attr->a_nvals = attr->a_vals;
1952                 }
1953
1954                 *attrp = attr;
1955                 attrp = &attr->a_next;
1956 next_attr:;
1957         }
1958         rs->sr_entry = &ent;
1959         rs->sr_attrs = op->ors_attrs;
1960         rs->sr_flags = 0;
1961         rs->sr_err = LDAP_SUCCESS;
1962         rc = send_search_entry( op, rs );
1963         switch ( rc ) {
1964         case LDAP_UNAVAILABLE:
1965                 rc = LDAP_OTHER;
1966                 break;
1967         }
1968         rs->sr_entry = NULL;
1969         rs->sr_attrs = NULL;
1970         
1971         if ( !BER_BVISNULL( &ent.e_name ) ) {
1972                 free( ent.e_name.bv_val );
1973                 BER_BVZERO( &ent.e_name );
1974         }
1975         if ( !BER_BVISNULL( &ent.e_nname ) ) {
1976                 free( ent.e_nname.bv_val );
1977                 BER_BVZERO( &ent.e_nname );
1978         }
1979         entry_clean( &ent );
1980
1981         return rc;
1982 }
1983