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