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