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