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