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