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