]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/search.c
more checks
[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 = LDAP_OTHER;
743                                 rs->sr_text = "remote server unavailable";
744
745                         } else if ( rc == LDAP_RES_SEARCH_ENTRY ) {
746                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
747                                         /* don't retry any more... */
748                                         candidates[ i ].sr_type = REP_RESULT;
749                                 }
750
751                                 is_ok++;
752
753                                 e = ldap_first_entry( msc->msc_ld, res );
754                                 savepriv = op->o_private;
755                                 op->o_private = (void *)i;
756                                 rs->sr_err = meta_send_entry( op, rs, mc, i, e );
757                                 ldap_msgfree( res );
758                                 res = NULL;
759
760                                 switch ( rs->sr_err ) {
761                                 case LDAP_SIZELIMIT_EXCEEDED:
762                                         savepriv = op->o_private;
763                                         op->o_private = (void *)i;
764                                         send_ldap_result( op, rs );
765                                         op->o_private = savepriv;
766                                         rs->sr_err = LDAP_SUCCESS;
767                                         goto finish;
768
769                                 case LDAP_UNAVAILABLE:
770                                         rs->sr_err = LDAP_OTHER;
771                                         goto finish;
772                                 }
773                                 op->o_private = savepriv;
774
775                                 /* don't wait any longer... */
776                                 gotit = 1;
777                                 tv.tv_sec = 0;
778                                 tv.tv_usec = 0;
779
780 #if 0
781                                 /*
782                                  * If scope is BASE, we need to jump out
783                                  * as soon as one entry is found; if
784                                  * the target pool is properly crafted,
785                                  * this should correspond to the sole
786                                  * entry that has the base DN
787                                  */
788                                 /* FIXME: this defeats the purpose of
789                                  * doing a search with scope == base and
790                                  * sizelimit = 1 to determine if a
791                                  * candidate is actually unique */
792                                 if ( op->ors_scope == LDAP_SCOPE_BASE
793                                                 && rs->sr_nentries > 0 )
794                                 {
795                                         doabandon = 1;
796                                         ncandidates = 0;
797                                         sres = LDAP_SUCCESS;
798                                         break;
799                                 }
800 #endif
801
802                         } else if ( rc == LDAP_RES_SEARCH_REFERENCE ) {
803                                 char            **references = NULL;
804                                 int             cnt;
805
806                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
807                                         /* don't retry any more... */
808                                         candidates[ i ].sr_type = REP_RESULT;
809                                 }
810
811                                 is_ok++;
812
813                                 rc = ldap_parse_reference( msc->msc_ld, res,
814                                                 &references, &rs->sr_ctrls, 1 );
815                                 res = NULL;
816
817                                 if ( rc != LDAP_SUCCESS ) {
818                                         continue;
819                                 }
820
821                                 if ( references == NULL ) {
822                                         continue;
823                                 }
824
825 #ifdef ENABLE_REWRITE
826                                 dc.ctx = "referralDN";
827 #else /* ! ENABLE_REWRITE */
828                                 dc.tofrom = 0;
829                                 dc.normalized = 0;
830 #endif /* ! ENABLE_REWRITE */
831
832                                 /* FIXME: merge all and return at the end */
833
834                                 for ( cnt = 0; references[ cnt ]; cnt++ )
835                                         ;
836
837                                 rs->sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
838
839                                 for ( cnt = 0; references[ cnt ]; cnt++ ) {
840                                         ber_str2bv( references[ cnt ], 0, 1, &rs->sr_ref[ cnt ] );
841                                 }
842                                 BER_BVZERO( &rs->sr_ref[ cnt ] );
843
844                                 ( void )ldap_back_referral_result_rewrite( &dc, rs->sr_ref );
845
846                                 if ( rs->sr_ref != NULL && !BER_BVISNULL( &rs->sr_ref[ 0 ] ) ) {
847                                         /* ignore return value by now */
848                                         savepriv = op->o_private;
849                                         op->o_private = (void *)i;
850                                         ( void )send_search_reference( op, rs );
851                                         op->o_private = savepriv;
852
853                                         ber_bvarray_free( rs->sr_ref );
854                                         rs->sr_ref = NULL;
855                                 }
856
857                                 /* cleanup */
858                                 if ( references ) {
859                                         ber_memvfree( (void **)references );
860                                 }
861
862                                 if ( rs->sr_ctrls ) {
863                                         ldap_controls_free( rs->sr_ctrls );
864                                         rs->sr_ctrls = NULL;
865                                 }
866
867                         } else if ( rc == LDAP_RES_SEARCH_RESULT ) {
868                                 char            buf[ SLAP_TEXT_BUFLEN ];
869                                 char            **references = NULL;
870
871                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
872                                         /* don't retry any more... */
873                                         candidates[ i ].sr_type = REP_RESULT;
874                                 }
875
876                                 /* NOTE: ignores response controls
877                                  * (and intermediate response controls
878                                  * as well, except for those with search
879                                  * references); this may not be correct,
880                                  * but if they're not ignored then
881                                  * back-meta would need to merge them
882                                  * consistently (think of pagedResults...)
883                                  */
884                                 rs->sr_err = ldap_parse_result( msc->msc_ld,
885                                                         res,
886                                                         &candidates[ i ].sr_err,
887                                                         (char **)&candidates[ i ].sr_matched,
888                                                         NULL /* (char **)&candidates[ i ].sr_text */ ,
889                                                         &references,
890                                                         NULL /* &candidates[ i ].sr_ctrls (unused) */ ,
891                                                         1 );
892                                 res = NULL;
893                                 if ( rs->sr_err != LDAP_SUCCESS ) {
894                                         ldap_get_option( msc->msc_ld,
895                                                         LDAP_OPT_ERROR_NUMBER,
896                                                         &rs->sr_err );
897                                         sres = slap_map_api2result( rs );
898                                         candidates[ i ].sr_type = REP_RESULT;
899                                         goto really_bad;
900                                 }
901
902                                 /* massage matchedDN if need be */
903                                 if ( candidates[ i ].sr_matched != NULL ) {
904                                         struct berval   match, mmatch;
905
906                                         ber_str2bv( candidates[ i ].sr_matched,
907                                                 0, 0, &match );
908                                         candidates[ i ].sr_matched = NULL;
909
910                                         dc.ctx = "matchedDN";
911                                         dc.target = mi->mi_targets[ i ];
912                                         if ( !ldap_back_dn_massage( &dc, &match, &mmatch ) ) {
913                                                 if ( mmatch.bv_val == match.bv_val ) {
914                                                         candidates[ i ].sr_matched = ch_strdup( mmatch.bv_val );
915
916                                                 } else {
917                                                         candidates[ i ].sr_matched = mmatch.bv_val;
918                                                 }
919
920                                                 candidate_match++;
921                                         } 
922                                         ldap_memfree( match.bv_val );
923                                 }
924
925                                 /* add references to array */
926                                 if ( references ) {
927                                         BerVarray       sr_ref;
928                                         int             cnt;
929
930                                         for ( cnt = 0; references[ cnt ]; cnt++ )
931                                                 ;
932
933                                         sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
934
935                                         for ( cnt = 0; references[ cnt ]; cnt++ ) {
936                                                 ber_str2bv( references[ cnt ], 0, 1, &sr_ref[ cnt ] );
937                                         }
938                                         BER_BVZERO( &sr_ref[ cnt ] );
939
940                                         ( void )ldap_back_referral_result_rewrite( &dc, sr_ref );
941                                 
942                                         /* cleanup */
943                                         ber_memvfree( (void **)references );
944
945                                         if ( rs->sr_v2ref == NULL ) {
946                                                 rs->sr_v2ref = sr_ref;
947
948                                         } else {
949                                                 for ( cnt = 0; !BER_BVISNULL( &sr_ref[ cnt ] ); cnt++ ) {
950                                                         ber_bvarray_add( &rs->sr_v2ref, &sr_ref[ cnt ] );
951                                                 }
952                                                 ber_memfree( sr_ref );
953                                         }
954                                 }
955
956                                 rs->sr_err = candidates[ i ].sr_err;
957                                 sres = slap_map_api2result( rs );
958
959                                 if ( LogTest( LDAP_DEBUG_TRACE | LDAP_DEBUG_ANY ) ) {
960                                         snprintf( buf, sizeof( buf ),
961                                                 "%s meta_back_search[%ld] "
962                                                 "match=\"%s\" err=%ld",
963                                                 op->o_log_prefix, i,
964                                                 candidates[ i ].sr_matched ? candidates[ i ].sr_matched : "",
965                                                 (long) candidates[ i ].sr_err );
966                                         if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
967                                                 Debug( LDAP_DEBUG_TRACE, "%s.\n", buf, 0, 0 );
968
969                                         } else {
970                                                 Debug( LDAP_DEBUG_ANY, "%s (%s).\n",
971                                                         buf, ldap_err2string( candidates[ i ].sr_err ), 0 );
972                                         }
973                                 }
974
975                                 switch ( sres ) {
976                                 case LDAP_NO_SUCH_OBJECT:
977                                         /* is_ok is touched any time a valid
978                                          * (even intermediate) result is
979                                          * returned; as a consequence, if
980                                          * a candidate returns noSuchObject
981                                          * it is ignored and the candidate
982                                          * is simply demoted. */
983                                         if ( is_ok ) {
984                                                 sres = LDAP_SUCCESS;
985                                         }
986                                         break;
987
988                                 case LDAP_SUCCESS:
989                                 case LDAP_REFERRAL:
990                                         is_ok++;
991                                         break;
992
993                                 case LDAP_SIZELIMIT_EXCEEDED:
994                                         /* if a target returned sizelimitExceeded
995                                          * and the entry count is equal to the
996                                          * proxy's limit, the target would have
997                                          * returned more, and the error must be
998                                          * propagated to the client; otherwise,
999                                          * the target enforced a limit lower
1000                                          * than what requested by the proxy;
1001                                          * ignore it */
1002                                         if ( rs->sr_nentries == op->ors_slimit
1003                                                 || META_BACK_ONERR_STOP( mi ) )
1004                                         {
1005                                                 savepriv = op->o_private;
1006                                                 op->o_private = (void *)i;
1007                                                 send_ldap_result( op, rs );
1008                                                 op->o_private = savepriv;
1009                                                 goto finish;
1010                                         }
1011                                         break;
1012
1013                                 default:
1014                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1015                                                 savepriv = op->o_private;
1016                                                 op->o_private = (void *)i;
1017                                                 send_ldap_result( op, rs );
1018                                                 op->o_private = savepriv;
1019                                                 goto finish;
1020                                         }
1021                                         break;
1022                                 }
1023
1024                                 last = i;
1025                                 rc = 0;
1026
1027                                 /*
1028                                  * When no candidates are left,
1029                                  * the outer cycle finishes
1030                                  */
1031                                 candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1032                                 --ncandidates;
1033
1034                         } else if ( rc == LDAP_RES_BIND ) {
1035                                 meta_search_candidate_t retcode;
1036
1037                                 retcode = meta_search_dobind_result( op, rs, &mc, i, candidates, res );
1038                                 if ( retcode == META_SEARCH_CANDIDATE ) {
1039                                         retcode = meta_back_search_start( op, rs, &dc, &mc, i, candidates );
1040                                 }
1041
1042                                 switch ( retcode ) {
1043                                 case META_SEARCH_CANDIDATE:
1044                                         goto get_result;
1045
1046                                         /* means that failed but onerr == continue */
1047                                 case META_SEARCH_NOT_CANDIDATE:
1048                                 case META_SEARCH_ERR:
1049                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1050                                         --ncandidates;
1051
1052                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1053                                                 savepriv = op->o_private;
1054                                                 op->o_private = (void *)i;
1055                                                 send_ldap_result( op, rs );
1056                                                 op->o_private = savepriv;
1057                                                 goto finish;
1058                                         }
1059                                         break;
1060
1061                                 default:
1062                                         assert( 0 );
1063                                         break;
1064                                 }
1065
1066                         } else {
1067                                 assert( 0 );
1068                                 goto really_bad;
1069                         }
1070                 }
1071
1072                 /* check for abandon */
1073                 if ( op->o_abandon || doabandon ) {
1074                         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1075                                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
1076
1077                                 if ( candidates[ i ].sr_msgid != META_MSGID_IGNORE )
1078                                 {
1079                                         ldap_abandon_ext( msc->msc_ld,
1080                                                 candidates[ i ].sr_msgid,
1081                                                 NULL, NULL );
1082                                         candidates[ i ].sr_msgid = META_MSGID_IGNORE;
1083                                 }
1084                         }
1085
1086                         if ( op->o_abandon ) {
1087                                 rc = SLAPD_ABANDON;
1088                                 goto finish;
1089                         }
1090                 }
1091
1092                 /* if no entry was found during this loop,
1093                  * set a minimal timeout */
1094                 if ( gotit == 0 ) {
1095                         /* make the entire wait last
1096                          * LDAP_BACK_RESULT_UTIMEOUT at worst */
1097                         tv.tv_sec = 0;
1098                         tv.tv_usec = LDAP_BACK_RESULT_UTIMEOUT/initial_candidates;
1099                         ldap_pvt_thread_yield();
1100                 }
1101         }
1102
1103         if ( rc == -1 ) {
1104                 /*
1105                  * FIXME: need a better strategy to handle errors
1106                  */
1107                 if ( mc ) {
1108                         rc = meta_back_op_result( mc, op, rs, META_TARGET_NONE );
1109                 } else {
1110                         rc = rs->sr_err;
1111                 }
1112                 goto finish;
1113         }
1114
1115         /*
1116          * Rewrite the matched portion of the search base, if required
1117          * 
1118          * FIXME: only the last one gets caught!
1119          */
1120         savepriv = op->o_private;
1121         op->o_private = (void *)(long)mi->mi_ntargets;
1122         if ( candidate_match > 0 ) {
1123                 struct berval   pmatched = BER_BVNULL;
1124
1125                 /* we use the first one */
1126                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1127                         if ( candidates[ i ].sr_tag == META_CANDIDATE
1128                                         && candidates[ i ].sr_matched != NULL )
1129                         {
1130                                 struct berval   bv, pbv;
1131                                 int             rc;
1132
1133                                 /* if we got success, and this target
1134                                  * returned noSuchObject, and its suffix
1135                                  * is a superior of the searchBase,
1136                                  * ignore the matchedDN */
1137                                 if ( sres == LDAP_SUCCESS
1138                                         && candidates[ i ].sr_err == LDAP_NO_SUCH_OBJECT
1139                                         && op->o_req_ndn.bv_len > mi->mi_targets[ i ]->mt_nsuffix.bv_len )
1140                                 {
1141                                         free( (char *)candidates[ i ].sr_matched );
1142                                         candidates[ i ].sr_matched = NULL;
1143                                         continue;
1144                                 }
1145
1146                                 ber_str2bv( candidates[ i ].sr_matched, 0, 0, &bv );
1147                                 rc = dnPretty( NULL, &bv, &pbv, op->o_tmpmemctx );
1148
1149                                 if ( rc == LDAP_SUCCESS ) {
1150
1151                                         /* NOTE: if they all are superiors
1152                                          * of the baseDN, the shorter is also 
1153                                          * superior of the longer... */
1154                                         if ( pbv.bv_len > pmatched.bv_len ) {
1155                                                 if ( !BER_BVISNULL( &pmatched ) ) {
1156                                                         op->o_tmpfree( pmatched.bv_val, op->o_tmpmemctx );
1157                                                 }
1158                                                 pmatched = pbv;
1159                                                 op->o_private = (void *)i;
1160
1161                                         } else {
1162                                                 op->o_tmpfree( pbv.bv_val, op->o_tmpmemctx );
1163                                         }
1164                                 }
1165
1166                                 if ( candidates[ i ].sr_matched != NULL ) {
1167                                         free( (char *)candidates[ i ].sr_matched );
1168                                         candidates[ i ].sr_matched = NULL;
1169                                 }
1170                         }
1171                 }
1172
1173                 if ( !BER_BVISNULL( &pmatched ) ) {
1174                         matched = pmatched.bv_val;
1175                 }
1176
1177         } else if ( sres == LDAP_NO_SUCH_OBJECT ) {
1178                 matched = op->o_bd->be_suffix[ 0 ].bv_val;
1179         }
1180
1181 #if 0
1182         {
1183                 char    buf[BUFSIZ];
1184                 char    cnd[BUFSIZ];
1185                 int     i;
1186
1187                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1188                         if ( candidates[ i ].sr_tag == META_CANDIDATE ) {
1189                                 cnd[ i ] = '*';
1190                         } else {
1191                                 cnd[ i ] = ' ';
1192                         }
1193                 }
1194                 cnd[ i ] = '\0';
1195
1196                 snprintf( buf, sizeof( buf ), "%s meta_back_search: is_scope=%d is_ok=%d cnd=\"%s\"\n",
1197                         op->o_log_prefix, initial_candidates, is_ok, cnd );
1198
1199                 Debug( LDAP_DEBUG_ANY, "%s", buf, 0, 0 );
1200         }
1201 #endif
1202
1203         /*
1204          * In case we returned at least one entry, we return LDAP_SUCCESS
1205          * otherwise, the latter error code we got
1206          *
1207          * FIXME: we should handle error codes and return the more 
1208          * important/reasonable
1209          */
1210
1211         if ( sres == LDAP_SUCCESS && rs->sr_v2ref ) {
1212                 sres = LDAP_REFERRAL;
1213         }
1214         rs->sr_err = sres;
1215         rs->sr_matched = matched;
1216         rs->sr_ref = ( sres == LDAP_REFERRAL ? rs->sr_v2ref : NULL );
1217         send_ldap_result( op, rs );
1218         op->o_private = savepriv;
1219         rs->sr_matched = NULL;
1220         rs->sr_ref = NULL;
1221
1222 finish:;
1223         if ( matched && matched != op->o_bd->be_suffix[ 0 ].bv_val ) {
1224                 op->o_tmpfree( matched, op->o_tmpmemctx );
1225         }
1226
1227         if ( rs->sr_v2ref ) {
1228                 ber_bvarray_free( rs->sr_v2ref );
1229         }
1230
1231         for ( i = 0; i < mi->mi_ntargets; i++ ) {
1232                 if ( candidates[ i ].sr_tag != META_CANDIDATE ) {
1233                         continue;
1234                 }
1235
1236                 if ( mc && candidates[ i ].sr_msgid >= 0 ) {
1237                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1238                         if ( LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) ) {
1239                                 LDAP_BACK_CONN_BINDING_CLEAR( &mc->mc_conns[ i ] );
1240                         }
1241                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1242                 }
1243
1244                 if ( candidates[ i ].sr_matched ) {
1245                         free( (char *)candidates[ i ].sr_matched );
1246                         candidates[ i ].sr_matched = NULL;
1247                 }
1248
1249                 if ( candidates[ i ].sr_text ) {
1250                         ldap_memfree( (char *)candidates[ i ].sr_text );
1251                         candidates[ i ].sr_text = NULL;
1252                 }
1253
1254                 if ( candidates[ i ].sr_ref ) {
1255                         ber_bvarray_free( candidates[ i ].sr_ref );
1256                         candidates[ i ].sr_ref = NULL;
1257                 }
1258
1259                 if ( candidates[ i ].sr_ctrls ) {
1260                         ldap_controls_free( candidates[ i ].sr_ctrls );
1261                         candidates[ i ].sr_ctrls = NULL;
1262                 }
1263         }
1264
1265         if ( mc ) {
1266                 meta_back_release_conn( op, mc );
1267         }
1268
1269         return rs->sr_err;
1270 }
1271
1272 static int
1273 meta_send_entry(
1274         Operation       *op,
1275         SlapReply       *rs,
1276         metaconn_t      *mc,
1277         int             target,
1278         LDAPMessage     *e )
1279 {
1280         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
1281         struct berval           a, mapped;
1282         Entry                   ent = { 0 };
1283         BerElement              ber = *e->lm_ber;
1284         Attribute               *attr, **attrp;
1285         struct berval           bdn,
1286                                 dn = BER_BVNULL;
1287         const char              *text;
1288         dncookie                dc;
1289         int                     rc;
1290
1291         if ( ber_scanf( &ber, "{m{", &bdn ) == LBER_ERROR ) {
1292                 return LDAP_DECODING_ERROR;
1293         }
1294
1295         /*
1296          * Rewrite the dn of the result, if needed
1297          */
1298         dc.target = mi->mi_targets[ target ];
1299         dc.conn = op->o_conn;
1300         dc.rs = rs;
1301         dc.ctx = "searchResult";
1302
1303         rs->sr_err = ldap_back_dn_massage( &dc, &bdn, &dn );
1304         if ( rs->sr_err != LDAP_SUCCESS) {
1305                 return rs->sr_err;
1306         }
1307
1308         /*
1309          * Note: this may fail if the target host(s) schema differs
1310          * from the one known to the meta, and a DN with unknown
1311          * attributes is returned.
1312          * 
1313          * FIXME: should we log anything, or delegate to dnNormalize?
1314          */
1315         rc = dnPrettyNormal( NULL, &dn, &ent.e_name, &ent.e_nname,
1316                 op->o_tmpmemctx );
1317         if ( dn.bv_val != bdn.bv_val ) {
1318                 free( dn.bv_val );
1319         }
1320         BER_BVZERO( &dn );
1321
1322         if ( rc != LDAP_SUCCESS ) {
1323                 return LDAP_INVALID_DN_SYNTAX;
1324         }
1325
1326         /*
1327          * cache dn
1328          */
1329         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
1330                 ( void )meta_dncache_update_entry( &mi->mi_cache,
1331                                 &ent.e_nname, target );
1332         }
1333
1334         attrp = &ent.e_attrs;
1335
1336         dc.ctx = "searchAttrDN";
1337         while ( ber_scanf( &ber, "{m", &a ) != LBER_ERROR ) {
1338                 int                             last = 0;
1339                 slap_syntax_validate_func       *validate;
1340                 slap_syntax_transform_func      *pretty;
1341
1342                 ldap_back_map( &mi->mi_targets[ target ]->mt_rwmap.rwm_at, 
1343                                 &a, &mapped, BACKLDAP_REMAP );
1344                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0' ) {
1345                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1346                         continue;
1347                 }
1348                 attr = ( Attribute * )ch_calloc( 1, sizeof( Attribute ) );
1349                 if ( attr == NULL ) {
1350                         continue;
1351                 }
1352                 if ( slap_bv2ad( &mapped, &attr->a_desc, &text )
1353                                 != LDAP_SUCCESS) {
1354                         if ( slap_bv2undef_ad( &mapped, &attr->a_desc, &text,
1355                                 SLAP_AD_PROXIED ) != LDAP_SUCCESS )
1356                         {
1357                                 char    buf[ SLAP_TEXT_BUFLEN ];
1358
1359                                 snprintf( buf, sizeof( buf ),
1360                                         "%s meta_send_entry(\"%s\"): "
1361                                         "slap_bv2undef_ad(%s): %s\n",
1362                                         op->o_log_prefix, ent.e_name.bv_val,
1363                                         mapped.bv_val, text );
1364
1365                                 Debug( LDAP_DEBUG_ANY, "%s", buf, 0, 0 );
1366                                 ch_free( attr );
1367                                 continue;
1368                         }
1369                 }
1370
1371                 /* no subschemaSubentry */
1372                 if ( attr->a_desc == slap_schema.si_ad_subschemaSubentry
1373                         || attr->a_desc == slap_schema.si_ad_entryDN )
1374                 {
1375
1376                         /* 
1377                          * We eat target's subschemaSubentry because
1378                          * a search for this value is likely not
1379                          * to resolve to the appropriate backend;
1380                          * later, the local subschemaSubentry is
1381                          * added.
1382                          *
1383                          * We also eat entryDN because the frontend
1384                          * will reattach it without checking if already
1385                          * present...
1386                          */
1387                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1388
1389                         ch_free(attr);
1390                         continue;
1391                 }
1392
1393                 if ( ber_scanf( &ber, "[W]", &attr->a_vals ) == LBER_ERROR 
1394                                 || attr->a_vals == NULL )
1395                 {
1396                         attr->a_vals = (struct berval *)&slap_dummy_bv;
1397
1398                 } else {
1399                         for ( last = 0; !BER_BVISNULL( &attr->a_vals[ last ] ); ++last )
1400                                 ;
1401                 }
1402
1403                 validate = attr->a_desc->ad_type->sat_syntax->ssyn_validate;
1404                 pretty = attr->a_desc->ad_type->sat_syntax->ssyn_pretty;
1405
1406                 if ( !validate && !pretty ) {
1407                         attr_free( attr );
1408                         goto next_attr;
1409                 }
1410
1411                 if ( attr->a_desc == slap_schema.si_ad_objectClass
1412                                 || attr->a_desc == slap_schema.si_ad_structuralObjectClass )
1413                 {
1414                         struct berval   *bv;
1415
1416                         for ( bv = attr->a_vals; !BER_BVISNULL( bv ); bv++ ) {
1417                                 ldap_back_map( &mi->mi_targets[ target ]->mt_rwmap.rwm_oc,
1418                                                 bv, &mapped, BACKLDAP_REMAP );
1419                                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0') {
1420                                         free( bv->bv_val );
1421                                         BER_BVZERO( bv );
1422                                         if ( --last < 0 ) {
1423                                                 break;
1424                                         }
1425                                         *bv = attr->a_vals[ last ];
1426                                         BER_BVZERO( &attr->a_vals[ last ] );
1427                                         bv--;
1428
1429                                 } else if ( mapped.bv_val != bv->bv_val ) {
1430                                         free( bv->bv_val );
1431                                         ber_dupbv( bv, &mapped );
1432                                 }
1433                         }
1434                 /*
1435                  * It is necessary to try to rewrite attributes with
1436                  * dn syntax because they might be used in ACLs as
1437                  * members of groups; since ACLs are applied to the
1438                  * rewritten stuff, no dn-based subecj clause could
1439                  * be used at the ldap backend side (see
1440                  * http://www.OpenLDAP.org/faq/data/cache/452.html)
1441                  * The problem can be overcome by moving the dn-based
1442                  * ACLs to the target directory server, and letting
1443                  * everything pass thru the ldap backend.
1444                  */
1445                 } else {
1446                         int     i;
1447
1448                         if ( attr->a_desc->ad_type->sat_syntax ==
1449                                 slap_schema.si_syn_distinguishedName )
1450                         {
1451                                 ldap_dnattr_result_rewrite( &dc, attr->a_vals );
1452
1453                         } else if ( attr->a_desc == slap_schema.si_ad_ref ) {
1454                                 ldap_back_referral_result_rewrite( &dc, attr->a_vals );
1455
1456                         }
1457
1458                         for ( i = 0; i < last; i++ ) {
1459                                 struct berval   pval;
1460                                 int             rc;
1461
1462                                 if ( pretty ) {
1463                                         rc = pretty( attr->a_desc->ad_type->sat_syntax,
1464                                                 &attr->a_vals[i], &pval, NULL );
1465
1466                                 } else {
1467                                         rc = validate( attr->a_desc->ad_type->sat_syntax,
1468                                                 &attr->a_vals[i] );
1469                                 }
1470
1471                                 if ( rc ) {
1472                                         LBER_FREE( attr->a_vals[i].bv_val );
1473                                         if ( --last == i ) {
1474                                                 BER_BVZERO( &attr->a_vals[ i ] );
1475                                                 break;
1476                                         }
1477                                         attr->a_vals[i] = attr->a_vals[last];
1478                                         BER_BVZERO( &attr->a_vals[last] );
1479                                         i--;
1480                                         continue;
1481                                 }
1482
1483                                 if ( pretty ) {
1484                                         LBER_FREE( attr->a_vals[i].bv_val );
1485                                         attr->a_vals[i] = pval;
1486                                 }
1487                         }
1488
1489                         if ( last == 0 && attr->a_vals != &slap_dummy_bv ) {
1490                                 attr_free( attr );
1491                                 goto next_attr;
1492                         }
1493                 }
1494
1495                 if ( last && attr->a_desc->ad_type->sat_equality &&
1496                         attr->a_desc->ad_type->sat_equality->smr_normalize )
1497                 {
1498                         int i;
1499
1500                         attr->a_nvals = ch_malloc( ( last + 1 ) * sizeof( struct berval ) );
1501                         for ( i = 0; i<last; i++ ) {
1502                                 attr->a_desc->ad_type->sat_equality->smr_normalize(
1503                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1504                                         attr->a_desc->ad_type->sat_syntax,
1505                                         attr->a_desc->ad_type->sat_equality,
1506                                         &attr->a_vals[i], &attr->a_nvals[i],
1507                                         NULL );
1508                         }
1509                         BER_BVZERO( &attr->a_nvals[i] );
1510
1511                 } else {
1512                         attr->a_nvals = attr->a_vals;
1513                 }
1514
1515                 *attrp = attr;
1516                 attrp = &attr->a_next;
1517 next_attr:;
1518         }
1519         rs->sr_entry = &ent;
1520         rs->sr_attrs = op->ors_attrs;
1521         rs->sr_flags = 0;
1522         rs->sr_err = LDAP_SUCCESS;
1523         rc = send_search_entry( op, rs );
1524         switch ( rc ) {
1525         case LDAP_UNAVAILABLE:
1526                 rc = LDAP_OTHER;
1527                 break;
1528         }
1529         rs->sr_entry = NULL;
1530         rs->sr_attrs = NULL;
1531         
1532         if ( !BER_BVISNULL( &ent.e_name ) ) {
1533                 free( ent.e_name.bv_val );
1534                 BER_BVZERO( &ent.e_name );
1535         }
1536         if ( !BER_BVISNULL( &ent.e_nname ) ) {
1537                 free( ent.e_nname.bv_val );
1538                 BER_BVZERO( &ent.e_nname );
1539         }
1540         entry_clean( &ent );
1541
1542         return rc;
1543 }
1544