]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/search.c
check existence of newSuperior
[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 static int
39 meta_send_entry(
40         Operation       *op,
41         SlapReply       *rs,
42         metaconn_t      *mc,
43         int             i,
44         LDAPMessage     *e );
45
46 typedef enum meta_search_candidate_t {
47         META_SEARCH_ERR = -1,
48         META_SEARCH_NOT_CANDIDATE,
49         META_SEARCH_CANDIDATE
50 } meta_search_candidate_t;
51
52 static meta_search_candidate_t
53 meta_back_search_start(
54         Operation               *op,
55         SlapReply               *rs,
56         dncookie                *dc,
57         metasingleconn_t        *msc,
58         int                     candidate,
59         SlapReply               *candidates
60 )
61 {
62         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
63         struct berval   realbase = op->o_req_dn;
64         int             realscope = op->ors_scope;
65         ber_len_t       suffixlen = 0;
66         struct berval   mbase = BER_BVNULL; 
67         struct berval   mfilter = BER_BVNULL;
68         char            **mapped_attrs = NULL;
69         int             rc;
70         meta_search_candidate_t retcode;
71         struct timeval  tv, *tvp = NULL;
72
73         /* should we check return values? */
74         if ( op->ors_deref != -1 ) {
75                 ldap_set_option( msc->msc_ld, LDAP_OPT_DEREF,
76                                 ( void * )&op->ors_deref );
77         }
78
79         if ( op->ors_tlimit != SLAP_NO_LIMIT ) {
80                 tv.tv_sec = op->ors_tlimit > 0 ? op->ors_tlimit : 1;
81                 tvp = &tv;
82         }
83
84         dc->target = &mi->mi_targets[ candidate ];
85
86         /*
87          * modifies the base according to the scope, if required
88          */
89         suffixlen = mi->mi_targets[ candidate ].mt_nsuffix.bv_len;
90         if ( suffixlen > op->o_req_ndn.bv_len ) {
91                 switch ( op->ors_scope ) {
92                 case LDAP_SCOPE_SUBTREE:
93                         /*
94                          * make the target suffix the new base
95                          * FIXME: this is very forgiving, because
96                          * "illegal" searchBases may be turned
97                          * into the suffix of the target; however,
98                          * the requested searchBase already passed
99                          * thru the candidate analyzer...
100                          */
101                         if ( dnIsSuffix( &mi->mi_targets[ candidate ].mt_nsuffix,
102                                         &op->o_req_ndn ) )
103                         {
104                                 realbase = mi->mi_targets[ candidate ].mt_nsuffix;
105                                 if ( mi->mi_targets[ candidate ].mt_scope == LDAP_SCOPE_SUBORDINATE ) {
106                                         realscope = LDAP_SCOPE_SUBORDINATE;
107                                 }
108
109                         } else {
110                                 /*
111                                  * this target is no longer candidate
112                                  */
113                                 return META_SEARCH_NOT_CANDIDATE;
114                         }
115                         break;
116
117                 case LDAP_SCOPE_SUBORDINATE:
118                 case LDAP_SCOPE_ONELEVEL:
119                 {
120                         struct berval   rdn = mi->mi_targets[ candidate ].mt_nsuffix;
121                         rdn.bv_len -= op->o_req_ndn.bv_len + STRLENOF( "," );
122                         if ( dnIsOneLevelRDN( &rdn )
123                                         && dnIsSuffix( &mi->mi_targets[ candidate ].mt_nsuffix, &op->o_req_ndn ) )
124                         {
125                                 /*
126                                  * if there is exactly one level,
127                                  * make the target suffix the new
128                                  * base, and make scope "base"
129                                  */
130                                 realbase = mi->mi_targets[ candidate ].mt_nsuffix;
131                                 if ( op->ors_scope == LDAP_SCOPE_SUBORDINATE ) {
132                                         if ( mi->mi_targets[ candidate ].mt_scope == LDAP_SCOPE_SUBORDINATE ) {
133                                                 realscope = LDAP_SCOPE_SUBORDINATE;
134                                         } else {
135                                                 realscope = LDAP_SCOPE_SUBTREE;
136                                         }
137                                 } else {
138                                         realscope = LDAP_SCOPE_BASE;
139                                 }
140                                 break;
141                         } /* else continue with the next case */
142                 }
143
144                 case LDAP_SCOPE_BASE:
145                         /*
146                          * this target is no longer candidate
147                          */
148                         return META_SEARCH_NOT_CANDIDATE;
149                 }
150         }
151
152         /*
153          * Rewrite the search base, if required
154          */
155         dc->ctx = "searchBase";
156         switch ( ldap_back_dn_massage( dc, &realbase, &mbase ) ) {
157         default:
158                 break;
159
160         case REWRITE_REGEXEC_UNWILLING:
161                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
162                 rs->sr_text = "Operation not allowed";
163                 send_ldap_result( op, rs );
164                 return META_SEARCH_ERR;
165
166         case REWRITE_REGEXEC_ERR:
167
168                 /*
169                  * this target is no longer candidate
170                  */
171                 return META_SEARCH_NOT_CANDIDATE;
172         }
173
174         /*
175          * Maps filter
176          */
177         rc = ldap_back_filter_map_rewrite( dc, op->ors_filter,
178                         &mfilter, BACKLDAP_MAP );
179         switch ( rc ) {
180         case LDAP_SUCCESS:
181                 break;
182
183         case LDAP_COMPARE_FALSE:
184         default:
185                 /*
186                  * this target is no longer candidate
187                  */
188                 retcode = META_SEARCH_NOT_CANDIDATE;
189                 goto done;
190         }
191
192         /*
193          * Maps required attributes
194          */
195         rc = ldap_back_map_attrs( &mi->mi_targets[ candidate ].mt_rwmap.rwm_at,
196                         op->ors_attrs, BACKLDAP_MAP, &mapped_attrs );
197         if ( rc != LDAP_SUCCESS ) {
198                 /*
199                  * this target is no longer candidate
200                  */
201                 retcode = META_SEARCH_NOT_CANDIDATE;
202                 goto done;
203         }
204
205         /*
206          * Starts the search
207          */
208         rc = ldap_search_ext( msc->msc_ld,
209                         mbase.bv_val, realscope, mfilter.bv_val,
210                         mapped_attrs, op->ors_attrsonly,
211                         op->o_ctrls, NULL, tvp, op->ors_slimit,
212                         &candidates[ candidate ].sr_msgid ); 
213         if ( rc == LDAP_SUCCESS ) {
214                 retcode = META_SEARCH_CANDIDATE;
215
216         } else {
217                 candidates[ candidate ].sr_msgid = -1;
218                 retcode = META_SEARCH_NOT_CANDIDATE;
219         }
220
221 done:;
222         if ( mapped_attrs ) {
223                 free( mapped_attrs );
224         }
225         if ( mfilter.bv_val != op->ors_filterstr.bv_val ) {
226                 free( mfilter.bv_val );
227         }
228         if ( mbase.bv_val != realbase.bv_val ) {
229                 free( mbase.bv_val );
230         }
231
232         return retcode;
233 }
234
235 int
236 meta_back_search( Operation *op, SlapReply *rs )
237 {
238         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
239         metaconn_t      *mc;
240         struct timeval  tv = { 0, 0 };
241         time_t          stoptime = (time_t)-1;
242         LDAPMessage     *res = NULL, *e;
243         int             rc = 0, sres = LDAP_SUCCESS;
244         char            *matched = NULL;
245         int             last = 0, ncandidates = 0,
246                         initial_candidates = 0, candidate_match = 0;
247         long            i;
248         dncookie        dc;
249         int             is_ok = 0;
250         void            *savepriv;
251         SlapReply       *candidates = meta_back_candidates_get( op );
252
253         /*
254          * controls are set in ldap_back_dobind()
255          * 
256          * FIXME: in case of values return filter, we might want
257          * to map attrs and maybe rewrite value
258          */
259         mc = meta_back_getconn( op, rs, NULL, LDAP_BACK_SENDERR );
260         if ( !mc || !meta_back_dobind( op, rs, mc, LDAP_BACK_SENDERR ) ) {
261                 return rs->sr_err;
262         }
263
264         dc.conn = op->o_conn;
265         dc.rs = rs;
266
267         /*
268          * Inits searches
269          */
270         for ( i = 0; i < mi->mi_ntargets; i++ ) {
271                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
272
273                 candidates[ i ].sr_msgid = -1;
274                 candidates[ i ].sr_matched = NULL;
275                 candidates[ i ].sr_text = NULL;
276                 candidates[ i ].sr_ref = NULL;
277                 candidates[ i ].sr_ctrls = NULL;
278
279                 if ( candidates[ i ].sr_tag != META_CANDIDATE
280                         || candidates[ i ].sr_err != LDAP_SUCCESS )
281                 {
282                         continue;
283                 }
284
285                 switch ( meta_back_search_start( op, rs, &dc, msc, i, candidates ) )
286                 {
287                 case META_SEARCH_NOT_CANDIDATE:
288                         break;
289
290                 case META_SEARCH_CANDIDATE:
291                         candidates[ i ].sr_type = REP_INTERMEDIATE;
292                         ++ncandidates;
293                         break;
294
295                 case META_SEARCH_ERR:
296                         rc = -1;
297                         goto finish;
298                 }
299         }
300
301         initial_candidates = ncandidates;
302
303 #if 0
304         {
305                 char    cnd[BUFSIZ];
306                 int     i;
307
308                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
309                         if ( candidates[ i ].sr_tag == META_CANDIDATE ) {
310                                 cnd[ i ] = '*';
311                         } else {
312                                 cnd[ i ] = ' ';
313                         }
314                 }
315                 cnd[ i ] = '\0';
316
317                 Debug( LDAP_DEBUG_ANY, "%s meta_back_search: ncandidates=%d "
318                         "cnd=\"%s\"\n", op->o_log_prefix, ncandidates, cnd );
319         }
320 #endif
321
322         if ( initial_candidates == 0 ) {
323                 /* NOTE: here we are not sending any matchedDN;
324                  * this is intended, because if the back-meta
325                  * is serving this search request, but no valid
326                  * candidate could be looked up, it means that
327                  * there is a hole in the mapping of the targets
328                  * and thus no knowledge of any remote superior
329                  * is available */
330                 Debug( LDAP_DEBUG_ANY, "%s meta_back_search: "
331                         "base=\"%s\" scope=%d: "
332                         "no candidate could be selected\n",
333                         op->o_log_prefix, op->o_req_dn.bv_val,
334                         op->ors_scope );
335
336                 /* FIXME: we're sending the first error we encounter;
337                  * maybe we should pick the worst... */
338                 rc = LDAP_NO_SUCH_OBJECT;
339                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
340                         if ( candidates[ i ].sr_tag == META_CANDIDATE
341                                 && candidates[ i ].sr_err != LDAP_SUCCESS )
342                         {
343                                 rc = candidates[ i ].sr_err;
344                                 break;
345                         }
346                 }
347
348                 send_ldap_error( op, rs, rc, NULL );
349
350                 goto finish;
351         }
352
353         /* We pull apart the ber result, stuff it into a slapd entry, and
354          * let send_search_entry stuff it back into ber format. Slow & ugly,
355          * but this is necessary for version matching, and for ACL processing.
356          */
357
358         if ( op->ors_tlimit != SLAP_NO_LIMIT ) {
359                 stoptime = op->o_time + op->ors_tlimit;
360         }
361
362         /*
363          * In case there are no candidates, no cycle takes place...
364          *
365          * FIXME: we might use a queue, to better balance the load 
366          * among the candidates
367          */
368         for ( rc = 0; ncandidates > 0; ) {
369                 int     gotit = 0, doabandon = 0;
370
371                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
372                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
373
374                         if ( candidates[ i ].sr_msgid == -1 ) {
375                                 continue;
376                         }
377
378                         /* check for abandon */
379                         if ( op->o_abandon ) {
380                                 break;
381                         }
382                         
383                         /*
384                          * FIXME: handle time limit as well?
385                          * Note that target servers are likely 
386                          * to handle it, so at some time we'll
387                          * get a LDAP_TIMELIMIT_EXCEEDED from
388                          * one of them ...
389                          */
390 get_result:;
391                         rc = ldap_result( msc->msc_ld, candidates[ i ].sr_msgid,
392                                         LDAP_MSG_ONE, &tv, &res );
393
394                         if ( rc == 0 ) {
395                                 /* FIXME: res should not need to be freed */
396                                 assert( res == NULL );
397
398                                 /* check time limit */
399                                 if ( op->ors_tlimit != SLAP_NO_LIMIT
400                                                 && slap_get_time() > stoptime )
401                                 {
402                                         doabandon = 1;
403                                         rc = rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
404                                         savepriv = op->o_private;
405                                         op->o_private = (void *)i;
406                                         send_ldap_result( op, rs );
407                                         op->o_private = savepriv;
408                                         goto finish;
409                                 }
410
411                                 continue;
412
413                         } else if ( rc == -1 ) {
414 really_bad:;
415                                 /* something REALLY bad happened! */
416                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
417                                         candidates[ i ].sr_type = REP_RESULT;
418
419                                         if ( meta_back_retry( op, rs, &mc, i, LDAP_BACK_DONTSEND ) ) {
420                                                 switch ( meta_back_search_start( op, rs, &dc, msc, i, candidates ) )
421                                                 {
422                                                 case META_SEARCH_CANDIDATE:
423                                                         goto get_result;
424
425                                                 case META_SEARCH_NOT_CANDIDATE:
426                                                         assert( 0 );
427
428                                                 default:
429                                                         rc = rs->sr_err = LDAP_OTHER;
430                                                         goto finish;
431                                                 }
432                                         }
433
434                                         savepriv = op->o_private;
435                                         op->o_private = (void *)i;
436                                         send_ldap_result( op, rs );
437                                         op->o_private = savepriv;
438                                         goto finish;
439                                 }
440
441                                 /*
442                                  * When no candidates are left,
443                                  * the outer cycle finishes
444                                  */
445                                 candidates[ i ].sr_msgid = -1;
446                                 --ncandidates;
447                                 rs->sr_err = candidates[ i ].sr_err = LDAP_OTHER;
448                                 rs->sr_text = "remote server unavailable";
449
450                         } else if ( rc == LDAP_RES_SEARCH_ENTRY ) {
451                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
452                                         /* don't retry any more... */
453                                         candidates[ i ].sr_type = REP_RESULT;
454                                 }
455
456                                 is_ok++;
457
458                                 e = ldap_first_entry( msc->msc_ld, res );
459                                 savepriv = op->o_private;
460                                 op->o_private = (void *)i;
461                                 rs->sr_err = meta_send_entry( op, rs, mc, i, e );
462                                 ldap_msgfree( res );
463                                 res = NULL;
464
465                                 switch ( rs->sr_err ) {
466                                 case LDAP_SIZELIMIT_EXCEEDED:
467                                         savepriv = op->o_private;
468                                         op->o_private = (void *)i;
469                                         send_ldap_result( op, rs );
470                                         op->o_private = savepriv;
471                                         rs->sr_err = LDAP_SUCCESS;
472                                         goto finish;
473
474                                 case LDAP_UNAVAILABLE:
475                                         rs->sr_err = LDAP_OTHER;
476                                         goto finish;
477                                 }
478                                 op->o_private = savepriv;
479
480                                 /* don't wait any longer... */
481                                 gotit = 1;
482                                 tv.tv_sec = 0;
483                                 tv.tv_usec = 0;
484
485 #if 0
486                                 /*
487                                  * If scope is BASE, we need to jump out
488                                  * as soon as one entry is found; if
489                                  * the target pool is properly crafted,
490                                  * this should correspond to the sole
491                                  * entry that has the base DN
492                                  */
493                                 /* FIXME: this defeats the purpose of
494                                  * doing a search with scope == base and
495                                  * sizelimit = 1 to determine if a
496                                  * candidate is actually unique */
497                                 if ( op->ors_scope == LDAP_SCOPE_BASE
498                                                 && rs->sr_nentries > 0 )
499                                 {
500                                         doabandon = 1;
501                                         ncandidates = 0;
502                                         sres = LDAP_SUCCESS;
503                                         break;
504                                 }
505 #endif
506
507                         } else if ( rc == LDAP_RES_SEARCH_REFERENCE ) {
508                                 char            **references = NULL;
509                                 int             cnt;
510
511                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
512                                         /* don't retry any more... */
513                                         candidates[ i ].sr_type = REP_RESULT;
514                                 }
515
516                                 is_ok++;
517
518                                 rc = ldap_parse_reference( msc->msc_ld, res,
519                                                 &references, &rs->sr_ctrls, 1 );
520                                 res = NULL;
521
522                                 if ( rc != LDAP_SUCCESS ) {
523                                         continue;
524                                 }
525
526                                 if ( references == NULL ) {
527                                         continue;
528                                 }
529
530 #ifdef ENABLE_REWRITE
531                                 dc.ctx = "referralDN";
532 #else /* ! ENABLE_REWRITE */
533                                 dc.tofrom = 0;
534                                 dc.normalized = 0;
535 #endif /* ! ENABLE_REWRITE */
536
537                                 /* FIXME: merge all and return at the end */
538
539                                 for ( cnt = 0; references[ cnt ]; cnt++ )
540                                         ;
541
542                                 rs->sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
543
544                                 for ( cnt = 0; references[ cnt ]; cnt++ ) {
545                                         ber_str2bv( references[ cnt ], 0, 1, &rs->sr_ref[ cnt ] );
546                                 }
547                                 BER_BVZERO( &rs->sr_ref[ cnt ] );
548
549                                 ( void )ldap_back_referral_result_rewrite( &dc, rs->sr_ref );
550
551                                 if ( rs->sr_ref != NULL && !BER_BVISNULL( &rs->sr_ref[ 0 ] ) ) {
552                                         /* ignore return value by now */
553                                         savepriv = op->o_private;
554                                         op->o_private = (void *)i;
555                                         ( void )send_search_reference( op, rs );
556                                         op->o_private = savepriv;
557
558                                         ber_bvarray_free( rs->sr_ref );
559                                         rs->sr_ref = NULL;
560                                 }
561
562                                 /* cleanup */
563                                 if ( references ) {
564                                         ber_memvfree( (void **)references );
565                                 }
566
567                                 if ( rs->sr_ctrls ) {
568                                         ldap_controls_free( rs->sr_ctrls );
569                                         rs->sr_ctrls = NULL;
570                                 }
571
572                         } else if ( rc == LDAP_RES_SEARCH_RESULT ) {
573                                 char            buf[ SLAP_TEXT_BUFLEN ];
574                                 char            **references = NULL;
575
576                                 if ( candidates[ i ].sr_type == REP_INTERMEDIATE ) {
577                                         /* don't retry any more... */
578                                         candidates[ i ].sr_type = REP_RESULT;
579                                 }
580
581                                 /* NOTE: ignores response controls
582                                  * (and intermediate response controls
583                                  * as well, except for those with search
584                                  * references); this may not be correct,
585                                  * but if they're not ignored then
586                                  * back-meta would need to merge them
587                                  * consistently (think of pagedResults...)
588                                  */
589                                 rs->sr_err = ldap_parse_result( msc->msc_ld,
590                                                         res,
591                                                         &candidates[ i ].sr_err,
592                                                         (char **)&candidates[ i ].sr_matched,
593                                                         NULL /* (char **)&candidates[ i ].sr_text */ ,
594                                                         &references,
595                                                         NULL /* &candidates[ i ].sr_ctrls (unused) */ ,
596                                                         1 );
597                                 res = NULL;
598                                 if ( rs->sr_err != LDAP_SUCCESS ) {
599                                         ldap_get_option( msc->msc_ld,
600                                                         LDAP_OPT_ERROR_NUMBER,
601                                                         &rs->sr_err );
602                                         sres = slap_map_api2result( rs );
603                                         candidates[ i ].sr_type = REP_RESULT;
604                                         goto really_bad;
605                                 }
606
607                                 /* massage matchedDN if need be */
608                                 if ( candidates[ i ].sr_matched != NULL ) {
609                                         struct berval   match, mmatch;
610
611                                         ber_str2bv( candidates[ i ].sr_matched,
612                                                 0, 0, &match );
613                                         candidates[ i ].sr_matched = NULL;
614
615                                         dc.ctx = "matchedDN";
616                                         dc.target = &mi->mi_targets[ i ];
617                                         if ( !ldap_back_dn_massage( &dc, &match, &mmatch ) ) {
618                                                 if ( mmatch.bv_val == match.bv_val ) {
619                                                         candidates[ i ].sr_matched = ch_strdup( mmatch.bv_val );
620
621                                                 } else {
622                                                         candidates[ i ].sr_matched = mmatch.bv_val;
623                                                 }
624
625                                                 candidate_match++;
626                                         } 
627                                         ldap_memfree( match.bv_val );
628                                 }
629
630                                 /* add references to array */
631                                 if ( references ) {
632                                         BerVarray       sr_ref;
633                                         int             cnt;
634
635                                         for ( cnt = 0; references[ cnt ]; cnt++ )
636                                                 ;
637
638                                         sr_ref = ch_calloc( sizeof( struct berval ), cnt + 1 );
639
640                                         for ( cnt = 0; references[ cnt ]; cnt++ ) {
641                                                 ber_str2bv( references[ cnt ], 0, 1, &sr_ref[ cnt ] );
642                                         }
643                                         BER_BVZERO( &sr_ref[ cnt ] );
644
645                                         ( void )ldap_back_referral_result_rewrite( &dc, sr_ref );
646                                 
647                                         /* cleanup */
648                                         ber_memvfree( (void **)references );
649
650                                         if ( rs->sr_v2ref == NULL ) {
651                                                 rs->sr_v2ref = sr_ref;
652
653                                         } else {
654                                                 for ( cnt = 0; !BER_BVISNULL( &sr_ref[ cnt ] ); cnt++ ) {
655                                                         ber_bvarray_add( &rs->sr_v2ref, &sr_ref[ cnt ] );
656                                                 }
657                                                 ber_memfree( sr_ref );
658                                         }
659                                 }
660
661                                 rs->sr_err = candidates[ i ].sr_err;
662                                 sres = slap_map_api2result( rs );
663
664                                 if ( LogTest( LDAP_DEBUG_TRACE | LDAP_DEBUG_ANY ) ) {
665                                         snprintf( buf, sizeof( buf ),
666                                                 "%s meta_back_search[%ld] "
667                                                 "match=\"%s\" err=%ld",
668                                                 op->o_log_prefix, i,
669                                                 candidates[ i ].sr_matched ? candidates[ i ].sr_matched : "",
670                                                 (long) candidates[ i ].sr_err );
671                                         if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
672                                                 Debug( LDAP_DEBUG_TRACE, "%s.\n", buf, 0, 0 );
673
674                                         } else {
675                                                 Debug( LDAP_DEBUG_ANY, "%s (%s).\n",
676                                                         buf, ldap_err2string( candidates[ i ].sr_err ), 0 );
677                                         }
678                                 }
679
680                                 switch ( sres ) {
681                                 case LDAP_NO_SUCH_OBJECT:
682                                         /* is_ok is touched any time a valid
683                                          * (even intermediate) result is
684                                          * returned; as a consequence, if
685                                          * a candidate returns noSuchObject
686                                          * it is ignored and the candidate
687                                          * is simply demoted. */
688                                         if ( is_ok ) {
689                                                 sres = LDAP_SUCCESS;
690                                         }
691                                         break;
692
693                                 case LDAP_SUCCESS:
694                                 case LDAP_REFERRAL:
695                                         is_ok++;
696                                         break;
697
698                                 case LDAP_SIZELIMIT_EXCEEDED:
699                                         /* if a target returned sizelimitExceeded
700                                          * and the entry count is equal to the
701                                          * proxy's limit, the target would have
702                                          * returned more, and the error must be
703                                          * propagated to the client; otherwise,
704                                          * the target enforced a limit lower
705                                          * than what requested by the proxy;
706                                          * ignore it */
707                                         if ( rs->sr_nentries == op->ors_slimit
708                                                 || META_BACK_ONERR_STOP( mi ) )
709                                         {
710                                                 savepriv = op->o_private;
711                                                 op->o_private = (void *)i;
712                                                 send_ldap_result( op, rs );
713                                                 op->o_private = savepriv;
714                                                 goto finish;
715                                         }
716                                         break;
717
718                                 default:
719                                         if ( META_BACK_ONERR_STOP( mi ) ) {
720                                                 savepriv = op->o_private;
721                                                 op->o_private = (void *)i;
722                                                 send_ldap_result( op, rs );
723                                                 op->o_private = savepriv;
724                                                 goto finish;
725                                         }
726                                         break;
727                                 }
728
729                                 last = i;
730                                 rc = 0;
731
732                                 /*
733                                  * When no candidates are left,
734                                  * the outer cycle finishes
735                                  */
736                                 candidates[ i ].sr_msgid = -1;
737                                 --ncandidates;
738
739                         } else {
740                                 assert( 0 );
741                                 goto really_bad;
742                         }
743                 }
744
745                 /* check for abandon */
746                 if ( op->o_abandon || doabandon ) {
747                         for ( i = 0; i < mi->mi_ntargets; i++ ) {
748                                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
749
750                                 if ( candidates[ i ].sr_msgid != -1 ) {
751                                         ldap_abandon_ext( msc->msc_ld,
752                                                 candidates[ i ].sr_msgid,
753                                                 NULL, NULL );
754                                         candidates[ i ].sr_msgid = -1;
755                                 }
756                         }
757
758                         if ( op->o_abandon ) {
759                                 rc = SLAPD_ABANDON;
760                                 goto finish;
761                         }
762                 }
763
764                 /* if no entry was found during this loop,
765                  * set a minimal timeout */
766                 if ( gotit == 0 ) {
767                         LDAP_BACK_TV_SET( &tv );
768                         ldap_pvt_thread_yield();
769                 }
770         }
771
772         if ( rc == -1 ) {
773                 /*
774                  * FIXME: need a better strategy to handle errors
775                  */
776                 rc = meta_back_op_result( mc, op, rs, META_TARGET_NONE );
777                 goto finish;
778         }
779
780         /*
781          * Rewrite the matched portion of the search base, if required
782          * 
783          * FIXME: only the last one gets caught!
784          */
785         savepriv = op->o_private;
786         op->o_private = (void *)(long)mi->mi_ntargets;
787         if ( candidate_match > 0 ) {
788                 struct berval   pmatched = BER_BVNULL;
789
790                 /* we use the first one */
791                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
792                         if ( candidates[ i ].sr_tag == META_CANDIDATE
793                                         && candidates[ i ].sr_matched != NULL )
794                         {
795                                 struct berval   bv, pbv;
796                                 int             rc;
797
798                                 /* if we got success, and this target
799                                  * returned noSuchObject, and its suffix
800                                  * is a superior of the searchBase,
801                                  * ignore the matchedDN */
802                                 if ( sres == LDAP_SUCCESS
803                                         && candidates[ i ].sr_err == LDAP_NO_SUCH_OBJECT
804                                         && op->o_req_ndn.bv_len > mi->mi_targets[ i ].mt_nsuffix.bv_len )
805                                 {
806                                         free( (char *)candidates[ i ].sr_matched );
807                                         candidates[ i ].sr_matched = NULL;
808                                         continue;
809                                 }
810
811                                 ber_str2bv( candidates[ i ].sr_matched, 0, 0, &bv );
812                                 rc = dnPretty( NULL, &bv, &pbv, op->o_tmpmemctx );
813
814                                 if ( rc == LDAP_SUCCESS ) {
815
816                                         /* NOTE: if they all are superiors
817                                          * of the baseDN, the shorter is also 
818                                          * superior of the longer... */
819                                         if ( pbv.bv_len > pmatched.bv_len ) {
820                                                 if ( !BER_BVISNULL( &pmatched ) ) {
821                                                         op->o_tmpfree( pmatched.bv_val, op->o_tmpmemctx );
822                                                 }
823                                                 pmatched = pbv;
824                                                 op->o_private = (void *)i;
825
826                                         } else {
827                                                 op->o_tmpfree( pbv.bv_val, op->o_tmpmemctx );
828                                         }
829                                 }
830
831                                 if ( candidates[ i ].sr_matched != NULL ) {
832                                         free( (char *)candidates[ i ].sr_matched );
833                                         candidates[ i ].sr_matched = NULL;
834                                 }
835                         }
836                 }
837
838                 if ( !BER_BVISNULL( &pmatched ) ) {
839                         matched = pmatched.bv_val;
840                 }
841
842         } else if ( sres == LDAP_NO_SUCH_OBJECT ) {
843                 matched = op->o_bd->be_suffix[ 0 ].bv_val;
844         }
845
846 #if 0
847         {
848                 char    buf[BUFSIZ];
849                 char    cnd[BUFSIZ];
850                 int     i;
851
852                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
853                         if ( candidates[ i ].sr_tag == META_CANDIDATE ) {
854                                 cnd[ i ] = '*';
855                         } else {
856                                 cnd[ i ] = ' ';
857                         }
858                 }
859                 cnd[ i ] = '\0';
860
861                 snprintf( buf, sizeof( buf ), "%s meta_back_search: is_scope=%d is_ok=%d cnd=\"%s\"\n",
862                         op->o_log_prefix, initial_candidates, is_ok, cnd );
863
864                 Debug( LDAP_DEBUG_ANY, "%s", buf, 0, 0 );
865         }
866 #endif
867
868         /*
869          * In case we returned at least one entry, we return LDAP_SUCCESS
870          * otherwise, the latter error code we got
871          *
872          * FIXME: we should handle error codes and return the more 
873          * important/reasonable
874          */
875
876         if ( sres == LDAP_SUCCESS && rs->sr_v2ref ) {
877                 sres = LDAP_REFERRAL;
878         }
879         rs->sr_err = sres;
880         rs->sr_matched = matched;
881         rs->sr_ref = ( sres == LDAP_REFERRAL ? rs->sr_v2ref : NULL );
882         send_ldap_result( op, rs );
883         op->o_private = savepriv;
884         rs->sr_matched = NULL;
885         rs->sr_ref = NULL;
886
887 finish:;
888         if ( matched && matched != op->o_bd->be_suffix[ 0 ].bv_val ) {
889                 op->o_tmpfree( matched, op->o_tmpmemctx );
890         }
891
892         if ( rs->sr_v2ref ) {
893                 ber_bvarray_free( rs->sr_v2ref );
894         }
895
896         for ( i = 0; i < mi->mi_ntargets; i++ ) {
897                 if ( candidates[ i ].sr_tag != META_CANDIDATE ) {
898                         continue;
899                 }
900
901                 if ( candidates[ i ].sr_matched ) {
902                         free( (char *)candidates[ i ].sr_matched );
903                         candidates[ i ].sr_matched = NULL;
904                 }
905
906                 if ( candidates[ i ].sr_text ) {
907                         ldap_memfree( (char *)candidates[ i ].sr_text );
908                         candidates[ i ].sr_text = NULL;
909                 }
910
911                 if ( candidates[ i ].sr_ref ) {
912                         ber_bvarray_free( candidates[ i ].sr_ref );
913                         candidates[ i ].sr_ref = NULL;
914                 }
915
916                 if ( candidates[ i ].sr_ctrls ) {
917                         ldap_controls_free( candidates[ i ].sr_ctrls );
918                         candidates[ i ].sr_ctrls = NULL;
919                 }
920         }
921
922         if ( mc ) {
923                 meta_back_release_conn( op, mc );
924         }
925
926         return rs->sr_err;
927 }
928
929 static int
930 meta_send_entry(
931         Operation       *op,
932         SlapReply       *rs,
933         metaconn_t      *mc,
934         int             target,
935         LDAPMessage     *e )
936 {
937         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
938         struct berval           a, mapped;
939         Entry                   ent = { 0 };
940         BerElement              ber = *e->lm_ber;
941         Attribute               *attr, **attrp;
942         struct berval           bdn,
943                                 dn = BER_BVNULL;
944         const char              *text;
945         dncookie                dc;
946         int                     rc;
947
948         if ( ber_scanf( &ber, "{m{", &bdn ) == LBER_ERROR ) {
949                 return LDAP_DECODING_ERROR;
950         }
951
952         /*
953          * Rewrite the dn of the result, if needed
954          */
955         dc.target = &mi->mi_targets[ target ];
956         dc.conn = op->o_conn;
957         dc.rs = rs;
958         dc.ctx = "searchResult";
959
960         rs->sr_err = ldap_back_dn_massage( &dc, &bdn, &dn );
961         if ( rs->sr_err != LDAP_SUCCESS) {
962                 return rs->sr_err;
963         }
964
965         /*
966          * Note: this may fail if the target host(s) schema differs
967          * from the one known to the meta, and a DN with unknown
968          * attributes is returned.
969          * 
970          * FIXME: should we log anything, or delegate to dnNormalize?
971          */
972         rc = dnPrettyNormal( NULL, &dn, &ent.e_name, &ent.e_nname,
973                 op->o_tmpmemctx );
974         if ( dn.bv_val != bdn.bv_val ) {
975                 free( dn.bv_val );
976         }
977         BER_BVZERO( &dn );
978
979         if ( rc != LDAP_SUCCESS ) {
980                 return LDAP_INVALID_DN_SYNTAX;
981         }
982
983         /*
984          * cache dn
985          */
986         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
987                 ( void )meta_dncache_update_entry( &mi->mi_cache,
988                                 &ent.e_nname, target );
989         }
990
991         attrp = &ent.e_attrs;
992
993         dc.ctx = "searchAttrDN";
994         while ( ber_scanf( &ber, "{m", &a ) != LBER_ERROR ) {
995                 int                             last = 0;
996                 slap_syntax_validate_func       *validate;
997                 slap_syntax_transform_func      *pretty;
998
999                 ldap_back_map( &mi->mi_targets[ target ].mt_rwmap.rwm_at, 
1000                                 &a, &mapped, BACKLDAP_REMAP );
1001                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0' ) {
1002                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1003                         continue;
1004                 }
1005                 attr = ( Attribute * )ch_calloc( 1, sizeof( Attribute ) );
1006                 if ( attr == NULL ) {
1007                         continue;
1008                 }
1009                 if ( slap_bv2ad( &mapped, &attr->a_desc, &text )
1010                                 != LDAP_SUCCESS) {
1011                         if ( slap_bv2undef_ad( &mapped, &attr->a_desc, &text,
1012                                 SLAP_AD_PROXIED ) != LDAP_SUCCESS )
1013                         {
1014                                 char    buf[ SLAP_TEXT_BUFLEN ];
1015
1016                                 snprintf( buf, sizeof( buf ),
1017                                         "%s meta_send_entry(\"%s\"): "
1018                                         "slap_bv2undef_ad(%s): %s\n",
1019                                         op->o_log_prefix, ent.e_name.bv_val,
1020                                         mapped.bv_val, text );
1021
1022                                 Debug( LDAP_DEBUG_ANY, "%s", buf, 0, 0 );
1023                                 ch_free( attr );
1024                                 continue;
1025                         }
1026                 }
1027
1028                 /* no subschemaSubentry */
1029                 if ( attr->a_desc == slap_schema.si_ad_subschemaSubentry
1030                         || attr->a_desc == slap_schema.si_ad_entryDN )
1031                 {
1032
1033                         /* 
1034                          * We eat target's subschemaSubentry because
1035                          * a search for this value is likely not
1036                          * to resolve to the appropriate backend;
1037                          * later, the local subschemaSubentry is
1038                          * added.
1039                          *
1040                          * We also eat entryDN because the frontend
1041                          * will reattach it without checking if already
1042                          * present...
1043                          */
1044                         ( void )ber_scanf( &ber, "x" /* [W] */ );
1045
1046                         ch_free(attr);
1047                         continue;
1048                 }
1049
1050                 if ( ber_scanf( &ber, "[W]", &attr->a_vals ) == LBER_ERROR 
1051                                 || attr->a_vals == NULL )
1052                 {
1053                         attr->a_vals = (struct berval *)&slap_dummy_bv;
1054
1055                 } else {
1056                         for ( last = 0; !BER_BVISNULL( &attr->a_vals[ last ] ); ++last )
1057                                 ;
1058                 }
1059
1060                 validate = attr->a_desc->ad_type->sat_syntax->ssyn_validate;
1061                 pretty = attr->a_desc->ad_type->sat_syntax->ssyn_pretty;
1062
1063                 if ( !validate && !pretty ) {
1064                         attr_free( attr );
1065                         goto next_attr;
1066                 }
1067
1068                 if ( attr->a_desc == slap_schema.si_ad_objectClass
1069                                 || attr->a_desc == slap_schema.si_ad_structuralObjectClass )
1070                 {
1071                         struct berval   *bv;
1072
1073                         for ( bv = attr->a_vals; !BER_BVISNULL( bv ); bv++ ) {
1074                                 ldap_back_map( &mi->mi_targets[ target ].mt_rwmap.rwm_oc,
1075                                                 bv, &mapped, BACKLDAP_REMAP );
1076                                 if ( BER_BVISNULL( &mapped ) || mapped.bv_val[0] == '\0') {
1077                                         free( bv->bv_val );
1078                                         BER_BVZERO( bv );
1079                                         if ( --last < 0 ) {
1080                                                 break;
1081                                         }
1082                                         *bv = attr->a_vals[ last ];
1083                                         BER_BVZERO( &attr->a_vals[ last ] );
1084                                         bv--;
1085
1086                                 } else if ( mapped.bv_val != bv->bv_val ) {
1087                                         free( bv->bv_val );
1088                                         ber_dupbv( bv, &mapped );
1089                                 }
1090                         }
1091                 /*
1092                  * It is necessary to try to rewrite attributes with
1093                  * dn syntax because they might be used in ACLs as
1094                  * members of groups; since ACLs are applied to the
1095                  * rewritten stuff, no dn-based subecj clause could
1096                  * be used at the ldap backend side (see
1097                  * http://www.OpenLDAP.org/faq/data/cache/452.html)
1098                  * The problem can be overcome by moving the dn-based
1099                  * ACLs to the target directory server, and letting
1100                  * everything pass thru the ldap backend.
1101                  */
1102                 } else {
1103                         int     i;
1104
1105                         if ( attr->a_desc->ad_type->sat_syntax ==
1106                                 slap_schema.si_syn_distinguishedName )
1107                         {
1108                                 ldap_dnattr_result_rewrite( &dc, attr->a_vals );
1109
1110                         } else if ( attr->a_desc == slap_schema.si_ad_ref ) {
1111                                 ldap_back_referral_result_rewrite( &dc, attr->a_vals );
1112
1113                         }
1114
1115                         for ( i = 0; i < last; i++ ) {
1116                                 struct berval   pval;
1117                                 int             rc;
1118
1119                                 if ( pretty ) {
1120                                         rc = pretty( attr->a_desc->ad_type->sat_syntax,
1121                                                 &attr->a_vals[i], &pval, NULL );
1122
1123                                 } else {
1124                                         rc = validate( attr->a_desc->ad_type->sat_syntax,
1125                                                 &attr->a_vals[i] );
1126                                 }
1127
1128                                 if ( rc ) {
1129                                         LBER_FREE( attr->a_vals[i].bv_val );
1130                                         if ( --last == i ) {
1131                                                 BER_BVZERO( &attr->a_vals[ i ] );
1132                                                 break;
1133                                         }
1134                                         attr->a_vals[i] = attr->a_vals[last];
1135                                         BER_BVZERO( &attr->a_vals[last] );
1136                                         i--;
1137                                         continue;
1138                                 }
1139
1140                                 if ( pretty ) {
1141                                         LBER_FREE( attr->a_vals[i].bv_val );
1142                                         attr->a_vals[i] = pval;
1143                                 }
1144                         }
1145
1146                         if ( last == 0 && attr->a_vals != &slap_dummy_bv ) {
1147                                 attr_free( attr );
1148                                 goto next_attr;
1149                         }
1150                 }
1151
1152                 if ( last && attr->a_desc->ad_type->sat_equality &&
1153                         attr->a_desc->ad_type->sat_equality->smr_normalize )
1154                 {
1155                         int i;
1156
1157                         attr->a_nvals = ch_malloc( ( last + 1 ) * sizeof( struct berval ) );
1158                         for ( i = 0; i<last; i++ ) {
1159                                 attr->a_desc->ad_type->sat_equality->smr_normalize(
1160                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1161                                         attr->a_desc->ad_type->sat_syntax,
1162                                         attr->a_desc->ad_type->sat_equality,
1163                                         &attr->a_vals[i], &attr->a_nvals[i],
1164                                         NULL );
1165                         }
1166                         BER_BVZERO( &attr->a_nvals[i] );
1167
1168                 } else {
1169                         attr->a_nvals = attr->a_vals;
1170                 }
1171
1172                 *attrp = attr;
1173                 attrp = &attr->a_next;
1174 next_attr:;
1175         }
1176         rs->sr_entry = &ent;
1177         rs->sr_attrs = op->ors_attrs;
1178         rs->sr_flags = 0;
1179         rs->sr_err = LDAP_SUCCESS;
1180         rc = send_search_entry( op, rs );
1181         switch ( rc ) {
1182         case LDAP_UNAVAILABLE:
1183                 rc = LDAP_OTHER;
1184                 break;
1185         }
1186         rs->sr_entry = NULL;
1187         rs->sr_attrs = NULL;
1188         
1189         if ( !BER_BVISNULL( &ent.e_name ) ) {
1190                 free( ent.e_name.bv_val );
1191                 BER_BVZERO( &ent.e_name );
1192         }
1193         if ( !BER_BVISNULL( &ent.e_nname ) ) {
1194                 free( ent.e_nname.bv_val );
1195                 BER_BVZERO( &ent.e_nname );
1196         }
1197         entry_clean( &ent );
1198
1199         return rc;
1200 }
1201