]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/search.c
a63a4bae9985462a57387cc4cd85a5138bd35fc8
[openldap] / servers / slapd / back-bdb / search.c
1 /* search.c - search operation */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2000-2004 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16
17 #include "portable.h"
18
19 #include <stdio.h>
20 #include <ac/string.h>
21
22 #include "back-bdb.h"
23 #include "idl.h"
24 #include "external.h"
25
26 static int base_candidate(
27         BackendDB       *be,
28         Entry   *e,
29         ID              *ids );
30
31 static int search_candidates(
32         Operation *stackop,     /* op with the current threadctx/slab cache */
33         Operation *sop,         /* search op */
34         SlapReply *rs,
35         Entry *e,
36         u_int32_t locker,
37         ID      *ids,
38         ID      *scopes );
39
40 static void send_paged_response( 
41         Operation *op,
42         SlapReply *rs,
43         ID  *lastid,
44         int tentries );
45
46 /* Dereference aliases for a single alias entry. Return the final
47  * dereferenced entry on success, NULL on any failure.
48  */
49 static Entry * deref_base (
50         Operation *op,
51         SlapReply *rs,
52         Entry *e,
53         Entry **matched,
54         u_int32_t locker,
55         DB_LOCK *lock,
56         ID      *tmp,
57         ID      *visited )
58 {
59         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
60         struct berval ndn;
61         EntryInfo *ei;
62         DB_LOCK lockr;
63
64         rs->sr_err = LDAP_ALIAS_DEREF_PROBLEM;
65         rs->sr_text = "maximum deref depth exceeded";
66
67         while (BDB_IDL_N(tmp) < op->o_bd->be_max_deref_depth) {
68                 /* Remember the last entry we looked at, so we can
69                  * report broken links
70                  */
71                 *matched = e;
72
73                 /* If this is part of a subtree or onelevel search,
74                  * have we seen this ID before? If so, quit.
75                  */
76                 if ( visited && bdb_idl_insert( visited, e->e_id ) ) {
77                         e = NULL;
78                         break;
79                 }
80
81                 /* If we've seen this ID during this deref iteration,
82                  * we've hit a loop.
83                  */
84                 if ( bdb_idl_insert( tmp, e->e_id ) ) {
85                         rs->sr_err = LDAP_ALIAS_PROBLEM;
86                         rs->sr_text = "circular alias";
87                         e = NULL;
88                         break;
89                 }
90
91                 /* If there was a problem getting the aliasedObjectName,
92                  * get_alias_dn will have set the error status.
93                  */
94                 if ( get_alias_dn(e, &ndn, &rs->sr_err, &rs->sr_text) ) {
95                         e = NULL;
96                         break;
97                 }
98
99                 rs->sr_err = bdb_dn2entry( op, NULL, &ndn, &ei,
100                         0, locker, &lockr );
101
102                 if ( ei ) {
103                         e = ei->bei_e;
104                 } else {
105                         e = NULL;
106                 }
107
108                 if (!e) {
109                         rs->sr_err = LDAP_ALIAS_PROBLEM;
110                         rs->sr_text = "aliasedObject not found";
111                         break;
112                 }
113
114                 /* Free the previous entry, continue to work with the
115                  * one we just retrieved.
116                  */
117                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
118                         *matched, lock);
119                 *lock = lockr;
120
121                 /* We found a regular entry. Return this to the caller. The
122                  * entry is still locked for Read.
123                  */
124                 if (!is_entry_alias(e)) {
125                         rs->sr_err = LDAP_SUCCESS;
126                         rs->sr_text = NULL;
127                         break;
128                 }
129         }
130         return e;
131 }
132
133 /* Look for and dereference all aliases within the search scope. Adds
134  * the dereferenced entries to the "ids" list. Requires "stack" to be
135  * able to hold 8 levels of DB_SIZE IDLs. Of course we're hardcoded to
136  * require a minimum of 8 UM_SIZE IDLs so this is never a problem.
137  */
138 static int search_aliases(
139         Operation *op,
140         SlapReply *rs,
141         Entry *e,
142         u_int32_t locker,
143         ID *ids,
144         ID *scopes,
145         ID *stack )
146 {
147         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
148         ID *aliases, *curscop, *subscop, *visited, *newsubs, *oldsubs, *tmp;
149         ID cursora, ida, cursoro, ido, *subscop2;
150         Entry *matched, *a;
151         EntryInfo *ei;
152         struct berval bv_alias = { sizeof("alias")-1, "alias" };
153         AttributeAssertion aa_alias;
154         Filter  af;
155         DB_LOCK locka, lockr;
156         int first = 1;
157
158         aliases = stack;        /* IDL of all aliases in the database */
159         curscop = aliases + BDB_IDL_DB_SIZE;    /* Aliases in the current scope */
160         subscop = curscop + BDB_IDL_DB_SIZE;    /* The current scope */
161         visited = subscop + BDB_IDL_DB_SIZE;    /* IDs we've seen in this search */
162         newsubs = visited + BDB_IDL_DB_SIZE;    /* New subtrees we've added */
163         oldsubs = newsubs + BDB_IDL_DB_SIZE;    /* Subtrees added previously */
164         tmp = oldsubs + BDB_IDL_DB_SIZE;        /* Scratch space for deref_base() */
165
166         /* A copy of subscop, because subscop gets clobbered by
167          * the bdb_idl_union/intersection routines
168          */
169         subscop2 = tmp + BDB_IDL_DB_SIZE;
170
171         af.f_choice = LDAP_FILTER_EQUALITY;
172         af.f_ava = &aa_alias;
173         af.f_av_desc = slap_schema.si_ad_objectClass;
174         af.f_av_value = bv_alias;
175         af.f_next = NULL;
176
177         /* Find all aliases in database */
178         BDB_IDL_ZERO( aliases );
179         rs->sr_err = bdb_filter_candidates( op, &af, aliases,
180                 curscop, visited );
181         if (rs->sr_err != LDAP_SUCCESS) {
182                 return rs->sr_err;
183         }
184         oldsubs[0] = 1;
185         oldsubs[1] = e->e_id;
186
187         BDB_IDL_ZERO( ids );
188         BDB_IDL_ZERO( visited );
189         BDB_IDL_ZERO( newsubs );
190
191         cursoro = 0;
192         ido = bdb_idl_first( oldsubs, &cursoro );
193
194         for (;;) {
195                 /* Set curscop to only the aliases in the current scope. Start with
196                  * all the aliases, obtain the IDL for the current scope, and then
197                  * get the intersection of these two IDLs. Add the current scope
198                  * to the cumulative list of candidates.
199                  */
200                 BDB_IDL_CPY( curscop, aliases );
201                 rs->sr_err = bdb_dn2idl( op, e, subscop,
202                         subscop2+BDB_IDL_DB_SIZE );
203                 if (first) {
204                         first = 0;
205                 } else {
206                         bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache, e, &locka);
207                 }
208                 BDB_IDL_CPY(subscop2, subscop);
209                 rs->sr_err = bdb_idl_intersection(curscop, subscop);
210                 bdb_idl_union( ids, subscop2 );
211
212                 /* Dereference all of the aliases in the current scope. */
213                 cursora = 0;
214                 for (ida = bdb_idl_first(curscop, &cursora); ida != NOID;
215                         ida = bdb_idl_next(curscop, &cursora))
216                 {
217                         ei = NULL;
218 retry1:
219                         rs->sr_err = bdb_cache_find_id(op, NULL,
220                                 ida, &ei, 0, locker, &lockr );
221                         if (rs->sr_err != LDAP_SUCCESS) {
222                                 if ( rs->sr_err == DB_LOCK_DEADLOCK ||
223                                         rs->sr_err == DB_LOCK_NOTGRANTED ) goto retry1;
224                                 continue;
225                         }
226                         a = ei->bei_e;
227
228                         /* This should only happen if the curscop IDL has maxed out and
229                          * turned into a range that spans IDs indiscriminately
230                          */
231                         if (!is_entry_alias(a)) {
232                                 bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache,
233                                         a, &lockr);
234                                 continue;
235                         }
236
237                         /* Actually dereference the alias */
238                         BDB_IDL_ZERO(tmp);
239                         a = deref_base( op, rs, a, &matched, locker, &lockr,
240                                 tmp, visited );
241                         if (a) {
242                                 /* If the target was not already in our current candidates,
243                                  * make note of it in the newsubs list. Also
244                                  * set it in the scopes list so that bdb_search
245                                  * can check it.
246                                  */
247                                 if (bdb_idl_insert(ids, a->e_id) == 0) {
248                                         bdb_idl_insert(newsubs, a->e_id);
249                                         bdb_idl_insert(scopes, a->e_id);
250                                 }
251                                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
252                                         a, &lockr);
253
254                         } else if (matched) {
255                                 /* Alias could not be dereferenced, or it deref'd to
256                                  * an ID we've already seen. Ignore it.
257                                  */
258                                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
259                                         matched, &lockr );
260                                 rs->sr_text = NULL;
261                         }
262                 }
263                 /* If this is a OneLevel search, we're done; oldsubs only had one
264                  * ID in it. For a Subtree search, oldsubs may be a list of scope IDs.
265                  */
266                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) break;
267 nextido:
268                 ido = bdb_idl_next( oldsubs, &cursoro );
269                 
270                 /* If we're done processing the old scopes, did we add any new
271                  * scopes in this iteration? If so, go back and do those now.
272                  */
273                 if (ido == NOID) {
274                         if (BDB_IDL_IS_ZERO(newsubs)) break;
275                         BDB_IDL_CPY(oldsubs, newsubs);
276                         BDB_IDL_ZERO(newsubs);
277                         cursoro = 0;
278                         ido = bdb_idl_first( oldsubs, &cursoro );
279                 }
280
281                 /* Find the entry corresponding to the next scope. If it can't
282                  * be found, ignore it and move on. This should never happen;
283                  * we should never see the ID of an entry that doesn't exist.
284                  * Set the name so that the scope's IDL can be retrieved.
285                  */
286                 ei = NULL;
287 sameido:
288                 rs->sr_err = bdb_cache_find_id(op, NULL, ido, &ei,
289                         0, locker, &locka );
290                 if ( rs->sr_err != LDAP_SUCCESS ) {
291                         if ( rs->sr_err == DB_LOCK_DEADLOCK ||
292                                 rs->sr_err == DB_LOCK_NOTGRANTED )
293                                 goto sameido;
294                         goto nextido;
295                 }
296                 e = ei->bei_e;
297         }
298         return rs->sr_err;
299 }
300
301 #define is_sync_protocol(op)    \
302         ((op)->o_sync_mode & SLAP_SYNC_REFRESH_AND_PERSIST)
303
304 #define IS_BDB_REPLACE(type) (( type == LDAP_PSEARCH_BY_DELETE ) || \
305         ( type == LDAP_PSEARCH_BY_SCOPEOUT ))
306 #define IS_PSEARCH (op != sop)
307
308 static Operation *
309 bdb_drop_psearch( Operation *op, ber_int_t msgid )
310 {
311         Operation       *ps_list;
312         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
313
314         LDAP_LIST_FOREACH ( ps_list, &bdb->bi_psearch_list, o_ps_link ) {
315                 if ( ps_list->o_connid == op->o_connid ) {
316                         if ( ps_list->o_msgid == msgid ) {
317                                 ps_list->o_abandon = 1;
318                                 LDAP_LIST_REMOVE( ps_list, o_ps_link );
319                                 ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
320                                 LDAP_STAILQ_REMOVE( &op->o_conn->c_ops, ps_list,
321                                         slap_op, o_next );
322                                 LDAP_STAILQ_NEXT( ps_list, o_next ) = NULL;
323                                 op->o_conn->c_n_ops_executing--;
324                                 op->o_conn->c_n_ops_completed++;
325                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
326                                 return ps_list;
327                         }
328                 }
329         }
330
331         return NULL;
332 }
333
334 int
335 bdb_abandon( Operation *op, SlapReply *rs )
336 {
337         Operation       *ps;
338
339         ps = bdb_drop_psearch( op, op->oq_abandon.rs_msgid );
340         if ( ps ) {
341                 if ( ps->o_tmpmemctx ) {
342                         slap_sl_mem_destroy( NULL, ps->o_tmpmemctx );
343                 }
344                 slap_op_free ( ps );
345                 return LDAP_SUCCESS;
346         }
347         return LDAP_UNAVAILABLE;
348 }
349
350 int
351 bdb_cancel( Operation *op, SlapReply *rs )
352 {
353         Operation       *ps;
354
355         ps = bdb_drop_psearch( op, op->oq_cancel.rs_msgid );
356         if ( ps ) {
357                 rs->sr_err = LDAP_CANCELLED;
358                 send_ldap_result( ps, rs );
359                 if ( ps->o_tmpmemctx ) {
360                         slap_sl_mem_destroy( NULL, ps->o_tmpmemctx );
361                 }
362                 slap_op_free ( ps );
363                 return LDAP_SUCCESS;
364         }
365         return LDAP_UNAVAILABLE;
366 }
367
368 int bdb_search( Operation *op, SlapReply *rs )
369 {
370         return bdb_do_search( op, rs, op, NULL, 0 );
371 }
372
373 int bdb_psearch( Operation *op, SlapReply *rs, Operation *sop,
374         Entry *ps_e, int ps_type )
375 {
376         int     rc;
377
378         sop->o_private = op->o_private;
379         rc = bdb_do_search( op, rs, sop, ps_e, ps_type );
380         sop->o_private = NULL;
381
382         return rc;
383 }
384
385 /* For persistent searches, op is the currently executing operation,
386  * sop is the persistent search. For regular searches, sop = op.
387  */
388 int
389 bdb_do_search( Operation *op, SlapReply *rs, Operation *sop,
390         Entry *ps_e, int ps_type )
391 {
392         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
393         time_t          stoptime;
394         ID              id, cursor;
395         ID              candidates[BDB_IDL_UM_SIZE];
396         ID              scopes[BDB_IDL_DB_SIZE];
397         Entry           *e = NULL, base, e_root = {0};
398         Entry           *matched = NULL;
399         EntryInfo       *ei, ei_root = {0};
400         struct berval   realbase = BER_BVNULL;
401         int             manageDSAit;
402         int             tentries = 0;
403         ID              lastid = NOID;
404         AttributeName   *attrs;
405
406         Filter          contextcsnand, contextcsnle, cookief, csnfnot,
407                         csnfeq, csnfand, csnfge;
408         AttributeAssertion aa_ge, aa_eq, aa_le;
409         struct berval   *search_context_csn = NULL;
410         DB_LOCK         ctxcsn_lock;
411         LDAPControl     *ctrls[SLAP_MAX_RESPONSE_CONTROLS];
412         int             num_ctrls = 0;
413         AttributeName   uuid_attr[2];
414         int             rc_sync = 0;
415         int             entry_sync_state = -1;
416         AttributeName   null_attr;
417         int             no_sync_state_change = 0;
418
419         u_int32_t       locker = 0;
420         DB_LOCK         lock;
421
422         Operation       *ps_list;
423         int                     sync_send_present_mode = 1;
424         int                     match;
425         MatchingRule *mr;
426         const char *text;
427         int                     slog_found = 0;
428
429         BerVarray       syncUUID_set = NULL;
430         int                     syncUUID_set_cnt = 0;
431
432         struct  bdb_op_info     *opinfo = NULL;
433         DB_TXN                  *ltid = NULL;
434
435 #ifdef NEW_LOGGING
436         LDAP_LOG( OPERATION, ENTRY, "bdb_search\n", 0, 0, 0 );
437 #else
438         Debug( LDAP_DEBUG_TRACE, "=> bdb_search\n", 0, 0, 0);
439 #endif
440         attrs = sop->oq_search.rs_attrs;
441
442         opinfo = (struct bdb_op_info *) op->o_private;
443
444         if ( !IS_PSEARCH && sop->o_sync_mode & SLAP_SYNC_REFRESH_AND_PERSIST ) {
445                 struct slap_session_entry *sent;
446                 if ( sop->o_sync_state.sid >= 0 ) {
447                         LDAP_LIST_FOREACH( sent, &bdb->bi_session_list, se_link ) {
448                                 if ( sent->se_id == sop->o_sync_state.sid ) {
449                                         sop->o_sync_slog_size = sent->se_size;
450                                         break;
451                                 }
452                         }
453                 }
454         }
455
456         /* psearch needs to be registered before refresh begins */
457         /* psearch and refresh transmission is serialized in send_ldap_ber() */
458         if ( !IS_PSEARCH && sop->o_sync_mode & SLAP_SYNC_PERSIST ) {
459                 ldap_pvt_thread_rdwr_wlock( &bdb->bi_pslist_rwlock );
460                 LDAP_LIST_INSERT_HEAD( &bdb->bi_psearch_list, sop, o_ps_link );
461                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_pslist_rwlock );
462
463         } else if ( !IS_PSEARCH && sop->o_sync_mode & SLAP_SYNC_REFRESH_AND_PERSIST
464                 && sop->o_sync_slog_size >= 0 )
465         {
466                 ldap_pvt_thread_rdwr_wlock( &bdb->bi_pslist_rwlock );
467                 LDAP_LIST_FOREACH( ps_list, &bdb->bi_psearch_list, o_ps_link ) {
468                         if ( ps_list->o_sync_slog_size >= 0 ) {
469                                 if ( ps_list->o_sync_state.sid == sop->o_sync_state.sid ) {
470                                         slog_found = 1;
471                                         break;
472                                 }
473                         }
474                 }
475
476                 if ( slog_found ) {
477                         if ( ps_list->o_sync_slog_omitcsn.bv_len != 0 ) {
478                                 mr = slap_schema.si_ad_entryCSN->ad_type->sat_ordering;
479                                 if ( sop->o_sync_state.ctxcsn &&
480                                         sop->o_sync_state.ctxcsn->bv_val != NULL )
481                                 {
482                                         value_match( &match, slap_schema.si_ad_entryCSN, mr,
483                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
484                                                 sop->o_sync_state.ctxcsn,
485                                                 &ps_list->o_sync_slog_omitcsn,
486                                                 &text );
487                                 } else {
488                                         match = -1;
489                                 }
490                                 if ( match >= 0 ) {
491                                         sync_send_present_mode = 0;
492                                 }
493                         } else {
494                                 sync_send_present_mode = 0;
495                         }
496                 } else if ( sop->o_sync_slog_size >= 0 ) {
497                         LDAP_LIST_INSERT_HEAD( &bdb->bi_psearch_list, sop, o_ps_link );
498                 } else {
499                         sop->o_sync_state.sid = -1;
500                 }
501                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_pslist_rwlock );
502         }
503
504         null_attr.an_desc = NULL;
505         null_attr.an_oc = NULL;
506         null_attr.an_oc_exclude = 0;
507         null_attr.an_name.bv_len = 0;
508         null_attr.an_name.bv_val = NULL;
509
510         for( num_ctrls = 0; num_ctrls < SLAP_MAX_RESPONSE_CONTROLS; num_ctrls++ ) {
511                 ctrls[num_ctrls] = NULL;
512         }
513         num_ctrls = 0;
514
515         if ( IS_PSEARCH && IS_BDB_REPLACE(ps_type)) {
516                 attrs = uuid_attr;
517                 attrs[0].an_desc = NULL;
518                 attrs[0].an_oc = NULL;
519                 attrs[0].an_oc_exclude = 0;
520                 attrs[0].an_name.bv_len = 0;
521                 attrs[0].an_name.bv_val = NULL;
522         }
523
524         manageDSAit = get_manageDSAit( sop );
525
526         /* Sync control overrides manageDSAit */
527         if ( !IS_PSEARCH && sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
528                 if ( manageDSAit == SLAP_NO_CONTROL ) {
529                         manageDSAit = SLAP_CRITICAL_CONTROL;
530                 }
531         } else if ( IS_PSEARCH ) {
532                 if ( manageDSAit == SLAP_NO_CONTROL ) {
533                         manageDSAit = SLAP_CRITICAL_CONTROL;
534                 }
535         }
536
537         if ( opinfo ) {
538                 ltid = opinfo->boi_txn;
539                 locker = TXN_ID( ltid );
540         } else {
541                 rs->sr_err = LOCK_ID( bdb->bi_dbenv, &locker );
542
543                 switch(rs->sr_err) {
544                 case 0:
545                         break;
546                 default:
547                         send_ldap_error( sop, rs, LDAP_OTHER, "internal error" );
548                         return rs->sr_err;
549                 }
550         }
551
552         if ( sop->o_req_ndn.bv_len == 0 ) {
553                 /* DIT root special case */
554                 ei_root.bei_e = &e_root;
555                 ei_root.bei_parent = &ei_root;
556                 e_root.e_private = &ei_root;
557                 e_root.e_id = 0;
558                 e_root.e_nname.bv_val="";
559                 e_root.e_name.bv_val="";
560                 ei = &ei_root;
561                 rs->sr_err = LDAP_SUCCESS;
562         } else {
563 dn2entry_retry:
564                 /* get entry with reader lock */
565                 rs->sr_err = bdb_dn2entry( op, ltid, &sop->o_req_ndn, &ei,
566                         1, locker, &lock );
567         }
568
569         switch(rs->sr_err) {
570         case DB_NOTFOUND:
571                 matched = ei->bei_e;
572                 break;
573         case 0:
574                 e = ei->bei_e;
575                 break;
576         case LDAP_BUSY:
577                 send_ldap_error( sop, rs, LDAP_BUSY, "ldap server busy" );
578                 if ( !opinfo )
579                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
580                 return LDAP_BUSY;
581         case DB_LOCK_DEADLOCK:
582         case DB_LOCK_NOTGRANTED:
583                 goto dn2entry_retry;
584         default:
585                 send_ldap_error( sop, rs, LDAP_OTHER, "internal error" );
586                 if ( !opinfo )
587                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
588                 return rs->sr_err;
589         }
590
591         if ( e && (op->ors_deref & LDAP_DEREF_FINDING) && is_entry_alias(e) ) {
592                 BDB_IDL_ZERO(candidates);
593                 e = deref_base( op, rs, e, &matched, locker, &lock,
594                         candidates, NULL );
595         }
596
597         if ( e == NULL ) {
598                 struct berval matched_dn = BER_BVNULL;
599
600                 if ( matched != NULL ) {
601                         BerVarray erefs;
602                         ber_dupbv( &matched_dn, &matched->e_name );
603
604                         erefs = is_entry_referral( matched )
605                                 ? get_entry_referrals( op, matched )
606                                 : NULL;
607
608                         bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache,
609                                 matched, &lock);
610                         matched = NULL;
611
612                         if( erefs ) {
613                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
614                                         &sop->o_req_dn, sop->oq_search.rs_scope );
615                                 ber_bvarray_free( erefs );
616                         }
617
618                 } else {
619                         rs->sr_ref = referral_rewrite( default_referral,
620                                 NULL, &sop->o_req_dn, sop->oq_search.rs_scope );
621                 }
622
623                 rs->sr_err = LDAP_REFERRAL;
624                 rs->sr_matched = matched_dn.bv_val;
625                 send_ldap_result( sop, rs );
626
627                 if ( !opinfo )
628                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
629                 if ( rs->sr_ref ) {
630                         ber_bvarray_free( rs->sr_ref );
631                         rs->sr_ref = NULL;
632                 }
633                 if ( matched_dn.bv_val ) {
634                         ber_memfree( matched_dn.bv_val );
635                         rs->sr_matched = NULL;
636                 }
637                 return rs->sr_err;
638         }
639
640         if ( !manageDSAit && e != &e_root && is_entry_referral( e ) ) {
641                 /* entry is a referral, don't allow add */
642                 struct berval matched_dn;
643                 BerVarray erefs;
644                 
645                 ber_dupbv( &matched_dn, &e->e_name );
646                 erefs = get_entry_referrals( op, e );
647
648                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache, e, &lock );
649                 e = NULL;
650
651                 if( erefs ) {
652                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
653                                 &sop->o_req_dn, sop->oq_search.rs_scope );
654                         ber_bvarray_free( erefs );
655                 }
656
657 #ifdef NEW_LOGGING
658                 LDAP_LOG ( OPERATION, RESULTS, 
659                         "bdb_search: entry is referral\n", 0, 0, 0 );
660 #else
661                 Debug( LDAP_DEBUG_TRACE, "bdb_search: entry is referral\n",
662                         0, 0, 0 );
663 #endif
664
665                 if (!rs->sr_ref) rs->sr_text = "bad_referral object";
666                 rs->sr_err = LDAP_REFERRAL;
667                 rs->sr_matched = matched_dn.bv_val;
668                 send_ldap_result( sop, rs );
669
670                 if ( !opinfo )
671                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
672                 ber_bvarray_free( rs->sr_ref );
673                 rs->sr_ref = NULL;
674                 ber_memfree( matched_dn.bv_val );
675                 rs->sr_matched = NULL;
676                 return 1;
677         }
678
679         if ( get_assert( op ) &&
680                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
681         {
682                 rs->sr_err = LDAP_ASSERTION_FAILED;
683                 send_ldap_result( sop, rs );
684                 return 1;
685         }
686
687         /* compute it anyway; root does not use it */
688         stoptime = op->o_time + sop->ors_tlimit;
689
690         /* need normalized dn below */
691         ber_dupbv( &realbase, &e->e_nname );
692
693         /* Copy info to base, must free entry before accessing the database
694          * in search_candidates, to avoid deadlocks.
695          */
696         base.e_private = e->e_private;
697         base.e_nname = realbase;
698         base.e_id = e->e_id;
699
700         if ( e != &e_root ) {
701                 bdb_cache_return_entry_r(bdb->bi_dbenv, &bdb->bi_cache, e, &lock);
702         }
703         e = NULL;
704
705         if ( !IS_PSEARCH ) {
706                 rs->sr_err = bdb_get_commit_csn( sop, rs, &search_context_csn,
707                         locker, &ctxcsn_lock );
708
709                 if ( rs->sr_err != LDAP_SUCCESS ) {
710                         send_ldap_error( sop, rs, rs->sr_err,
711                                 "error in csn management in search" );
712                         goto done;
713                 }
714
715                 if ( sop->o_sync_mode != SLAP_SYNC_NONE &&
716                         sop->o_sync_state.ctxcsn &&
717                         sop->o_sync_state.ctxcsn->bv_val &&
718                         ber_bvcmp( &sop->o_sync_state.ctxcsn[0], search_context_csn ) == 0 )
719                 {
720                         bdb_cache_entry_db_unlock( bdb->bi_dbenv, &ctxcsn_lock );
721                         goto nochange;
722                 }
723         } else {
724                 search_context_csn = ber_dupbv( NULL, &op->o_sync_csn );        
725         }
726
727         /* select candidates */
728         if ( sop->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
729                 rs->sr_err = base_candidate( op->o_bd, &base, candidates );
730
731         } else {
732                 BDB_IDL_ZERO( candidates );
733                 BDB_IDL_ZERO( scopes );
734                 rs->sr_err = search_candidates( op, sop, rs, &base,
735                         locker, candidates, scopes );
736         }
737
738         if ( !IS_PSEARCH && sop->o_sync_mode != SLAP_SYNC_NONE ) {
739                 bdb_cache_entry_db_unlock( bdb->bi_dbenv, &ctxcsn_lock );
740         }
741
742         /* start cursor at beginning of candidates.
743          */
744         cursor = 0;
745         if (IS_PSEARCH) {
746                 if ( !BDB_IDL_IS_RANGE( candidates ) ) {
747                         cursor = bdb_idl_search( candidates, ps_e->e_id );
748                         if ( candidates[cursor] != ps_e->e_id ) {
749                                 rs->sr_err = LDAP_SUCCESS;
750                                 goto done;
751                         }
752                 } else if ( ps_e->e_id < BDB_IDL_RANGE_FIRST( candidates ) ||
753                         ps_e->e_id > BDB_IDL_RANGE_LAST( candidates ))
754                 {
755                         rs->sr_err = LDAP_SUCCESS;
756                         goto done;
757                 }
758                 candidates[0] = 1;
759                 candidates[1] = ps_e->e_id;
760         }
761
762         if ( candidates[0] == 0 ) {
763 #ifdef NEW_LOGGING
764                 LDAP_LOG ( OPERATION, RESULTS,
765                         "bdb_search: no candidates\n", 0, 0, 0 );
766 #else
767                 Debug( LDAP_DEBUG_TRACE, "bdb_search: no candidates\n",
768                         0, 0, 0 );
769 #endif
770
771                 goto nochange;
772         }
773
774         /* if not root and candidates exceed to-be-checked entries, abort */
775         if ( sop->ors_limit     /* isroot == TRUE */ &&
776                 sop->ors_limit->lms_s_unchecked != -1 &&
777                 BDB_IDL_N(candidates) > (unsigned) sop->ors_limit->lms_s_unchecked )
778         {
779                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
780                 send_ldap_result( sop, rs );
781                 rs->sr_err = LDAP_SUCCESS;
782                 goto done;
783         }
784
785         if ( sop->ors_limit == NULL     /* isroot == FALSE */ ||
786                 !sop->ors_limit->lms_s_pr_hide )
787         {
788                 tentries = BDB_IDL_N(candidates);
789         }
790
791         if ( get_pagedresults(sop) > SLAP_NO_CONTROL ) {
792                 if ( (ID)( sop->o_pagedresults_state.ps_cookie ) == 0 ) {
793                         id = bdb_idl_first( candidates, &cursor );
794
795                 } else {
796                         if ( sop->o_pagedresults_size == 0 ) {
797                                 rs->sr_err = LDAP_SUCCESS;
798                                 rs->sr_text = "search abandoned by pagedResult size=0";
799                                 send_ldap_result( sop, rs );
800                                 goto done;
801                         }
802                         for ( id = bdb_idl_first( candidates, &cursor );
803                                 id != NOID &&
804                                         id <= (ID)( sop->o_pagedresults_state.ps_cookie );
805                                 id = bdb_idl_next( candidates, &cursor ) )
806                         {
807                                 /* empty */;
808                         }
809                 }
810
811                 if ( cursor == NOID ) {
812 #ifdef NEW_LOGGING
813                         LDAP_LOG ( OPERATION, RESULTS, 
814                                 "bdb_search: no paged results candidates\n", 
815                                 0, 0, 0 );
816 #else
817                         Debug( LDAP_DEBUG_TRACE, 
818                                 "bdb_search: no paged results candidates\n",
819                                 0, 0, 0 );
820 #endif
821                         send_paged_response( sop, rs, &lastid, 0 );
822
823                         rs->sr_err = LDAP_OTHER;
824                         goto done;
825                 }
826                 goto loop_begin;
827         }
828
829         if (( sop->o_sync_mode & SLAP_SYNC_REFRESH ) || IS_PSEARCH ) {
830                 int match;
831
832                 cookief.f_choice = LDAP_FILTER_AND;
833                 cookief.f_and = &csnfnot;
834                 cookief.f_next = NULL;
835
836                 csnfnot.f_choice = LDAP_FILTER_NOT;
837                 csnfnot.f_not = &csnfeq;
838                 csnfnot.f_next = &csnfand;
839
840                 csnfeq.f_choice = LDAP_FILTER_EQUALITY;
841                 csnfeq.f_ava = &aa_eq;
842                 csnfeq.f_av_desc = slap_schema.si_ad_entryCSN;
843                 if ( sop->o_sync_state.ctxcsn != NULL ) {
844                         csnfeq.f_av_value = *sop->o_sync_state.ctxcsn;
845                 } else {
846                         csnfeq.f_av_value = slap_empty_bv;
847                 }
848
849                 csnfand.f_choice = LDAP_FILTER_AND;
850                 csnfand.f_and = &csnfge;
851                 csnfand.f_next = NULL;
852
853                 csnfge.f_choice = LDAP_FILTER_GE;
854                 csnfge.f_ava = &aa_ge;
855                 csnfge.f_av_desc = slap_schema.si_ad_entryCSN;
856                 if ( sop->o_sync_state.ctxcsn != NULL ) {
857                         csnfge.f_av_value = *sop->o_sync_state.ctxcsn;
858                 } else {
859                         csnfge.f_av_value = slap_empty_bv;
860                 }
861
862                 if ( search_context_csn && !IS_PSEARCH ) {
863                         csnfge.f_next = &contextcsnand;
864
865                         contextcsnand.f_choice = LDAP_FILTER_AND;
866                         contextcsnand.f_and = &contextcsnle;
867                         contextcsnand.f_next = NULL;
868         
869                         contextcsnle.f_choice = LDAP_FILTER_LE;
870                         contextcsnle.f_ava = &aa_le;
871                         contextcsnle.f_av_desc = slap_schema.si_ad_entryCSN;
872                         contextcsnle.f_av_value = *search_context_csn;
873                         contextcsnle.f_next = sop->oq_search.rs_filter;
874
875                         mr = slap_schema.si_ad_entryCSN->ad_type->sat_ordering;
876                         if ( sop->o_sync_state.ctxcsn &&
877                                 sop->o_sync_state.ctxcsn->bv_val != NULL )
878                         {
879                                 value_match( &match, slap_schema.si_ad_entryCSN, mr,
880                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
881                                                 &sop->o_sync_state.ctxcsn[0], search_context_csn,
882                                                 &text );
883                         } else {
884                                 match = -1;
885                         }
886                         no_sync_state_change = ( match >= 0 );
887                 } else {
888                         csnfge.f_next = sop->oq_search.rs_filter;
889                 }
890         }
891
892         for ( id = bdb_idl_first( candidates, &cursor );
893                 id != NOID && !no_sync_state_change;
894                 id = bdb_idl_next( candidates, &cursor ) )
895         {
896                 int scopeok = 0;
897
898 loop_begin:
899                 /* check for abandon */
900                 if ( sop->o_abandon ) {
901                         if ( sop != op ) {
902                                 bdb_drop_psearch( sop, sop->o_msgid );
903                         }
904                         rs->sr_err = LDAP_SUCCESS;
905                         goto done;
906                 }
907
908                 if ( sop->o_cancel ) {
909                         assert( sop->o_cancel == SLAP_CANCEL_REQ );
910                         rs->sr_err = LDAP_CANCELLED;
911                         send_ldap_result( sop, rs );
912                         sop->o_cancel = SLAP_CANCEL_ACK;
913                         rs->sr_err = LDAP_SUCCESS;
914                         goto done;
915                 }
916
917                 /* check time limit */
918                 if ( sop->ors_tlimit != SLAP_NO_LIMIT
919                                 && slap_get_time() > stoptime )
920                 {
921                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
922                         rs->sr_ref = rs->sr_v2ref;
923                         send_ldap_result( sop, rs );
924                         rs->sr_err = LDAP_SUCCESS;
925                         goto done;
926                 }
927
928                 if (!IS_PSEARCH) {
929 id2entry_retry:
930                         /* get the entry with reader lock */
931                         ei = NULL;
932                         rs->sr_err = bdb_cache_find_id( op, ltid,
933                                 id, &ei, 0, locker, &lock );
934
935                         if (rs->sr_err == LDAP_BUSY) {
936                                 rs->sr_text = "ldap server busy";
937                                 send_ldap_result( sop, rs );
938                                 goto done;
939
940                         } else if ( rs->sr_err == DB_LOCK_DEADLOCK
941                                 || rs->sr_err == DB_LOCK_NOTGRANTED )
942                         {
943                                 goto id2entry_retry;    
944                         }
945
946                         if ( ei && rs->sr_err == LDAP_SUCCESS ) {
947                                 e = ei->bei_e;
948                         } else {
949                                 e = NULL;
950                         }
951
952                         if ( e == NULL ) {
953                                 if( !BDB_IDL_IS_RANGE(candidates) ) {
954                                         /* only complain for non-range IDLs */
955 #ifdef NEW_LOGGING
956                                         LDAP_LOG ( OPERATION, RESULTS,
957                                                 "bdb_search: candidate %ld not found\n",
958                                                 (long) id, 0, 0);
959 #else
960                                         Debug( LDAP_DEBUG_TRACE,
961                                                 "bdb_search: candidate %ld not found\n",
962                                                 (long) id, 0, 0 );
963 #endif
964                                 }
965
966                                 goto loop_continue;
967                         }
968                 } else {
969                         e = ps_e;
970                 }
971
972                 rs->sr_entry = e;
973
974 #ifdef BDB_SUBENTRIES
975                 /* FIXME: send all but syncrepl */
976 #if 0
977                 if ( !is_sync_protocol( sop ) )
978 #endif
979                 {
980                         if ( is_entry_subentry( e ) ) {
981                                 if( sop->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
982                                         if(!get_subentries_visibility( sop )) {
983                                                 /* only subentries are visible */
984                                                 goto loop_continue;
985                                         }
986
987                                 } else if ( get_subentries( sop ) &&
988                                         !get_subentries_visibility( sop ))
989                                 {
990                                         /* only subentries are visible */
991                                         goto loop_continue;
992                                 }
993
994                         } else if ( get_subentries_visibility( sop )) {
995                                 /* only subentries are visible */
996                                 goto loop_continue;
997                         }
998                 }
999 #endif /* BDB_SUBENTRIES */
1000
1001                 /* Does this candidate actually satisfy the search scope?
1002                  *
1003                  * Note that we don't lock access to the bei_parent pointer.
1004                  * Since only leaf nodes can be deleted, the parent of any
1005                  * node will always be a valid node. Also since we have
1006                  * a Read lock on the data, it cannot be renamed out of the
1007                  * scope while we are looking at it, and unless we're using
1008                  * BDB_HIER, its parents cannot be moved either.
1009                  */
1010                 switch( sop->ors_scope ) {
1011                 case LDAP_SCOPE_BASE:
1012                         /* This is always true, yes? */
1013                         if ( id == base.e_id ) scopeok = 1;
1014                         break;
1015
1016                 case LDAP_SCOPE_ONELEVEL:
1017                         if ( ei->bei_parent->bei_id == base.e_id ) scopeok = 1;
1018                         break;
1019
1020 #ifdef LDAP_SCOPE_CHILDREN
1021                 case LDAP_SCOPE_CHILDREN:
1022                         if ( id == base.e_id ) break;
1023                         /* Fall-thru */
1024 #endif
1025                 case LDAP_SCOPE_SUBTREE: {
1026                         EntryInfo *tmp;
1027                         for (tmp = BEI(e); tmp;
1028                                  tmp = tmp->bei_parent ) {
1029                                 if ( tmp->bei_id == base.e_id ) {
1030                                         scopeok = 1;
1031                                         break;
1032                                 }
1033                         }
1034                         } break;
1035                 }
1036
1037 #ifdef BDB_ALIASES
1038                 /* aliases were already dereferenced in candidate list */
1039                 if ( sop->ors_deref & LDAP_DEREF_SEARCHING ) {
1040                         /* but if the search base is an alias, and we didn't
1041                          * deref it when finding, return it.
1042                          */
1043                         if ( is_entry_alias(e) &&
1044                                 ((sop->ors_deref & LDAP_DEREF_FINDING) ||
1045                                         !bvmatch(&e->e_nname, &op->o_req_ndn)))
1046                         {
1047                                 goto loop_continue;
1048                         }
1049
1050                         /* scopes is only non-empty for onelevel or subtree */
1051                         if ( !scopeok && BDB_IDL_N(scopes) ) {
1052                                 unsigned x;
1053                                 if ( sop->ors_scope == LDAP_SCOPE_ONELEVEL ) {
1054                                         x = bdb_idl_search( scopes, e->e_id );
1055                                         if ( scopes[x] == e->e_id ) scopeok = 1;
1056                                 } else {
1057                                         /* subtree, walk up the tree */
1058                                         EntryInfo *tmp = BEI(e);
1059                                         for (;tmp->bei_parent; tmp=tmp->bei_parent) {
1060                                                 x = bdb_idl_search( scopes, tmp->bei_id );
1061                                                 if ( scopes[x] == tmp->bei_id ) {
1062                                                         scopeok = 1;
1063                                                         break;
1064                                                 }
1065                                         }
1066                                 }
1067                         }
1068                 }
1069 #endif
1070
1071                 /* Not in scope, ignore it */
1072                 if ( !scopeok ) {
1073 #ifdef NEW_LOGGING
1074                         LDAP_LOG ( OPERATION, RESULTS,
1075                                 "bdb_search: %ld scope not okay\n",
1076                                 (long) id, 0, 0);
1077 #else
1078                         Debug( LDAP_DEBUG_TRACE,
1079                                 "bdb_search: %ld scope not okay\n",
1080                                 (long) id, 0, 0 );
1081 #endif
1082                         goto loop_continue;
1083                 }
1084
1085                 /*
1086                  * if it's a referral, add it to the list of referrals. only do
1087                  * this for non-base searches, and don't check the filter
1088                  * explicitly here since it's only a candidate anyway.
1089                  */
1090                 if ( !manageDSAit && sop->oq_search.rs_scope != LDAP_SCOPE_BASE
1091                         && is_entry_referral( e ) )
1092                 {
1093                         BerVarray erefs = get_entry_referrals( sop, e );
1094                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
1095                                 sop->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
1096                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
1097
1098                         send_search_reference( sop, rs );
1099
1100                         ber_bvarray_free( rs->sr_ref );
1101                         ber_bvarray_free( erefs );
1102                         rs->sr_ref = NULL;
1103
1104                         goto loop_continue;
1105                 }
1106
1107                 if ( !manageDSAit && is_entry_glue( e )) {
1108                         goto loop_continue;
1109                 }
1110
1111                 /* if it matches the filter and scope, send it */
1112                 if (IS_PSEARCH) {
1113                         if (ps_type != LDAP_PSEARCH_BY_SCOPEOUT) {
1114                                 rs->sr_err = test_filter( sop, rs->sr_entry, &cookief );
1115                         } else {
1116                                 rs->sr_err = LDAP_COMPARE_TRUE;
1117                         }
1118
1119                 } else {
1120                         if ( sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
1121                                 rc_sync = test_filter( sop, rs->sr_entry, &cookief );
1122                                 rs->sr_err = test_filter( sop, rs->sr_entry, &contextcsnand );
1123                                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
1124                                         if ( rc_sync == LDAP_COMPARE_TRUE ) {
1125                                                 if ( no_sync_state_change ) {
1126 #ifdef NEW_LOGGING
1127                                                         LDAP_LOG ( OPERATION, RESULTS,
1128                                                                 "bdb_search: error in context csn management\n",
1129                                                                 0, 0, 0 );
1130 #else
1131                                                         Debug( LDAP_DEBUG_TRACE,
1132                                                                 "bdb_search: error in context csn management\n",
1133                                                                 0, 0, 0 );
1134 #endif
1135                                                 }
1136                                                 entry_sync_state = LDAP_SYNC_ADD;
1137
1138                                         } else {
1139                                                 if ( no_sync_state_change ) {
1140                                                         goto loop_continue;
1141                                                 }
1142                                                 entry_sync_state = LDAP_SYNC_PRESENT;
1143                                         }
1144                                 }
1145
1146                         } else {
1147                                 rs->sr_err = test_filter( sop,
1148                                         rs->sr_entry, sop->oq_search.rs_filter );
1149                         }
1150                 }
1151
1152                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
1153                         /* check size limit */
1154                         if ( --sop->ors_slimit == -1 &&
1155                                 sop->o_sync_slog_size == -1 )
1156                         {
1157                                 if (!IS_PSEARCH) {
1158                                         bdb_cache_return_entry_r( bdb->bi_dbenv,
1159                                                 &bdb->bi_cache, e, &lock );
1160                                 }
1161                                 e = NULL;
1162                                 rs->sr_entry = NULL;
1163                                 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
1164                                 rs->sr_ref = rs->sr_v2ref;
1165                                 send_ldap_result( sop, rs );
1166                                 rs->sr_err = LDAP_SUCCESS;
1167                                 goto done;
1168                         }
1169
1170                         if ( get_pagedresults(sop) > SLAP_NO_CONTROL ) {
1171                                 if ( rs->sr_nentries >= sop->o_pagedresults_size ) {
1172                                         send_paged_response( sop, rs, &lastid, tentries );
1173                                         goto done;
1174                                 }
1175                                 lastid = id;
1176                         }
1177
1178                         if (e) {
1179                                 /* safe default */
1180                                 int result = -1;
1181                                 
1182                                 if (IS_PSEARCH) {
1183                                         int premodify_found = 0;
1184                                         int entry_sync_state;
1185
1186                                         if ( ps_type == LDAP_PSEARCH_BY_ADD ||
1187                                                  ps_type == LDAP_PSEARCH_BY_DELETE ||
1188                                                  ps_type == LDAP_PSEARCH_BY_MODIFY ||
1189                                                  ps_type == LDAP_PSEARCH_BY_SCOPEOUT )
1190                                         {
1191                                                 if ( ps_type == LDAP_PSEARCH_BY_MODIFY ) {
1192                                                         struct psid_entry* psid_e;
1193                                                         LDAP_LIST_FOREACH( psid_e,
1194                                                                 &op->o_pm_list, ps_link)
1195                                                         {
1196                                                                 if( psid_e->ps_op == sop ) {
1197                                                                         premodify_found = 1;
1198                                                                         LDAP_LIST_REMOVE(psid_e, ps_link);
1199                                                                         break;
1200                                                                 }
1201                                                         }
1202                                                         if (psid_e != NULL) free (psid_e);
1203                                                 }
1204
1205                                                 if ( ps_type == LDAP_PSEARCH_BY_ADD ) {
1206                                                         entry_sync_state = LDAP_SYNC_ADD;
1207                                                 } else if ( ps_type == LDAP_PSEARCH_BY_DELETE ) {
1208                                                         entry_sync_state = LDAP_SYNC_DELETE;
1209                                                 } else if ( ps_type == LDAP_PSEARCH_BY_MODIFY ) {
1210                                                         if ( premodify_found ) {
1211                                                                 entry_sync_state = LDAP_SYNC_MODIFY;
1212                                                         } else {
1213                                                                 entry_sync_state = LDAP_SYNC_ADD;
1214                                                         }
1215                                                 } else if ( ps_type == LDAP_PSEARCH_BY_SCOPEOUT ) {
1216                                                         entry_sync_state = LDAP_SYNC_DELETE;
1217                                                 } else {
1218                                                         rs->sr_err = LDAP_OTHER;
1219                                                         goto done;
1220                                                 }
1221
1222                                                 if ( sop->o_sync_slog_size != -1 ) {
1223                                                         if ( entry_sync_state == LDAP_SYNC_DELETE ) {
1224                                                                 result = slap_add_session_log( op, sop, e );
1225                                                         } else {
1226                                                                 result = 1;
1227                                                         }
1228                                                 } else {
1229                                                         struct berval cookie;
1230                                                         slap_compose_sync_cookie( sop, &cookie,
1231                                                                 search_context_csn,
1232                                                                 sop->o_sync_state.sid,
1233                                                                 sop->o_sync_state.rid );
1234                                                         rs->sr_err = slap_build_sync_state_ctrl( sop,
1235                                                                 rs, e, entry_sync_state, ctrls,
1236                                                                 num_ctrls++, 1, &cookie );
1237                                                         if ( rs->sr_err != LDAP_SUCCESS ) goto done;
1238                                                         rs->sr_attrs = attrs;
1239                                                         rs->sr_ctrls = ctrls;
1240                                                         rs->sr_flags = 0;
1241                                                         result = send_search_entry( sop, rs );
1242                                                         if ( cookie.bv_val ) ch_free( cookie.bv_val );  
1243                                                         slap_sl_free(
1244                                                                 ctrls[num_ctrls-1]->ldctl_value.bv_val,
1245                                                                 sop->o_tmpmemctx );
1246                                                         slap_sl_free( ctrls[--num_ctrls],
1247                                                                 sop->o_tmpmemctx );
1248                                                         ctrls[num_ctrls] = NULL;
1249                                                         rs->sr_ctrls = NULL;
1250                                                 }
1251
1252                                         } else if ( ps_type == LDAP_PSEARCH_BY_PREMODIFY ) {
1253                                                 struct psid_entry* psid_e;
1254                                                 psid_e = (struct psid_entry *) ch_calloc(1,
1255                                                         sizeof(struct psid_entry));
1256                                                 psid_e->ps_op = sop;
1257                                                 LDAP_LIST_INSERT_HEAD( &op->o_pm_list,
1258                                                         psid_e, ps_link );
1259
1260                                         } else {
1261 #ifdef NEW_LOGGING
1262                                                 LDAP_LOG ( OPERATION, RESULTS,
1263                                                         "bdb_search: invalid ps_type (%d) \n",
1264                                                         ps_type, 0, 0);
1265 #else
1266                                                 Debug( LDAP_DEBUG_TRACE,
1267                                                         "bdb_search: invalid ps_type (%d) \n",
1268                                                         ps_type, 0, 0);
1269 #endif
1270                                         }
1271
1272                                 } else {
1273                                         if ( sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
1274                                                 if ( rc_sync == LDAP_COMPARE_TRUE ) { /* ADD */
1275                                                         rs->sr_err = slap_build_sync_state_ctrl( sop,
1276                                                                 rs, e, entry_sync_state, ctrls,
1277                                                                 num_ctrls++, 0, NULL );
1278                                                         if ( rs->sr_err != LDAP_SUCCESS ) goto done;
1279                                                         rs->sr_ctrls = ctrls;
1280                                                         rs->sr_attrs = sop->oq_search.rs_attrs;
1281                                                         rs->sr_flags = 0;
1282                                                         result = send_search_entry( sop, rs );
1283                                                         slap_sl_free(
1284                                                                 ctrls[num_ctrls-1]->ldctl_value.bv_val,
1285                                                                 sop->o_tmpmemctx );
1286                                                         slap_sl_free( ctrls[--num_ctrls],
1287                                                                 sop->o_tmpmemctx );
1288                                                         ctrls[num_ctrls] = NULL;
1289                                                         rs->sr_ctrls = NULL;
1290
1291                                                 } else { /* PRESENT */
1292                                                         if ( sync_send_present_mode ) {
1293                                                                 result = slap_build_syncUUID_set( sop,
1294                                                                         &syncUUID_set, e );
1295                                                                 if ( result <= 0 ) {
1296                                                                         result = -1;    
1297                                                                 } else {
1298                                                                         syncUUID_set_cnt++;
1299                                                                         if ( syncUUID_set_cnt ==
1300                                                                                 SLAP_SYNCUUID_SET_SIZE )
1301                                                                         {
1302                                                                                 rs->sr_err = LDAP_SUCCESS;
1303                                                                                 rs->sr_rspoid = LDAP_SYNC_INFO;
1304                                                                                 rs->sr_ctrls = NULL;
1305                                                                                 result = slap_send_syncinfo( sop, rs,
1306                                                                                         LDAP_TAG_SYNC_ID_SET,
1307                                                                                         NULL, 0, syncUUID_set, 0 );
1308                                                                                 if ( result != LDAP_SUCCESS ) {
1309                                                                                         result = -1;
1310                                                                                 }
1311                                                                                 ber_bvarray_free_x( syncUUID_set,
1312                                                                                         sop->o_tmpmemctx );
1313                                                                                 syncUUID_set = NULL;
1314                                                                                 syncUUID_set_cnt = 0;
1315                                                                         }
1316                                                                 }
1317
1318                                                         } else {
1319                                                                 result = 1;
1320                                                         }
1321                                                 }
1322
1323                                         } else {
1324                                                 rs->sr_attrs = sop->oq_search.rs_attrs;
1325                                                 rs->sr_ctrls = NULL;
1326                                                 rs->sr_flags = 0;
1327                                                 rs->sr_err = LDAP_SUCCESS;
1328                                                 result = send_search_entry( sop, rs );
1329                                         }
1330                                 }
1331
1332                                 switch (result) {
1333                                 case 0:         /* entry sent ok */
1334                                         break;
1335                                 case 1:         /* entry not sent */
1336                                         break;
1337                                 case -1:        /* connection closed */
1338                                         if (!IS_PSEARCH) {
1339                                                 bdb_cache_return_entry_r(bdb->bi_dbenv,
1340                                                         &bdb->bi_cache, e, &lock);
1341                                         }
1342                                         e = NULL;
1343                                         rs->sr_entry = NULL;
1344                                         rs->sr_err = LDAP_OTHER;
1345                                         goto done;
1346                                 }
1347                         }
1348
1349                 } else {
1350 #ifdef NEW_LOGGING
1351                         LDAP_LOG ( OPERATION, RESULTS,
1352                                 "bdb_search: %ld does not match filter\n", (long) id, 0, 0);
1353 #else
1354                         Debug( LDAP_DEBUG_TRACE,
1355                                 "bdb_search: %ld does not match filter\n",
1356                                 (long) id, 0, 0 );
1357 #endif
1358                 }
1359
1360 loop_continue:
1361                 if( e != NULL ) {
1362                         /* free reader lock */
1363                         if (!IS_PSEARCH) {
1364                                 bdb_cache_return_entry_r( bdb->bi_dbenv,
1365                                         &bdb->bi_cache, e , &lock );
1366                                 if ( sop->o_nocaching ) {
1367                                         bdb_cache_delete_entry( bdb, ei, locker, &lock );
1368                                 }
1369                         }
1370                         e = NULL;
1371                         rs->sr_entry = NULL;
1372                 }
1373
1374                 ldap_pvt_thread_yield();
1375         }
1376
1377         if ( syncUUID_set_cnt > 0 ) {
1378                 rs->sr_err = LDAP_SUCCESS;
1379                 rs->sr_rspoid = LDAP_SYNC_INFO;
1380                 rs->sr_ctrls = NULL;
1381                 slap_send_syncinfo( sop, rs, LDAP_TAG_SYNC_ID_SET,
1382                         NULL, 0, syncUUID_set, 0 );
1383                 ber_bvarray_free_x( syncUUID_set, sop->o_tmpmemctx );
1384                 syncUUID_set_cnt = 0;
1385         }
1386
1387 nochange:
1388         if (!IS_PSEARCH) {
1389                 if ( sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
1390                         if ( sop->o_sync_mode & SLAP_SYNC_PERSIST ) {
1391                                 struct berval cookie;
1392                                 slap_compose_sync_cookie( sop, &cookie, search_context_csn,
1393                                         sop->o_sync_state.sid, sop->o_sync_state.rid );
1394
1395                                 if ( sync_send_present_mode ) {
1396                                         rs->sr_err = LDAP_SUCCESS;
1397                                         rs->sr_rspoid = LDAP_SYNC_INFO;
1398                                         rs->sr_ctrls = NULL;
1399                                         slap_send_syncinfo( sop, rs,
1400                                                 LDAP_TAG_SYNC_REFRESH_PRESENT, &cookie, 1, NULL, 0 );
1401
1402                                 } else {
1403                                         if ( !no_sync_state_change ) {
1404                                                 int slog_found = 0;
1405                                                 ldap_pvt_thread_rdwr_rlock( &bdb->bi_pslist_rwlock );
1406                                                 LDAP_LIST_FOREACH( ps_list, &bdb->bi_psearch_list,
1407                                                         o_ps_link )
1408                                                 {
1409                                                         if ( ps_list->o_sync_slog_size > 0 ) {
1410                                                                 if ( ps_list->o_sync_state.sid ==
1411                                                                         sop->o_sync_state.sid )
1412                                                                 {
1413                                                                         slog_found = 1;
1414                                                                         break;
1415                                                                 }
1416                                                         }
1417                                                 }
1418                 
1419                                                 if ( slog_found ) {
1420                                                         rs->sr_err = LDAP_SUCCESS;
1421                                                         rs->sr_rspoid = NULL;
1422                                                         rs->sr_ctrls = NULL;
1423                                                         slap_send_session_log( op, ps_list, rs );
1424                                                 }
1425                                                 ldap_pvt_thread_rdwr_runlock( &bdb->bi_pslist_rwlock );
1426                                         }
1427
1428                                         rs->sr_err = LDAP_SUCCESS;
1429                                         rs->sr_rspoid = LDAP_SYNC_INFO;
1430                                         rs->sr_ctrls = NULL;
1431                                         slap_send_syncinfo( sop, rs,
1432                                                 LDAP_TAG_SYNC_REFRESH_DELETE, &cookie, 1, NULL, 0 );
1433                                 }
1434
1435                                 if ( cookie.bv_val ) ch_free( cookie.bv_val );
1436
1437                         } else {
1438                                 /* refreshOnly mode */
1439                                 struct berval cookie;
1440                                 slap_compose_sync_cookie( sop, &cookie, search_context_csn,
1441                                         sop->o_sync_state.sid, sop->o_sync_state.rid );
1442
1443                                 if ( sync_send_present_mode ) {
1444                                         slap_build_sync_done_ctrl( sop, rs, ctrls,
1445                                                 num_ctrls++, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
1446
1447                                 } else {
1448                                         if ( !no_sync_state_change ) {
1449                                                 int slog_found = 0;
1450                                                 ldap_pvt_thread_rdwr_rlock( &bdb->bi_pslist_rwlock );
1451                                                 LDAP_LIST_FOREACH( ps_list, &bdb->bi_psearch_list,
1452                                                         o_ps_link )
1453                                                 {
1454                                                         if ( ps_list->o_sync_slog_size > 0 ) {
1455                                                                 if ( ps_list->o_sync_state.sid ==
1456                                                                                 sop->o_sync_state.sid ) {
1457                                                                         slog_found = 1;
1458                                                                         break;
1459                                                                 }
1460                                                         }
1461                                                 }
1462                 
1463                                                 if ( slog_found ) {
1464                                                         slap_send_session_log( op, ps_list, rs );
1465                                                 }
1466                                                 ldap_pvt_thread_rdwr_runlock( &bdb->bi_pslist_rwlock );
1467                                         }
1468
1469                                         slap_build_sync_done_ctrl( sop, rs, ctrls,
1470                                                 num_ctrls++, 1, &cookie, LDAP_SYNC_REFRESH_DELETES );
1471                                 }
1472
1473                                 rs->sr_ctrls = ctrls;
1474                                 rs->sr_ref = rs->sr_v2ref;
1475                                 rs->sr_err = (rs->sr_v2ref == NULL)
1476                                         ? LDAP_SUCCESS : LDAP_REFERRAL;
1477                                 rs->sr_rspoid = NULL;
1478                                 send_ldap_result( sop, rs );
1479                                 if ( ctrls[num_ctrls-1]->ldctl_value.bv_val != NULL ) {
1480                                         slap_sl_free( ctrls[num_ctrls-1]->ldctl_value.bv_val,
1481                                                 sop->o_tmpmemctx );
1482                                 }
1483                                 slap_sl_free( ctrls[--num_ctrls], sop->o_tmpmemctx );
1484                                 ctrls[num_ctrls] = NULL;
1485                                 if ( cookie.bv_val ) ch_free( cookie.bv_val );  
1486                         }
1487
1488                 } else {
1489                         rs->sr_ctrls = NULL;
1490                         rs->sr_ref = rs->sr_v2ref;
1491                         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
1492                         rs->sr_rspoid = NULL;
1493                         if ( get_pagedresults(sop) > SLAP_NO_CONTROL ) {
1494                                 send_paged_response( sop, rs, NULL, 0 );
1495                         } else {
1496                                 send_ldap_result( sop, rs );
1497                         }
1498                 }
1499         }
1500
1501         rs->sr_err = LDAP_SUCCESS;
1502
1503 done:
1504         if( !IS_PSEARCH && e != NULL ) {
1505                 /* free reader lock */
1506                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache, e, &lock );
1507         }
1508
1509         if ( !opinfo )
1510                 LOCK_ID_FREE( bdb->bi_dbenv, locker );
1511
1512         ber_bvfree( search_context_csn );
1513
1514         if( rs->sr_v2ref ) {
1515                 ber_bvarray_free( rs->sr_v2ref );
1516                 rs->sr_v2ref = NULL;
1517         }
1518         if( realbase.bv_val ) ch_free( realbase.bv_val );
1519
1520         return rs->sr_err;
1521 }
1522
1523
1524 static int base_candidate(
1525         BackendDB       *be,
1526         Entry   *e,
1527         ID              *ids )
1528 {
1529 #ifdef NEW_LOGGING
1530         LDAP_LOG ( OPERATION, ENTRY,
1531                 "base_candidate: base: \"%s\" (0x%08lx)\n",
1532                 e->e_nname.bv_val, (long) e->e_id, 0);
1533 #else
1534         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
1535                 e->e_nname.bv_val, (long) e->e_id, 0);
1536 #endif
1537
1538         ids[0] = 1;
1539         ids[1] = e->e_id;
1540         return 0;
1541 }
1542
1543 /* Look for "objectClass Present" in this filter.
1544  * Also count depth of filter tree while we're at it.
1545  */
1546 static int oc_filter(
1547         Filter *f,
1548         int cur,
1549         int *max )
1550 {
1551         int rc = 0;
1552
1553         assert( f );
1554
1555         if( cur > *max ) *max = cur;
1556
1557         switch( f->f_choice ) {
1558         case LDAP_FILTER_PRESENT:
1559                 if (f->f_desc == slap_schema.si_ad_objectClass) {
1560                         rc = 1;
1561                 }
1562                 break;
1563
1564         case LDAP_FILTER_AND:
1565         case LDAP_FILTER_OR:
1566                 cur++;
1567                 for ( f=f->f_and; f; f=f->f_next ) {
1568                         (void) oc_filter(f, cur, max);
1569                 }
1570                 break;
1571
1572         default:
1573                 break;
1574         }
1575         return rc;
1576 }
1577
1578 static void search_stack_free( void *key, void *data )
1579 {
1580         ber_memfree_x(data, NULL);
1581 }
1582
1583 static void *search_stack( Operation *op )
1584 {
1585         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1586         void *ret = NULL;
1587
1588         if ( op->o_threadctx ) {
1589                 ldap_pvt_thread_pool_getkey( op->o_threadctx, search_stack,
1590                         &ret, NULL );
1591         } else {
1592                 ret = bdb->bi_search_stack;
1593         }
1594
1595         if ( !ret ) {
1596                 ret = ch_malloc( bdb->bi_search_stack_depth * BDB_IDL_UM_SIZE
1597                         * sizeof( ID ) );
1598                 if ( op->o_threadctx ) {
1599                         ldap_pvt_thread_pool_setkey( op->o_threadctx, search_stack,
1600                                 ret, search_stack_free );
1601                 } else {
1602                         bdb->bi_search_stack = ret;
1603                 }
1604         }
1605         return ret;
1606 }
1607
1608 static int search_candidates(
1609         Operation *stackop,
1610         Operation *op,
1611         SlapReply *rs,
1612         Entry *e,
1613         u_int32_t locker,
1614         ID      *ids,
1615         ID      *scopes )
1616 {
1617         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1618         int rc, depth = 1;
1619         Filter          f, rf, xf, nf;
1620         ID              *stack;
1621         AttributeAssertion aa_ref;
1622 #ifdef BDB_SUBENTRIES
1623         Filter  sf;
1624         AttributeAssertion aa_subentry;
1625 #endif
1626
1627         /*
1628          * This routine takes as input a filter (user-filter)
1629          * and rewrites it as follows:
1630          *      (&(scope=DN)[(objectClass=subentry)]
1631          *              (|[(objectClass=referral)(objectClass=alias)](user-filter))
1632          */
1633
1634 #ifdef NEW_LOGGING
1635         LDAP_LOG ( OPERATION, ENTRY,
1636                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n", 
1637                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope);
1638 #else
1639         Debug(LDAP_DEBUG_TRACE,
1640                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1641                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1642 #endif
1643
1644         xf.f_or = op->oq_search.rs_filter;
1645         xf.f_choice = LDAP_FILTER_OR;
1646         xf.f_next = NULL;
1647
1648         /* If the user's filter uses objectClass=*,
1649          * these clauses are redundant.
1650          */
1651         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
1652                 && !get_subentries_visibility(op)
1653                 && !is_sync_protocol(op) )
1654         {
1655                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
1656                         /* match referral objects */
1657                         struct berval bv_ref = { sizeof("referral")-1, "referral" };
1658                         rf.f_choice = LDAP_FILTER_EQUALITY;
1659                         rf.f_ava = &aa_ref;
1660                         rf.f_av_desc = slap_schema.si_ad_objectClass;
1661                         rf.f_av_value = bv_ref;
1662                         rf.f_next = xf.f_or;
1663                         xf.f_or = &rf;
1664                         depth++;
1665                 }
1666         }
1667
1668         f.f_next = NULL;
1669         f.f_choice = LDAP_FILTER_AND;
1670         f.f_and = &nf;
1671         /* Dummy; we compute scope separately now */
1672         nf.f_choice = SLAPD_FILTER_COMPUTED;
1673         nf.f_result = LDAP_SUCCESS;
1674         nf.f_next = ( xf.f_or == op->oq_search.rs_filter )
1675                 ? op->oq_search.rs_filter : &xf ;
1676         /* Filter depth increased again, adding dummy clause */
1677         depth++;
1678
1679 #ifdef BDB_SUBENTRIES
1680         if( get_subentries_visibility( op ) ) {
1681                 struct berval bv_subentry = { sizeof("SUBENTRY")-1, "SUBENTRY" };
1682                 sf.f_choice = LDAP_FILTER_EQUALITY;
1683                 sf.f_ava = &aa_subentry;
1684                 sf.f_av_desc = slap_schema.si_ad_objectClass;
1685                 sf.f_av_value = bv_subentry;
1686                 sf.f_next = nf.f_next;
1687                 nf.f_next = &sf;
1688         }
1689 #endif
1690
1691         /* Allocate IDL stack, plus 1 more for former tmp */
1692         if ( depth+1 > bdb->bi_search_stack_depth ) {
1693                 stack = ch_malloc( (depth + 1) * BDB_IDL_UM_SIZE * sizeof( ID ) );
1694         } else {
1695                 stack = search_stack( stackop );
1696         }
1697
1698         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1699                 rc = search_aliases( op, rs, e, locker, ids, scopes, stack );
1700         } else {
1701                 rc = bdb_dn2idl( op, e, ids, stack );
1702         }
1703
1704         if ( rc == LDAP_SUCCESS ) {
1705                 rc = bdb_filter_candidates( op, &f, ids,
1706                         stack, stack+BDB_IDL_UM_SIZE );
1707         }
1708
1709         if ( depth+1 > bdb->bi_search_stack_depth ) {
1710                 ch_free( stack );
1711         }
1712
1713         if( rc ) {
1714 #ifdef NEW_LOGGING
1715                 LDAP_LOG ( OPERATION, DETAIL1,
1716                         "bdb_search_candidates: failed (rc=%d)\n", rc, 0, 0  );
1717 #else
1718                 Debug(LDAP_DEBUG_TRACE,
1719                         "bdb_search_candidates: failed (rc=%d)\n",
1720                         rc, NULL, NULL );
1721 #endif
1722
1723         } else {
1724 #ifdef NEW_LOGGING
1725                 LDAP_LOG ( OPERATION, DETAIL1,
1726                         "bdb_search_candidates: id=%ld first=%ld last=%ld\n",
1727                         (long) ids[0], (long) BDB_IDL_FIRST(ids), 
1728                         (long) BDB_IDL_LAST(ids));
1729 #else
1730                 Debug(LDAP_DEBUG_TRACE,
1731                         "bdb_search_candidates: id=%ld first=%ld last=%ld\n",
1732                         (long) ids[0],
1733                         (long) BDB_IDL_FIRST(ids),
1734                         (long) BDB_IDL_LAST(ids) );
1735 #endif
1736         }
1737
1738         return rc;
1739 }
1740
1741 static void
1742 send_paged_response( 
1743         Operation       *op,
1744         SlapReply       *rs,
1745         ID              *lastid,
1746         int             tentries )
1747 {
1748         LDAPControl     ctrl, *ctrls[2];
1749         BerElementBuffer berbuf;
1750         BerElement      *ber = (BerElement *)&berbuf;
1751         PagedResultsCookie respcookie;
1752         struct berval cookie;
1753
1754 #ifdef NEW_LOGGING
1755         LDAP_LOG ( OPERATION, ENTRY,
1756                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1757                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1758 #else
1759         Debug(LDAP_DEBUG_ARGS,
1760                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1761                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1762 #endif
1763
1764         ctrl.ldctl_value.bv_val = NULL;
1765         ctrls[0] = &ctrl;
1766         ctrls[1] = NULL;
1767
1768         ber_init2( ber, NULL, LBER_USE_DER );
1769
1770         if ( lastid ) {
1771                 respcookie = ( PagedResultsCookie )(*lastid);
1772                 cookie.bv_len = sizeof( respcookie );
1773                 cookie.bv_val = (char *)&respcookie;
1774
1775         } else {
1776                 respcookie = ( PagedResultsCookie )0;
1777                 cookie.bv_val = "";
1778                 cookie.bv_len = 0;
1779         }
1780
1781         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1782         op->o_conn->c_pagedresults_state.ps_count =
1783                 op->o_pagedresults_state.ps_count + rs->sr_nentries;
1784
1785         /* return size of 0 -- no estimate */
1786         ber_printf( ber, "{iO}", 0, &cookie ); 
1787
1788         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1789                 goto done;
1790         }
1791
1792         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1793         ctrls[0]->ldctl_iscritical = 0;
1794
1795         rs->sr_ctrls = ctrls;
1796         rs->sr_err = LDAP_SUCCESS;
1797         send_ldap_result( op, rs );
1798         rs->sr_ctrls = NULL;
1799
1800 done:
1801         (void) ber_free_buf( ber );
1802 }
1803