]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/search.c
Fix ITS#3424
[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
25 static int base_candidate(
26         BackendDB       *be,
27         Entry   *e,
28         ID              *ids );
29
30 static int search_candidates(
31         Operation *stackop,     /* op with the current threadctx/slab cache */
32         Operation *sop,         /* search op */
33         SlapReply *rs,
34         Entry *e,
35         u_int32_t locker,
36         ID      *ids,
37         ID      *scopes );
38
39 static int parse_paged_cookie( Operation *op, SlapReply *rs );
40
41 static void send_paged_response( 
42         Operation *op,
43         SlapReply *rs,
44         ID  *lastid,
45         int tentries );
46
47 static int bdb_pfid_cmp( const void *v_id1, const void *v_id2 );
48 static ID* bdb_id_dup( Operation *op, ID *id );
49
50 /* Dereference aliases for a single alias entry. Return the final
51  * dereferenced entry on success, NULL on any failure.
52  */
53 static Entry * deref_base (
54         Operation *op,
55         SlapReply *rs,
56         Entry *e,
57         Entry **matched,
58         u_int32_t locker,
59         DB_LOCK *lock,
60         ID      *tmp,
61         ID      *visited )
62 {
63         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
64         struct berval ndn;
65         EntryInfo *ei;
66         DB_LOCK lockr;
67
68         rs->sr_err = LDAP_ALIAS_DEREF_PROBLEM;
69         rs->sr_text = "maximum deref depth exceeded";
70
71         while (BDB_IDL_N(tmp) < op->o_bd->be_max_deref_depth) {
72                 /* Remember the last entry we looked at, so we can
73                  * report broken links
74                  */
75                 *matched = e;
76
77                 /* If this is part of a subtree or onelevel search,
78                  * have we seen this ID before? If so, quit.
79                  */
80                 if ( visited && bdb_idl_insert( visited, e->e_id ) ) {
81                         e = NULL;
82                         break;
83                 }
84
85                 /* If we've seen this ID during this deref iteration,
86                  * we've hit a loop.
87                  */
88                 if ( bdb_idl_insert( tmp, e->e_id ) ) {
89                         rs->sr_err = LDAP_ALIAS_PROBLEM;
90                         rs->sr_text = "circular alias";
91                         e = NULL;
92                         break;
93                 }
94
95                 /* If there was a problem getting the aliasedObjectName,
96                  * get_alias_dn will have set the error status.
97                  */
98                 if ( get_alias_dn(e, &ndn, &rs->sr_err, &rs->sr_text) ) {
99                         e = NULL;
100                         break;
101                 }
102
103                 rs->sr_err = bdb_dn2entry( op, NULL, &ndn, &ei,
104                         0, locker, &lockr );
105
106                 if ( ei ) {
107                         e = ei->bei_e;
108                 } else {
109                         e = NULL;
110                 }
111
112                 if (!e) {
113                         rs->sr_err = LDAP_ALIAS_PROBLEM;
114                         rs->sr_text = "aliasedObject not found";
115                         break;
116                 }
117
118                 /* Free the previous entry, continue to work with the
119                  * one we just retrieved.
120                  */
121                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
122                         *matched, lock);
123                 *lock = lockr;
124
125                 /* We found a regular entry. Return this to the caller. The
126                  * entry is still locked for Read.
127                  */
128                 if (!is_entry_alias(e)) {
129                         rs->sr_err = LDAP_SUCCESS;
130                         rs->sr_text = NULL;
131                         break;
132                 }
133         }
134         return e;
135 }
136
137 /* Look for and dereference all aliases within the search scope. Adds
138  * the dereferenced entries to the "ids" list. Requires "stack" to be
139  * able to hold 8 levels of DB_SIZE IDLs. Of course we're hardcoded to
140  * require a minimum of 8 UM_SIZE IDLs so this is never a problem.
141  */
142 static int search_aliases(
143         Operation *op,
144         SlapReply *rs,
145         Entry *e,
146         u_int32_t locker,
147         ID *ids,
148         ID *scopes,
149         ID *stack )
150 {
151         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
152         ID *aliases, *curscop, *subscop, *visited, *newsubs, *oldsubs, *tmp;
153         ID cursora, ida, cursoro, ido, *subscop2;
154         Entry *matched, *a;
155         EntryInfo *ei;
156         struct berval bv_alias = BER_BVC( "alias" );
157         AttributeAssertion aa_alias;
158         Filter  af;
159         DB_LOCK locka, lockr;
160         int first = 1;
161
162         aliases = stack;        /* IDL of all aliases in the database */
163         curscop = aliases + BDB_IDL_DB_SIZE;    /* Aliases in the current scope */
164         subscop = curscop + BDB_IDL_DB_SIZE;    /* The current scope */
165         visited = subscop + BDB_IDL_DB_SIZE;    /* IDs we've seen in this search */
166         newsubs = visited + BDB_IDL_DB_SIZE;    /* New subtrees we've added */
167         oldsubs = newsubs + BDB_IDL_DB_SIZE;    /* Subtrees added previously */
168         tmp = oldsubs + BDB_IDL_DB_SIZE;        /* Scratch space for deref_base() */
169
170         /* A copy of subscop, because subscop gets clobbered by
171          * the bdb_idl_union/intersection routines
172          */
173         subscop2 = tmp + BDB_IDL_DB_SIZE;
174
175         af.f_choice = LDAP_FILTER_EQUALITY;
176         af.f_ava = &aa_alias;
177         af.f_av_desc = slap_schema.si_ad_objectClass;
178         af.f_av_value = bv_alias;
179         af.f_next = NULL;
180
181         /* Find all aliases in database */
182         BDB_IDL_ZERO( aliases );
183         rs->sr_err = bdb_filter_candidates( op, &af, aliases,
184                 curscop, visited );
185         if (rs->sr_err != LDAP_SUCCESS) {
186                 return rs->sr_err;
187         }
188         oldsubs[0] = 1;
189         oldsubs[1] = e->e_id;
190
191         BDB_IDL_ZERO( ids );
192         BDB_IDL_ZERO( visited );
193         BDB_IDL_ZERO( newsubs );
194
195         cursoro = 0;
196         ido = bdb_idl_first( oldsubs, &cursoro );
197
198         for (;;) {
199                 /* Set curscop to only the aliases in the current scope. Start with
200                  * all the aliases, obtain the IDL for the current scope, and then
201                  * get the intersection of these two IDLs. Add the current scope
202                  * to the cumulative list of candidates.
203                  */
204                 BDB_IDL_CPY( curscop, aliases );
205                 rs->sr_err = bdb_dn2idl( op, e, subscop,
206                         subscop2+BDB_IDL_DB_SIZE );
207                 if (first) {
208                         first = 0;
209                 } else {
210                         bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache, e, &locka);
211                 }
212                 BDB_IDL_CPY(subscop2, subscop);
213                 rs->sr_err = bdb_idl_intersection(curscop, subscop);
214                 bdb_idl_union( ids, subscop2 );
215
216                 /* Dereference all of the aliases in the current scope. */
217                 cursora = 0;
218                 for (ida = bdb_idl_first(curscop, &cursora); ida != NOID;
219                         ida = bdb_idl_next(curscop, &cursora))
220                 {
221                         ei = NULL;
222 retry1:
223                         rs->sr_err = bdb_cache_find_id(op, NULL,
224                                 ida, &ei, 0, locker, &lockr );
225                         if (rs->sr_err != LDAP_SUCCESS) {
226                                 if ( rs->sr_err == DB_LOCK_DEADLOCK ||
227                                         rs->sr_err == DB_LOCK_NOTGRANTED ) goto retry1;
228                                 continue;
229                         }
230                         a = ei->bei_e;
231
232                         /* This should only happen if the curscop IDL has maxed out and
233                          * turned into a range that spans IDs indiscriminately
234                          */
235                         if (!is_entry_alias(a)) {
236                                 bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache,
237                                         a, &lockr);
238                                 continue;
239                         }
240
241                         /* Actually dereference the alias */
242                         BDB_IDL_ZERO(tmp);
243                         a = deref_base( op, rs, a, &matched, locker, &lockr,
244                                 tmp, visited );
245                         if (a) {
246                                 /* If the target was not already in our current candidates,
247                                  * make note of it in the newsubs list. Also
248                                  * set it in the scopes list so that bdb_search
249                                  * can check it.
250                                  */
251                                 if (bdb_idl_insert(ids, a->e_id) == 0) {
252                                         bdb_idl_insert(newsubs, a->e_id);
253                                         bdb_idl_insert(scopes, a->e_id);
254                                 }
255                                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
256                                         a, &lockr);
257
258                         } else if (matched) {
259                                 /* Alias could not be dereferenced, or it deref'd to
260                                  * an ID we've already seen. Ignore it.
261                                  */
262                                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
263                                         matched, &lockr );
264                                 rs->sr_text = NULL;
265                         }
266                 }
267                 /* If this is a OneLevel search, we're done; oldsubs only had one
268                  * ID in it. For a Subtree search, oldsubs may be a list of scope IDs.
269                  */
270                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) break;
271 nextido:
272                 ido = bdb_idl_next( oldsubs, &cursoro );
273                 
274                 /* If we're done processing the old scopes, did we add any new
275                  * scopes in this iteration? If so, go back and do those now.
276                  */
277                 if (ido == NOID) {
278                         if (BDB_IDL_IS_ZERO(newsubs)) break;
279                         BDB_IDL_CPY(oldsubs, newsubs);
280                         BDB_IDL_ZERO(newsubs);
281                         cursoro = 0;
282                         ido = bdb_idl_first( oldsubs, &cursoro );
283                 }
284
285                 /* Find the entry corresponding to the next scope. If it can't
286                  * be found, ignore it and move on. This should never happen;
287                  * we should never see the ID of an entry that doesn't exist.
288                  * Set the name so that the scope's IDL can be retrieved.
289                  */
290                 ei = NULL;
291 sameido:
292                 rs->sr_err = bdb_cache_find_id(op, NULL, ido, &ei,
293                         0, locker, &locka );
294                 if ( rs->sr_err != LDAP_SUCCESS ) {
295                         if ( rs->sr_err == DB_LOCK_DEADLOCK ||
296                                 rs->sr_err == DB_LOCK_NOTGRANTED )
297                                 goto sameido;
298                         goto nextido;
299                 }
300                 e = ei->bei_e;
301         }
302         return rs->sr_err;
303 }
304
305 #ifdef BDB_PSEARCH
306
307 #define is_sync_protocol(op)    \
308         ((op)->o_sync_mode & SLAP_SYNC_REFRESH_AND_PERSIST)
309
310 #define IS_BDB_REPLACE(type) (( type == LDAP_PSEARCH_BY_DELETE ) || \
311         ( type == LDAP_PSEARCH_BY_SCOPEOUT ))
312 #define IS_PSEARCH (op != sop)
313 #define IS_POST_SEARCH ( op->ors_post_search_id != NOID )
314
315 static Operation *
316 bdb_drop_psearch( Operation *op, ber_int_t msgid )
317 {
318         Operation       *ps_list;
319         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
320
321         LDAP_LIST_FOREACH ( ps_list, &bdb->bi_psearch_list, o_ps_link ) {
322                 if ( ps_list->o_connid == op->o_connid ) {
323                         if ( ps_list->o_msgid == msgid ) {
324                                 ps_list->o_abandon = 1;
325                                 LDAP_LIST_REMOVE( ps_list, o_ps_link );
326                                 ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
327                                 LDAP_STAILQ_REMOVE( &op->o_conn->c_ops, ps_list,
328                                         slap_op, o_next );
329                                 LDAP_STAILQ_NEXT( ps_list, o_next ) = NULL;
330                                 op->o_conn->c_n_ops_executing--;
331                                 op->o_conn->c_n_ops_completed++;
332                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
333                                 return ps_list;
334                         }
335                 }
336         }
337
338         return NULL;
339 }
340
341 int
342 bdb_abandon( Operation *op, SlapReply *rs )
343 {
344         Operation       *ps;
345         void            *saved_tmpmemctx;
346
347         ps = bdb_drop_psearch( op, op->oq_abandon.rs_msgid );
348         if ( ps ) {
349                 saved_tmpmemctx = ps->o_tmpmemctx;
350
351                 if (!BER_BVISNULL(&ps->o_req_dn)) {
352                         slap_sl_free(ps->o_req_dn.bv_val, ps->o_tmpmemctx );
353                 }
354                 if (!BER_BVISNULL(&ps->o_req_ndn)) {
355                         slap_sl_free(ps->o_req_ndn.bv_val, ps->o_tmpmemctx );
356                 }
357                 if (!BER_BVISNULL(&ps->ors_filterstr)) {
358                         ps->o_tmpfree(ps->ors_filterstr.bv_val, ps->o_tmpmemctx);
359                 }
360                 if (ps->ors_filter != NULL) {
361                         filter_free_x(ps, ps->ors_filter);
362                 }
363                 if (ps->ors_attrs != NULL) {
364                         ps->o_tmpfree(ps->ors_attrs, ps->o_tmpmemctx);
365                 }
366
367                 slap_op_free ( ps );
368
369                 if ( saved_tmpmemctx ) {
370                         slap_sl_mem_destroy( NULL, saved_tmpmemctx );
371                 }
372
373                 return LDAP_SUCCESS;
374         }
375         return LDAP_UNAVAILABLE;
376 }
377
378 int
379 bdb_cancel( Operation *op, SlapReply *rs )
380 {
381         Operation       *ps;
382         void            *saved_tmpmemctx;
383
384         ps = bdb_drop_psearch( op, op->oq_cancel.rs_msgid );
385         if ( ps ) {
386                 saved_tmpmemctx = ps->o_tmpmemctx;
387
388                 rs->sr_err = LDAP_CANCELLED;
389                 send_ldap_result( ps, rs );
390
391                 if (!BER_BVISNULL(&ps->o_req_dn)) {
392                         slap_sl_free(ps->o_req_dn.bv_val, ps->o_tmpmemctx );
393                 }
394                 if (!BER_BVISNULL(&ps->o_req_ndn)) {
395                         slap_sl_free(ps->o_req_ndn.bv_val, ps->o_tmpmemctx );
396                 }
397                 if (!BER_BVISNULL(&ps->ors_filterstr)) {
398                         ps->o_tmpfree(ps->ors_filterstr.bv_val, ps->o_tmpmemctx);
399                 }
400                 if (ps->ors_filter != NULL) {
401                         filter_free_x(ps, ps->ors_filter);
402                 }
403                 if (ps->ors_attrs != NULL) {
404                         ps->o_tmpfree(ps->ors_attrs, ps->o_tmpmemctx);
405                 }
406
407                 slap_op_free ( ps );
408
409                 if ( saved_tmpmemctx ) {
410                         slap_sl_mem_destroy( NULL, saved_tmpmemctx );
411                 }
412
413                 return LDAP_SUCCESS;
414         }
415         return LDAP_UNAVAILABLE;
416 }
417
418 int bdb_search( Operation *op, SlapReply *rs )
419 {
420         int rc;
421         struct pc_entry *pce = NULL;
422         struct pc_entry *tmp_pce = NULL;
423         Entry ps_e = {0};
424         Attribute *a;
425
426         ps_e.e_private = NULL;
427         ldap_pvt_thread_mutex_init( &op->o_pcmutex );
428         LDAP_TAILQ_INIT( &op->o_ps_pre_candidates );
429         LDAP_TAILQ_INIT( &op->o_ps_post_candidates );
430
431         op->ors_post_search_id = NOID;
432         rc = bdb_do_search( op, rs, op, NULL, 0 );
433
434         ldap_pvt_thread_mutex_lock( &op->o_pcmutex );
435         pce = LDAP_TAILQ_FIRST( &op->o_ps_post_candidates );
436         ldap_pvt_thread_mutex_unlock( &op->o_pcmutex );
437
438         while ( rc == LDAP_SUCCESS && pce &&
439                         op->o_sync_mode & SLAP_SYNC_REFRESH_AND_PERSIST ) {
440
441                 ps_e.e_id = op->ors_post_search_id = pce->pc_id;
442                 if ( op->o_sync_csn.bv_val ) {
443                         ch_free( op->o_sync_csn.bv_val );
444                         op->o_sync_csn.bv_val = NULL;
445                 }
446                 ber_dupbv( &op->o_sync_csn, &pce->pc_csn );
447                 ber_dupbv( &ps_e.e_name, &pce->pc_ename );
448                 ber_dupbv( &ps_e.e_nname, &pce->pc_enname );
449                 a = ch_calloc( 1, sizeof( Attribute ));
450                 a->a_desc = slap_schema.si_ad_entryUUID;
451                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
452                 ber_dupbv( &a->a_vals[0], &pce->pc_entryUUID );
453                 a->a_nvals = a->a_vals;
454                 a->a_next = NULL;
455                 ps_e.e_attrs = a;
456
457                 rc = bdb_do_search( op, rs, op, &ps_e, 0 );
458
459                 tmp_pce = pce;
460                 ldap_pvt_thread_mutex_lock( &op->o_pcmutex );
461                 pce = LDAP_TAILQ_NEXT( pce, pc_link );
462                 LDAP_TAILQ_REMOVE( &op->o_ps_post_candidates, tmp_pce, pc_link );
463                 ldap_pvt_thread_mutex_unlock( &op->o_pcmutex );
464
465                 ch_free( tmp_pce->pc_csn.bv_val );
466                 ch_free( tmp_pce->pc_entryUUID.bv_val );
467                 ch_free( tmp_pce->pc_ename.bv_val );
468                 ch_free( tmp_pce->pc_enname.bv_val );
469                 ch_free( tmp_pce );     
470                 entry_clean( &ps_e );
471         }
472         return rc;
473 }
474
475 #define BDB_PSEARCH_MAX_WAIT 3
476 int bdb_psearch( Operation *op, SlapReply *rs, Operation *sop,
477         Entry *ps_e, int ps_type )
478 {
479         int     rc;
480         struct pc_entry *pce = NULL;
481         struct pc_entry *p = NULL;
482         int num_retries = 0;
483
484         op->ors_post_search_id = NOID;
485
486         switch (ps_type) {
487         case LDAP_PSEARCH_BY_PREMODIFY:
488         case LDAP_PSEARCH_BY_PREDELETE:
489
490                 if ( !op->o_ps_send_wait ) {
491                         if ( sop->o_refresh_in_progress ) {
492                                 pce = (struct pc_entry *) ch_calloc(
493                                                         1, sizeof( struct pc_entry ));
494                                 pce->pc_id = ps_e->e_id;
495                                 ldap_pvt_thread_mutex_lock( &sop->o_pcmutex );
496                                 if ( LDAP_TAILQ_EMPTY( &sop->o_ps_pre_candidates )) {
497                                         LDAP_TAILQ_INSERT_HEAD(
498                                                         &sop->o_ps_pre_candidates, pce, pc_link );
499                                 } else {
500                                         LDAP_TAILQ_FOREACH( p,
501                                                         &sop->o_ps_pre_candidates, pc_link ) {
502                                                 if ( p->pc_id > pce->pc_id )
503                                                         break;
504                                         }
505
506                                         if ( p ) {
507                                                 LDAP_TAILQ_INSERT_BEFORE( p, pce, pc_link );
508                                         } else {
509                                                 LDAP_TAILQ_INSERT_TAIL(
510                                                                 &sop->o_ps_pre_candidates,
511                                                                 pce, pc_link );
512                                         }
513                                 }
514                                 ldap_pvt_thread_mutex_unlock( &sop->o_pcmutex );
515                         } else {
516                                 rc = bdb_do_search( op, rs, sop, ps_e, ps_type );
517                                 return rc;
518                         }
519                 } else {
520                         pce = op->o_ps_send_wait;
521                 }
522
523                 /* Wait until refresh search send the entry */
524                 while ( !pce->pc_sent ) {
525                         if ( sop->o_refresh_in_progress ) {
526                                 if ( num_retries == BDB_PSEARCH_MAX_WAIT ) {
527                                         op->o_ps_send_wait = pce;
528                                         return LDAP_BUSY;
529                                 }
530                                 ldap_pvt_thread_yield();
531                                 bdb_trans_backoff( ++num_retries );
532                         } else {
533                                 break;
534                         }
535                 }
536
537                 op->o_ps_send_wait = NULL;
538
539                 if ( !sop->o_refresh_in_progress && !pce->pc_sent ) {
540                         /* refresh ended without processing pce */
541                         /* need to perform psearch for ps_e */
542                         ldap_pvt_thread_mutex_lock( &sop->o_pcmutex );
543                         LDAP_TAILQ_REMOVE( &sop->o_ps_pre_candidates, pce, pc_link );
544                         ldap_pvt_thread_mutex_unlock( &sop->o_pcmutex );
545                         ch_free( pce );
546                         rc = bdb_do_search( op, rs, sop, ps_e, ps_type );
547                         return rc;
548                 } else {
549                         /* the pce entry was sent in the refresh phase */
550                         if ( ps_type == LDAP_PSEARCH_BY_PREMODIFY ) {
551                                 struct psid_entry* psid_e;
552                                 psid_e = (struct psid_entry *) ch_calloc(1,
553                                                         sizeof(struct psid_entry));
554                                 psid_e->ps_op = sop;
555                                 LDAP_LIST_INSERT_HEAD( &op->o_pm_list, psid_e, ps_link );
556                         }
557
558                         ldap_pvt_thread_mutex_lock( &sop->o_pcmutex );
559                         LDAP_TAILQ_REMOVE( &sop->o_ps_pre_candidates, pce, pc_link );
560                         ldap_pvt_thread_mutex_unlock( &sop->o_pcmutex );
561                         ch_free( pce );
562                         return LDAP_SUCCESS;
563                 } 
564                 break;
565         case LDAP_PSEARCH_BY_DELETE:
566         case LDAP_PSEARCH_BY_SCOPEOUT:
567         case LDAP_PSEARCH_BY_ADD:
568         case LDAP_PSEARCH_BY_MODIFY:
569                 ldap_pvt_thread_mutex_lock( &op->o_pcmutex );
570                 if ( sop->o_refresh_in_progress ||
571                                 !LDAP_TAILQ_EMPTY( &sop->o_ps_post_candidates )) {
572                         pce = (struct pc_entry *) ch_calloc( 1, sizeof( struct pc_entry ));
573                         pce->pc_id = ps_e->e_id;
574                         ber_dupbv( &pce->pc_csn, &op->o_sync_csn );
575                         if ( ps_type == LDAP_PSEARCH_BY_DELETE ) {
576                                 Attribute *a;
577                                 for ( a = ps_e->e_attrs; a != NULL; a = a->a_next ) {
578                                         AttributeDescription *desc = a->a_desc;
579                                         if ( desc == slap_schema.si_ad_entryUUID ) {
580                                                 ber_dupbv( &pce->pc_entryUUID, &a->a_nvals[0] );
581                                         }
582                                 }
583                         }       
584                         ber_dupbv( &pce->pc_ename, &ps_e->e_name ); 
585                         ber_dupbv( &pce->pc_enname, &ps_e->e_nname ); 
586                         LDAP_TAILQ_INSERT_TAIL( &sop->o_ps_post_candidates, pce, pc_link );
587                         ldap_pvt_thread_mutex_unlock( &op->o_pcmutex );
588                 } else {
589                         ldap_pvt_thread_mutex_unlock( &op->o_pcmutex );
590                         rc = bdb_do_search( op, rs, sop, ps_e, ps_type );
591                         return rc;
592                 }
593                 break;
594         default:
595                 Debug( LDAP_DEBUG_TRACE, "do_psearch: invalid psearch type\n",
596                                 0, 0, 0 );
597                 return LDAP_OTHER;
598         }
599 }
600 #else
601 int bdb_search( Operation *op, SlapReply *rs )
602 {
603         return bdb_do_search( op, rs, op, NULL, 0 );
604 }
605 #endif
606
607 /* For persistent searches, op is the currently executing operation,
608  * sop is the persistent search. For regular searches, sop = op.
609  */
610 int
611 bdb_do_search( Operation *op, SlapReply *rs, Operation *sop,
612         Entry *ps_e, int ps_type )
613 {
614         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
615         time_t          stoptime;
616         ID              id, cursor;
617         ID              candidates[BDB_IDL_UM_SIZE];
618         ID              scopes[BDB_IDL_DB_SIZE];
619         Entry           *e = NULL, base, e_root = {0};
620         Entry           *matched = NULL;
621         EntryInfo       *ei, ei_root = {0};
622         struct berval   realbase = BER_BVNULL;
623         int             manageDSAit;
624         int             tentries = 0;
625         ID              lastid = NOID;
626         AttributeName   *attrs;
627
628         u_int32_t       locker = 0;
629         DB_LOCK         lock;
630         struct  bdb_op_info     *opinfo = NULL;
631         DB_TXN                  *ltid = NULL;
632
633 #ifdef BDB_PSEARCH
634         Filter          contextcsnand, contextcsnle, cookief, csnfnot,
635                         csnfeq, csnfand, csnfge;
636         AttributeAssertion aa_ge, aa_eq, aa_le;
637         struct berval   *search_context_csn = NULL;
638         DB_LOCK         ctxcsn_lock;
639         LDAPControl     *ctrls[SLAP_MAX_RESPONSE_CONTROLS];
640         int             num_ctrls = 0;
641         AttributeName   uuid_attr[2];
642         int             rc_sync = 0;
643         int             entry_sync_state = -1;
644         AttributeName   null_attr;
645         int             no_sync_state_change = 0;
646
647
648         Operation       *ps_list;
649         int                     sync_send_present_mode = 1;
650         int                     match;
651         MatchingRule *mr;
652         const char *text;
653         int                     slog_found = 0;
654
655         struct pc_entry *pce = NULL;
656         BerVarray       syncUUID_set = NULL;
657         int                     syncUUID_set_cnt = 0;
658
659 #endif
660
661         Debug( LDAP_DEBUG_TRACE, "=> " LDAP_XSTRING(bdb_search) "\n", 0, 0, 0);
662         attrs = sop->oq_search.rs_attrs;
663
664         opinfo = (struct bdb_op_info *) op->o_private;
665
666 #ifdef BDB_PSEARCH
667         if ( !IS_POST_SEARCH && !IS_PSEARCH &&
668                         sop->o_sync_mode & SLAP_SYNC_REFRESH_AND_PERSIST ) {
669                 struct slap_session_entry *sent;
670                 if ( sop->o_sync_state.sid >= 0 ) {
671                         LDAP_LIST_FOREACH( sent, &bdb->bi_session_list, se_link ) {
672                                 if ( sent->se_id == sop->o_sync_state.sid ) {
673                                         sop->o_sync_slog_size = sent->se_size;
674                                         break;
675                                 }
676                         }
677                 }
678         }
679
680         /* psearch needs to be registered before refresh begins */
681         if ( !IS_POST_SEARCH && !IS_PSEARCH &&
682                         sop->o_sync_mode & SLAP_SYNC_PERSIST ) {
683                 sop->o_refresh_in_progress = 1;
684                 ldap_pvt_thread_rdwr_wlock( &bdb->bi_pslist_rwlock );
685                 LDAP_LIST_INSERT_HEAD( &bdb->bi_psearch_list, sop, o_ps_link );
686                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_pslist_rwlock );
687
688         } else if ( !IS_POST_SEARCH && !IS_PSEARCH &&
689                                 sop->o_sync_mode & SLAP_SYNC_REFRESH_AND_PERSIST
690                                 && sop->o_sync_slog_size >= 0 )
691         {
692                 ldap_pvt_thread_rdwr_wlock( &bdb->bi_pslist_rwlock );
693                 LDAP_LIST_FOREACH( ps_list, &bdb->bi_psearch_list, o_ps_link ) {
694                         if ( ps_list->o_sync_slog_size >= 0 ) {
695                                 if ( ps_list->o_sync_state.sid == sop->o_sync_state.sid ) {
696                                         slog_found = 1;
697                                         break;
698                                 }
699                         }
700                 }
701
702                 if ( slog_found ) {
703                         if ( ps_list->o_sync_slog_omitcsn.bv_len != 0 ) {
704                                 mr = slap_schema.si_ad_entryCSN->ad_type->sat_ordering;
705                                 if ( sop->o_sync_state.ctxcsn &&
706                                         sop->o_sync_state.ctxcsn->bv_val != NULL )
707                                 {
708                                         value_match( &match, slap_schema.si_ad_entryCSN, mr,
709                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
710                                                 sop->o_sync_state.ctxcsn,
711                                                 &ps_list->o_sync_slog_omitcsn,
712                                                 &text );
713                                 } else {
714                                         match = -1;
715                                 }
716                                 if ( match >= 0 ) {
717                                         sync_send_present_mode = 0;
718                                 }
719                         } else {
720                                 sync_send_present_mode = 0;
721                         }
722                 } else if ( sop->o_sync_slog_size >= 0 ) {
723                         LDAP_LIST_INSERT_HEAD( &bdb->bi_psearch_list, sop, o_ps_link );
724                 } else {
725                         sop->o_sync_state.sid = -1;
726                 }
727                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_pslist_rwlock );
728         }
729
730         null_attr.an_desc = NULL;
731         null_attr.an_oc = NULL;
732         null_attr.an_oc_exclude = 0;
733         BER_BVZERO( &null_attr.an_name );
734
735         for( num_ctrls = 0; num_ctrls < SLAP_MAX_RESPONSE_CONTROLS; num_ctrls++ ) {
736                 ctrls[num_ctrls] = NULL;
737         }
738         num_ctrls = 0;
739
740         if ( IS_PSEARCH && IS_BDB_REPLACE(ps_type)) {
741                 attrs = uuid_attr;
742                 attrs[0].an_desc = NULL;
743                 attrs[0].an_oc = NULL;
744                 attrs[0].an_oc_exclude = 0;
745                 BER_BVZERO( &attrs[0].an_name );
746         }
747 #endif
748
749         manageDSAit = get_manageDSAit( sop );
750
751 #ifdef BDB_PSEARCH
752         /* Sync control overrides manageDSAit */
753         if ( !IS_PSEARCH && sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
754                 if ( manageDSAit == SLAP_CONTROL_NONE ) {
755                         manageDSAit = SLAP_CONTROL_CRITICAL;
756                 }
757         } else if ( IS_PSEARCH ) {
758                 if ( manageDSAit == SLAP_CONTROL_NONE ) {
759                         manageDSAit = SLAP_CONTROL_CRITICAL;
760                 }
761         }
762 #endif
763
764         if ( opinfo && opinfo->boi_txn ) {
765                 ltid = opinfo->boi_txn;
766                 locker = TXN_ID( ltid );
767         } else {
768                 rs->sr_err = LOCK_ID( bdb->bi_dbenv, &locker );
769
770                 switch(rs->sr_err) {
771                 case 0:
772                         break;
773                 default:
774                         send_ldap_error( sop, rs, LDAP_OTHER, "internal error" );
775                         return rs->sr_err;
776                 }
777         }
778
779 #ifdef BDB_PSEARCH
780         if ( IS_POST_SEARCH ) {
781                 cursor = 0;
782                 candidates[0] = 1;
783                 candidates[1] = op->ors_post_search_id;
784                 search_context_csn = ber_dupbv( NULL, &op->o_sync_csn );        
785                 goto loop_start;
786         }
787 #endif
788
789         if ( sop->o_req_ndn.bv_len == 0 ) {
790                 /* DIT root special case */
791                 ei_root.bei_e = &e_root;
792                 ei_root.bei_parent = &ei_root;
793                 e_root.e_private = &ei_root;
794                 e_root.e_id = 0;
795                 BER_BVSTR( &e_root.e_nname, "" );
796                 BER_BVSTR( &e_root.e_name, "" );
797                 ei = &ei_root;
798                 rs->sr_err = LDAP_SUCCESS;
799         } else {
800 dn2entry_retry:
801                 /* get entry with reader lock */
802                 rs->sr_err = bdb_dn2entry( op, ltid, &sop->o_req_ndn, &ei,
803                         1, locker, &lock );
804         }
805
806         switch(rs->sr_err) {
807         case DB_NOTFOUND:
808                 matched = ei->bei_e;
809                 break;
810         case 0:
811                 e = ei->bei_e;
812                 break;
813         case LDAP_BUSY:
814                 send_ldap_error( sop, rs, LDAP_BUSY, "ldap server busy" );
815                 if ( !opinfo )
816                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
817                 return LDAP_BUSY;
818         case DB_LOCK_DEADLOCK:
819         case DB_LOCK_NOTGRANTED:
820                 goto dn2entry_retry;
821         default:
822                 send_ldap_error( sop, rs, LDAP_OTHER, "internal error" );
823                 if ( !opinfo )
824                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
825                 return rs->sr_err;
826         }
827
828         if ( e && (op->ors_deref & LDAP_DEREF_FINDING) && is_entry_alias(e) ) {
829                 BDB_IDL_ZERO(candidates);
830                 e = deref_base( op, rs, e, &matched, locker, &lock,
831                         candidates, NULL );
832         }
833
834         if ( e == NULL ) {
835                 struct berval matched_dn = BER_BVNULL;
836
837                 if ( matched != NULL ) {
838                         BerVarray erefs;
839                         ber_dupbv( &matched_dn, &matched->e_name );
840
841                         erefs = is_entry_referral( matched )
842                                 ? get_entry_referrals( op, matched )
843                                 : NULL;
844
845                         bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache,
846                                 matched, &lock);
847                         matched = NULL;
848
849                         if( erefs ) {
850                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
851                                         &sop->o_req_dn, sop->oq_search.rs_scope );
852                                 ber_bvarray_free( erefs );
853                         }
854
855                 } else {
856                         rs->sr_ref = referral_rewrite( default_referral,
857                                 NULL, &sop->o_req_dn, sop->oq_search.rs_scope );
858                 }
859
860                 rs->sr_err = LDAP_REFERRAL;
861                 rs->sr_matched = matched_dn.bv_val;
862                 send_ldap_result( sop, rs );
863
864                 if ( !opinfo )
865                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
866                 if ( rs->sr_ref ) {
867                         ber_bvarray_free( rs->sr_ref );
868                         rs->sr_ref = NULL;
869                 }
870                 if ( matched_dn.bv_val ) {
871                         ber_memfree( matched_dn.bv_val );
872                         rs->sr_matched = NULL;
873                 }
874                 return rs->sr_err;
875         }
876
877         if ( !manageDSAit && e != &e_root && is_entry_referral( e ) ) {
878                 /* entry is a referral, don't allow add */
879                 struct berval matched_dn;
880                 BerVarray erefs;
881                 
882                 ber_dupbv( &matched_dn, &e->e_name );
883                 erefs = get_entry_referrals( op, e );
884
885                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache, e, &lock );
886                 e = NULL;
887
888                 if( erefs ) {
889                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
890                                 &sop->o_req_dn, sop->oq_search.rs_scope );
891                         ber_bvarray_free( erefs );
892                 }
893
894                 Debug( LDAP_DEBUG_TRACE,
895                         LDAP_XSTRING(bdb_search) ": entry is referral\n",
896                         0, 0, 0 );
897
898                 if (!rs->sr_ref) rs->sr_text = "bad_referral object";
899                 rs->sr_err = LDAP_REFERRAL;
900                 rs->sr_matched = matched_dn.bv_val;
901                 send_ldap_result( sop, rs );
902
903                 if ( !opinfo )
904                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
905                 ber_bvarray_free( rs->sr_ref );
906                 rs->sr_ref = NULL;
907                 ber_memfree( matched_dn.bv_val );
908                 rs->sr_matched = NULL;
909                 return 1;
910         }
911
912         if ( get_assert( op ) &&
913                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
914         {
915                 rs->sr_err = LDAP_ASSERTION_FAILED;
916                 send_ldap_result( sop, rs );
917                 return 1;
918         }
919
920         /* compute it anyway; root does not use it */
921         stoptime = op->o_time + sop->ors_tlimit;
922
923         /* need normalized dn below */
924         ber_dupbv( &realbase, &e->e_nname );
925
926         /* Copy info to base, must free entry before accessing the database
927          * in search_candidates, to avoid deadlocks.
928          */
929         base.e_private = e->e_private;
930         base.e_nname = realbase;
931         base.e_id = e->e_id;
932
933         if ( e != &e_root ) {
934                 bdb_cache_return_entry_r(bdb->bi_dbenv, &bdb->bi_cache, e, &lock);
935         }
936         e = NULL;
937
938 #ifdef BDB_PSEARCH
939         if ( !IS_PSEARCH ) {
940                 rs->sr_err = bdb_get_commit_csn( sop, rs, &search_context_csn,
941                         locker, &ctxcsn_lock );
942
943                 if ( rs->sr_err != LDAP_SUCCESS ) {
944                         send_ldap_error( sop, rs, rs->sr_err,
945                                 "error in csn management in search" );
946                         goto done;
947                 }
948
949                 if ( sop->o_sync_mode != SLAP_SYNC_NONE &&
950                         sop->o_sync_state.ctxcsn &&
951                         sop->o_sync_state.ctxcsn->bv_val &&
952                         ber_bvcmp( &sop->o_sync_state.ctxcsn[0], search_context_csn ) == 0 )
953                 {
954                         bdb_cache_entry_db_unlock( bdb->bi_dbenv, &ctxcsn_lock );
955                         goto nochange;
956                 }
957         } else {
958                 search_context_csn = ber_dupbv( NULL, &op->o_sync_csn );        
959         }
960 #endif
961
962         /* select candidates */
963         if ( sop->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
964                 rs->sr_err = base_candidate( op->o_bd, &base, candidates );
965
966         } else {
967                 BDB_IDL_ZERO( candidates );
968                 BDB_IDL_ZERO( scopes );
969                 rs->sr_err = search_candidates( op, sop, rs, &base,
970                         locker, candidates, scopes );
971         }
972
973 #ifdef BDB_PSEARCH
974         if ( !IS_PSEARCH && sop->o_sync_mode != SLAP_SYNC_NONE ) {
975                 bdb_cache_entry_db_unlock( bdb->bi_dbenv, &ctxcsn_lock );
976         }
977 #endif
978
979         /* start cursor at beginning of candidates.
980          */
981         cursor = 0;
982 #ifdef BDB_PSEARCH
983         if (IS_PSEARCH) {
984                 if ( !BDB_IDL_IS_RANGE( candidates ) ) {
985                         cursor = bdb_idl_search( candidates, ps_e->e_id );
986                         if ( candidates[cursor] != ps_e->e_id ) {
987                                 rs->sr_err = LDAP_SUCCESS;
988                                 goto done;
989                         }
990                 } else if ( ps_e->e_id < BDB_IDL_RANGE_FIRST( candidates ) ||
991                         ps_e->e_id > BDB_IDL_RANGE_LAST( candidates ))
992                 {
993                         rs->sr_err = LDAP_SUCCESS;
994                         goto done;
995                 }
996                 candidates[0] = 1;
997                 candidates[1] = ps_e->e_id;
998         }
999 #endif
1000
1001         if ( candidates[0] == 0 ) {
1002                 Debug( LDAP_DEBUG_TRACE,
1003                         LDAP_XSTRING(bdb_search) ": no candidates\n",
1004                         0, 0, 0 );
1005
1006                 goto nochange;
1007         }
1008
1009         /* if not root and candidates exceed to-be-checked entries, abort */
1010         if ( sop->ors_limit     /* isroot == FALSE */ &&
1011                 sop->ors_limit->lms_s_unchecked != -1 &&
1012                 BDB_IDL_N(candidates) > (unsigned) sop->ors_limit->lms_s_unchecked )
1013         {
1014                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
1015                 send_ldap_result( sop, rs );
1016                 rs->sr_err = LDAP_SUCCESS;
1017                 goto done;
1018         }
1019
1020         if ( sop->ors_limit == NULL     /* isroot == TRUE */ ||
1021                 !sop->ors_limit->lms_s_pr_hide )
1022         {
1023                 tentries = BDB_IDL_N(candidates);
1024         }
1025
1026         if ( get_pagedresults( sop ) > SLAP_CONTROL_IGNORED ) {
1027                 PagedResultsState *ps = sop->o_pagedresults_state;
1028                 /* deferred cookie parsing */
1029                 rs->sr_err = parse_paged_cookie( sop, rs );
1030                 if ( rs->sr_err != LDAP_SUCCESS ) {
1031                         send_ldap_result( sop, rs );
1032                         goto done;
1033                 }
1034
1035                 if ( (ID)( ps->ps_cookie ) == 0 ) {
1036                         id = bdb_idl_first( candidates, &cursor );
1037
1038                 } else {
1039                         if ( ps->ps_size == 0 ) {
1040                                 rs->sr_err = LDAP_SUCCESS;
1041                                 rs->sr_text = "search abandoned by pagedResult size=0";
1042                                 send_ldap_result( sop, rs );
1043                                 goto done;
1044                         }
1045                         for ( id = bdb_idl_first( candidates, &cursor );
1046                                 id != NOID &&
1047                                         id <= (ID)( ps->ps_cookie );
1048                                 id = bdb_idl_next( candidates, &cursor ) )
1049                         {
1050                                 /* empty */;
1051                         }
1052                 }
1053
1054                 if ( cursor == NOID ) {
1055                         Debug( LDAP_DEBUG_TRACE, 
1056                                 LDAP_XSTRING(bdb_search)
1057                                 ": no paged results candidates\n",
1058                                 0, 0, 0 );
1059                         send_paged_response( sop, rs, &lastid, 0 );
1060
1061                         rs->sr_err = LDAP_OTHER;
1062                         goto done;
1063                 }
1064                 goto loop_begin;
1065         }
1066
1067 #ifdef BDB_PSEARCH
1068         if (( sop->o_sync_mode & SLAP_SYNC_REFRESH ) || IS_PSEARCH ) {
1069                 int match;
1070
1071                 cookief.f_choice = LDAP_FILTER_AND;
1072                 cookief.f_and = &csnfnot;
1073                 cookief.f_next = NULL;
1074
1075                 csnfnot.f_choice = LDAP_FILTER_NOT;
1076                 csnfnot.f_not = &csnfeq;
1077                 csnfnot.f_next = &csnfand;
1078
1079                 csnfeq.f_choice = LDAP_FILTER_EQUALITY;
1080                 csnfeq.f_ava = &aa_eq;
1081                 csnfeq.f_av_desc = slap_schema.si_ad_entryCSN;
1082                 if ( sop->o_sync_state.ctxcsn != NULL ) {
1083                         csnfeq.f_av_value = *sop->o_sync_state.ctxcsn;
1084                 } else {
1085                         csnfeq.f_av_value = slap_empty_bv;
1086                 }
1087
1088                 csnfand.f_choice = LDAP_FILTER_AND;
1089                 csnfand.f_and = &csnfge;
1090                 csnfand.f_next = NULL;
1091
1092                 csnfge.f_choice = LDAP_FILTER_GE;
1093                 csnfge.f_ava = &aa_ge;
1094                 csnfge.f_av_desc = slap_schema.si_ad_entryCSN;
1095                 if ( sop->o_sync_state.ctxcsn != NULL ) {
1096                         csnfge.f_av_value = *sop->o_sync_state.ctxcsn;
1097                 } else {
1098                         csnfge.f_av_value = slap_empty_bv;
1099                 }
1100
1101                 if ( search_context_csn && !IS_PSEARCH ) {
1102                         csnfge.f_next = &contextcsnand;
1103
1104                         contextcsnand.f_choice = LDAP_FILTER_AND;
1105                         contextcsnand.f_and = &contextcsnle;
1106                         contextcsnand.f_next = NULL;
1107         
1108                         contextcsnle.f_choice = LDAP_FILTER_LE;
1109                         contextcsnle.f_ava = &aa_le;
1110                         contextcsnle.f_av_desc = slap_schema.si_ad_entryCSN;
1111                         contextcsnle.f_av_value = *search_context_csn;
1112                         contextcsnle.f_next = sop->oq_search.rs_filter;
1113
1114                         mr = slap_schema.si_ad_entryCSN->ad_type->sat_ordering;
1115                         if ( sop->o_sync_state.ctxcsn &&
1116                                 sop->o_sync_state.ctxcsn->bv_val != NULL )
1117                         {
1118                                 value_match( &match, slap_schema.si_ad_entryCSN, mr,
1119                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1120                                                 &sop->o_sync_state.ctxcsn[0], search_context_csn,
1121                                                 &text );
1122                         } else {
1123                                 match = -1;
1124                         }
1125                         no_sync_state_change = ( match >= 0 );
1126                 } else {
1127                         csnfge.f_next = sop->oq_search.rs_filter;
1128                 }
1129         }
1130 #endif
1131
1132 loop_start:
1133
1134         for ( id = bdb_idl_first( candidates, &cursor );
1135                   id != NOID
1136 #ifdef BDB_PSEARCH
1137                         && !no_sync_state_change
1138 #endif
1139                 ; id = bdb_idl_next( candidates, &cursor ) )
1140         {
1141                 int scopeok = 0;
1142                 ID* idhole = NULL;
1143
1144 loop_begin:
1145
1146 #ifdef BDB_PSEARCH
1147                 if ( !IS_POST_SEARCH ) {
1148                         idhole = (ID*) avl_find( sop->o_psearch_finished,
1149                                                                          (caddr_t)&id, bdb_pfid_cmp );
1150                         if ( idhole ) {
1151                                 avl_delete( &sop->o_psearch_finished,
1152                                                         (caddr_t)idhole, bdb_pfid_cmp );
1153                                 sop->o_tmpfree( idhole, sop->o_tmpmemctx );
1154                                 goto loop_continue;
1155                         }
1156
1157                         if ( sop->o_refresh_in_progress ) {
1158                                 ldap_pvt_thread_mutex_lock( &sop->o_pcmutex );
1159                                 pce = LDAP_TAILQ_FIRST( &sop->o_ps_pre_candidates );    
1160                                 while ( pce && pce->pc_sent ) {
1161                                         pce = LDAP_TAILQ_NEXT( pce, pc_link );
1162                                 }
1163                                 ldap_pvt_thread_mutex_unlock( &sop->o_pcmutex );
1164                                 if ( pce ) {
1165                                         ID pos;
1166                                         if ( BDB_IDL_IS_RANGE( candidates ) ) {
1167                                                 if ( pce->pc_id >= candidates[1] &&
1168                                                          pce->pc_id <= candidates[2] &&
1169                                                          pce->pc_id > cursor-1 ) {
1170                                                         id = pce->pc_id;
1171                                                         cursor--;
1172                                                         avl_insert( &sop->o_psearch_finished,
1173                                                                                 (caddr_t)bdb_id_dup( sop, &pce->pc_id ),
1174                                                                                 bdb_pfid_cmp, avl_dup_error );
1175                                                 } else {
1176                                                         pce->pc_sent = 1;
1177                                                 }
1178                                         } else {
1179                                                 pos = bdb_idl_search(candidates, pce->pc_id);
1180                                                 if ( pos > cursor-1 && pos <= candidates[0] ) {
1181                                                         id = pce->pc_id;
1182                                                         cursor--;
1183                                                         avl_insert( &sop->o_psearch_finished,
1184                                                                                 (caddr_t)bdb_id_dup( sop, &pce->pc_id ),
1185                                                                                 bdb_pfid_cmp, avl_dup_error );
1186                                                 } else {
1187                                                         pce->pc_sent = 1;
1188                                                 }
1189                                         }
1190                                 }
1191                         }
1192                 }
1193
1194                 /* check for abandon */
1195                 if ( sop->o_abandon ) {
1196                         if ( sop != op ) {
1197                                 bdb_drop_psearch( sop, sop->o_msgid );
1198                         }
1199                         rs->sr_err = LDAP_SUCCESS;
1200                         goto done;
1201                 }
1202
1203                 if ( sop->o_cancel ) {
1204                         assert( sop->o_cancel == SLAP_CANCEL_REQ );
1205                         rs->sr_err = LDAP_CANCELLED;
1206                         send_ldap_result( sop, rs );
1207                         sop->o_cancel = SLAP_CANCEL_ACK;
1208                         rs->sr_err = LDAP_SUCCESS;
1209                         goto done;
1210                 }
1211 #else
1212                 /* check for abandon */
1213                 if ( sop->o_abandon ) {
1214                         rs->sr_err = LDAP_SUCCESS;
1215                         goto done;
1216                 }
1217 #endif
1218
1219                 /* check time limit */
1220                 if ( sop->ors_tlimit != SLAP_NO_LIMIT
1221                                 && slap_get_time() > stoptime )
1222                 {
1223                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
1224                         rs->sr_ref = rs->sr_v2ref;
1225                         send_ldap_result( sop, rs );
1226                         rs->sr_err = LDAP_SUCCESS;
1227                         goto done;
1228                 }
1229
1230 #ifdef BDB_PSEARCH
1231                 if (!IS_PSEARCH) {
1232 #endif
1233 id2entry_retry:
1234                         /* get the entry with reader lock */
1235                         ei = NULL;
1236                         rs->sr_err = bdb_cache_find_id( op, ltid,
1237                                 id, &ei, 0, locker, &lock );
1238
1239                         if (rs->sr_err == LDAP_BUSY) {
1240                                 rs->sr_text = "ldap server busy";
1241                                 send_ldap_result( sop, rs );
1242                                 goto done;
1243
1244                         } else if ( rs->sr_err == DB_LOCK_DEADLOCK
1245                                 || rs->sr_err == DB_LOCK_NOTGRANTED )
1246                         {
1247                                 goto id2entry_retry;    
1248                         }
1249
1250                         if ( ei && rs->sr_err == LDAP_SUCCESS ) {
1251                                 e = ei->bei_e;
1252                         } else {
1253                                 e = NULL;
1254                         }
1255
1256                         if ( e == NULL ) {
1257 #ifdef BDB_PSEARCH
1258                                 if ( IS_POST_SEARCH ) {
1259                                         /* send LDAP_SYNC_DELETE */
1260                                         rs->sr_entry = e = ps_e;
1261                                         goto post_search_no_entry;
1262                                 } else
1263 #endif
1264                                 if( !BDB_IDL_IS_RANGE(candidates) ) {
1265                                         /* only complain for non-range IDLs */
1266                                         Debug( LDAP_DEBUG_TRACE,
1267                                                 LDAP_XSTRING(bdb_search)
1268                                                 ": candidate %ld not found\n",
1269                                                 (long) id, 0, 0 );
1270                                 }
1271
1272                                 goto loop_continue;
1273                         }
1274 #ifdef BDB_PSEARCH
1275                 } else {
1276                         e = ps_e;
1277                 }
1278 #endif
1279
1280                 rs->sr_entry = e;
1281
1282 #ifdef BDB_SUBENTRIES
1283                 /* FIXME: send all but syncrepl */
1284 #if 0
1285                 if ( !is_sync_protocol( sop ) )
1286 #endif
1287                 {
1288                         if ( is_entry_subentry( e ) ) {
1289                                 if( sop->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
1290                                         if(!get_subentries_visibility( sop )) {
1291                                                 /* only subentries are visible */
1292                                                 goto loop_continue;
1293                                         }
1294
1295                                 } else if ( get_subentries( sop ) &&
1296                                         !get_subentries_visibility( sop ))
1297                                 {
1298                                         /* only subentries are visible */
1299                                         goto loop_continue;
1300                                 }
1301
1302                         } else if ( get_subentries_visibility( sop )) {
1303                                 /* only subentries are visible */
1304                                 goto loop_continue;
1305                         }
1306                 }
1307 #endif /* BDB_SUBENTRIES */
1308
1309                 /* Does this candidate actually satisfy the search scope?
1310                  *
1311                  * Note that we don't lock access to the bei_parent pointer.
1312                  * Since only leaf nodes can be deleted, the parent of any
1313                  * node will always be a valid node. Also since we have
1314                  * a Read lock on the data, it cannot be renamed out of the
1315                  * scope while we are looking at it, and unless we're using
1316                  * BDB_HIER, its parents cannot be moved either.
1317                  */
1318                 switch( sop->ors_scope ) {
1319                 case LDAP_SCOPE_BASE:
1320                         /* This is always true, yes? */
1321                         if ( id == base.e_id ) scopeok = 1;
1322                         break;
1323
1324                 case LDAP_SCOPE_ONELEVEL:
1325                         if ( ei->bei_parent->bei_id == base.e_id ) scopeok = 1;
1326                         break;
1327
1328 #ifdef LDAP_SCOPE_CHILDREN
1329                 case LDAP_SCOPE_CHILDREN:
1330                         if ( id == base.e_id ) break;
1331                         /* Fall-thru */
1332 #endif
1333                 case LDAP_SCOPE_SUBTREE: {
1334                         EntryInfo *tmp;
1335                         for ( tmp = BEI(e); tmp; tmp = tmp->bei_parent ) {
1336                                 if ( tmp->bei_id == base.e_id ) {
1337                                         scopeok = 1;
1338                                         break;
1339                                 }
1340                         }
1341                         } break;
1342                 }
1343
1344                 /* aliases were already dereferenced in candidate list */
1345                 if ( sop->ors_deref & LDAP_DEREF_SEARCHING ) {
1346                         /* but if the search base is an alias, and we didn't
1347                          * deref it when finding, return it.
1348                          */
1349                         if ( is_entry_alias(e) &&
1350                                 ((sop->ors_deref & LDAP_DEREF_FINDING) ||
1351                                         !bvmatch(&e->e_nname, &op->o_req_ndn)))
1352                         {
1353                                 goto loop_continue;
1354                         }
1355
1356                         /* scopes is only non-empty for onelevel or subtree */
1357                         if ( !scopeok && BDB_IDL_N(scopes) ) {
1358                                 unsigned x;
1359                                 if ( sop->ors_scope == LDAP_SCOPE_ONELEVEL ) {
1360                                         x = bdb_idl_search( scopes, e->e_id );
1361                                         if ( scopes[x] == e->e_id ) scopeok = 1;
1362                                 } else {
1363                                         /* subtree, walk up the tree */
1364                                         EntryInfo *tmp = BEI(e);
1365                                         for (;tmp->bei_parent; tmp=tmp->bei_parent) {
1366                                                 x = bdb_idl_search( scopes, tmp->bei_id );
1367                                                 if ( scopes[x] == tmp->bei_id ) {
1368                                                         scopeok = 1;
1369                                                         break;
1370                                                 }
1371                                         }
1372                                 }
1373                         }
1374                 }
1375
1376                 /* Not in scope, ignore it */
1377 #ifdef BDB_PSEARCH
1378                 if ( !IS_POST_SEARCH && !scopeok )
1379 #else
1380                 if ( !scopeok )
1381 #endif
1382                 {
1383                         Debug( LDAP_DEBUG_TRACE,
1384                                 LDAP_XSTRING(bdb_search)
1385                                 ": %ld scope not okay\n",
1386                                 (long) id, 0, 0 );
1387                         goto loop_continue;
1388                 }
1389
1390                 /*
1391                  * if it's a referral, add it to the list of referrals. only do
1392                  * this for non-base searches, and don't check the filter
1393                  * explicitly here since it's only a candidate anyway.
1394                  */
1395                 if ( !manageDSAit && sop->oq_search.rs_scope != LDAP_SCOPE_BASE
1396                         && is_entry_referral( e ) )
1397                 {
1398                         BerVarray erefs = get_entry_referrals( sop, e );
1399                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
1400                                 sop->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
1401                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
1402
1403                         send_search_reference( sop, rs );
1404
1405                         ber_bvarray_free( rs->sr_ref );
1406                         ber_bvarray_free( erefs );
1407                         rs->sr_ref = NULL;
1408
1409                         goto loop_continue;
1410                 }
1411
1412                 if ( !manageDSAit && is_entry_glue( e )) {
1413                         goto loop_continue;
1414                 }
1415
1416                 /* if it matches the filter and scope, send it */
1417 #ifndef BDB_PSEARCH
1418                 rs->sr_err = test_filter( sop, rs->sr_entry, sop->oq_search.rs_filter );
1419 #else
1420                 if (IS_PSEARCH) {
1421                         if (ps_type != LDAP_PSEARCH_BY_SCOPEOUT) {
1422                                 rs->sr_err = test_filter( sop, rs->sr_entry, &cookief );
1423                         } else {
1424                                 rs->sr_err = LDAP_COMPARE_TRUE;
1425                         }
1426
1427                 } else {
1428                         if ( !IS_POST_SEARCH ) {
1429                                 if ( sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
1430                                         rc_sync = test_filter( sop, rs->sr_entry, &cookief );
1431                                         rs->sr_err = test_filter( sop, rs->sr_entry,
1432                                                                                 &contextcsnand );
1433                                         if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
1434                                                 if ( rc_sync == LDAP_COMPARE_TRUE ) {
1435                                                         if ( no_sync_state_change ) {
1436                                                                 Debug( LDAP_DEBUG_TRACE,
1437                                                                         LDAP_XSTRING(bdb_search) ": "
1438                                                                         "error in context csn management\n",
1439                                                                         0, 0, 0 );
1440                                                         }
1441                                                         entry_sync_state = LDAP_SYNC_ADD;
1442
1443                                                 } else {
1444                                                         if ( no_sync_state_change ) {
1445                                                                 goto loop_continue;
1446                                                         }
1447                                                         entry_sync_state = LDAP_SYNC_PRESENT;
1448                                                 }
1449                                         }
1450                                 } else {
1451                                         rs->sr_err = test_filter( sop,
1452                                                 rs->sr_entry, sop->oq_search.rs_filter );
1453                                 }
1454                         } else {
1455                                 if ( scopeok ) {
1456                                         rs->sr_err = test_filter( sop,
1457                                                 rs->sr_entry, sop->oq_search.rs_filter );
1458                                 } else {
1459                                         rs->sr_err = LDAP_COMPARE_TRUE;
1460                                 }
1461                         }
1462                 }
1463 #endif
1464
1465                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
1466                         /* check size limit */
1467                         if ( --sop->ors_slimit == -1
1468 #ifdef BDB_PSEARCH
1469                                 && sop->o_sync_slog_size == -1
1470 #endif
1471                          ) {
1472 #ifdef BDB_PSEARCH
1473                                 if (!IS_PSEARCH) {
1474 #endif
1475                                         bdb_cache_return_entry_r( bdb->bi_dbenv,
1476                                                 &bdb->bi_cache, e, &lock );
1477 #ifdef BDB_PSEARCH
1478                                 }
1479 #endif
1480                                 e = NULL;
1481                                 rs->sr_entry = NULL;
1482                                 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
1483                                 rs->sr_ref = rs->sr_v2ref;
1484                                 send_ldap_result( sop, rs );
1485                                 rs->sr_err = LDAP_SUCCESS;
1486                                 goto done;
1487                         }
1488
1489                         if ( get_pagedresults(sop) > SLAP_CONTROL_IGNORED ) {
1490                                 if ( rs->sr_nentries >= ((PagedResultsState *)sop->o_pagedresults_state)->ps_size ) {
1491                                         send_paged_response( sop, rs, &lastid, tentries );
1492                                         goto done;
1493                                 }
1494                                 lastid = id;
1495                         }
1496
1497                         if (e) {
1498                                 /* safe default */
1499                                 int result = -1;
1500 #ifdef BDB_PSEARCH
1501                                 if (IS_PSEARCH || IS_POST_SEARCH) {
1502                                         int premodify_found = 0;
1503
1504                                         if ( IS_POST_SEARCH ||
1505                                                  ps_type == LDAP_PSEARCH_BY_ADD ||
1506                                                  ps_type == LDAP_PSEARCH_BY_DELETE ||
1507                                                  ps_type == LDAP_PSEARCH_BY_MODIFY ||
1508                                                  ps_type == LDAP_PSEARCH_BY_SCOPEOUT )
1509                                         {
1510                                                 if ( !IS_POST_SEARCH &&
1511                                                          ps_type == LDAP_PSEARCH_BY_MODIFY ) {
1512                                                         struct psid_entry* psid_e;
1513                                                         LDAP_LIST_FOREACH( psid_e,
1514                                                                 &op->o_pm_list, ps_link)
1515                                                         {
1516                                                                 if( psid_e->ps_op == sop ) {
1517                                                                         premodify_found = 1;
1518                                                                         LDAP_LIST_REMOVE(psid_e, ps_link);
1519                                                                         break;
1520                                                                 }
1521                                                         }
1522                                                         if (psid_e != NULL) free (psid_e);
1523                                                 }
1524
1525                                                 if ( IS_POST_SEARCH ) {
1526                                                         if ( scopeok ) {
1527                                                                 entry_sync_state = LDAP_SYNC_ADD;
1528                                                         } else {
1529 post_search_no_entry:
1530                                                                 entry_sync_state = LDAP_SYNC_DELETE;
1531                                                         }
1532                                                 } else if ( ps_type == LDAP_PSEARCH_BY_ADD ) {
1533                                                         entry_sync_state = LDAP_SYNC_ADD;
1534                                                 } else if ( ps_type == LDAP_PSEARCH_BY_DELETE ) {
1535                                                         entry_sync_state = LDAP_SYNC_DELETE;
1536                                                 } else if ( ps_type == LDAP_PSEARCH_BY_MODIFY ) {
1537                                                         if ( premodify_found ) {
1538                                                                 entry_sync_state = LDAP_SYNC_MODIFY;
1539                                                         } else {
1540                                                                 entry_sync_state = LDAP_SYNC_ADD;
1541                                                         }
1542                                                 } else if ( ps_type == LDAP_PSEARCH_BY_SCOPEOUT ) {
1543                                                         entry_sync_state = LDAP_SYNC_DELETE;
1544                                                 } else {
1545                                                         rs->sr_err = LDAP_OTHER;
1546                                                         goto done;
1547                                                 }
1548
1549                                                 if ( sop->o_sync_slog_size != -1 ) {
1550                                                         if ( entry_sync_state == LDAP_SYNC_DELETE ) {
1551                                                                 result = slap_add_session_log( op, sop, e );
1552                                                         } else {
1553                                                                 result = 1;
1554                                                         }
1555                                                 } else {
1556                                                         struct berval cookie;
1557                                                         slap_compose_sync_cookie( sop, &cookie,
1558                                                                 search_context_csn,
1559                                                                 sop->o_sync_state.sid,
1560                                                                 sop->o_sync_state.rid );
1561                                                         rs->sr_err = slap_build_sync_state_ctrl(
1562                                                                 sop, rs, e, entry_sync_state, ctrls,
1563                                                                 num_ctrls++, 1, &cookie );
1564                                                         if ( rs->sr_err != LDAP_SUCCESS ) goto done;
1565                                                         if (!(IS_POST_SEARCH &&
1566                                                                 entry_sync_state == LDAP_SYNC_DELETE)) {
1567                                                                 rs->sr_attrs = attrs;
1568                                                         } else {
1569                                                                 rs->sr_attrs = NULL;
1570                                                         }
1571                                                         rs->sr_operational_attrs = NULL;
1572                                                         rs->sr_ctrls = ctrls;
1573                                                         rs->sr_flags = 0;
1574                                                         result = send_search_entry( sop, rs );
1575                                                         if ( cookie.bv_val ) ch_free( cookie.bv_val );  
1576                                                         slap_sl_free(
1577                                                                 ctrls[num_ctrls-1]->ldctl_value.bv_val,
1578                                                                 sop->o_tmpmemctx );
1579                                                         slap_sl_free( ctrls[--num_ctrls],
1580                                                                 sop->o_tmpmemctx );
1581                                                         ctrls[num_ctrls] = NULL;
1582                                                         rs->sr_ctrls = NULL;
1583                                                 }
1584
1585                                         } else if ( ps_type == LDAP_PSEARCH_BY_PREMODIFY ) {
1586                                                 struct psid_entry* psid_e;
1587                                                 psid_e = (struct psid_entry *) ch_calloc(1,
1588                                                         sizeof(struct psid_entry));
1589                                                 psid_e->ps_op = sop;
1590                                                 LDAP_LIST_INSERT_HEAD( &op->o_pm_list,
1591                                                         psid_e, ps_link );
1592
1593                                         } else {
1594                                                 Debug( LDAP_DEBUG_TRACE,
1595                                                         LDAP_XSTRING(bdb_search)
1596                                                         ": invalid ps_type (%d) \n",
1597                                                         ps_type, 0, 0);
1598                                         }
1599
1600                                 } else {
1601                                         if ( sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
1602                                                 if ( rc_sync == LDAP_COMPARE_TRUE ) { /* ADD */
1603                                                         rs->sr_err = slap_build_sync_state_ctrl(
1604                                                                 sop, rs, e, entry_sync_state, ctrls,
1605                                                                 num_ctrls++, 0, NULL );
1606                                                         if ( rs->sr_err != LDAP_SUCCESS ) goto done;
1607                                                         rs->sr_ctrls = ctrls;
1608                                                         rs->sr_attrs = sop->oq_search.rs_attrs;
1609                                                         rs->sr_operational_attrs = NULL;
1610                                                         rs->sr_flags = 0;
1611                                                         result = send_search_entry( sop, rs );
1612                                                         slap_sl_free(
1613                                                                 ctrls[num_ctrls-1]->ldctl_value.bv_val,
1614                                                                 sop->o_tmpmemctx );
1615                                                         slap_sl_free( ctrls[--num_ctrls],
1616                                                                 sop->o_tmpmemctx );
1617                                                         ctrls[num_ctrls] = NULL;
1618                                                         rs->sr_ctrls = NULL;
1619
1620                                                 } else { /* PRESENT */
1621                                                         if ( sync_send_present_mode ) {
1622                                                                 result = slap_build_syncUUID_set( sop,
1623                                                                         &syncUUID_set, e );
1624                                                                 if ( result <= 0 ) {
1625                                                                         result = -1;    
1626                                                                 } else {
1627                                                                         syncUUID_set_cnt++;
1628                                                                         if ( syncUUID_set_cnt ==
1629                                                                                 SLAP_SYNCUUID_SET_SIZE )
1630                                                                         {
1631                                                                                 rs->sr_err = LDAP_SUCCESS;
1632                                                                                 rs->sr_rspoid = LDAP_SYNC_INFO;
1633                                                                                 rs->sr_ctrls = NULL;
1634                                                                                 result = slap_send_syncinfo( sop, rs,
1635                                                                                         LDAP_TAG_SYNC_ID_SET,
1636                                                                                         NULL, 0, syncUUID_set, 0 );
1637                                                                                 if ( result != LDAP_SUCCESS ) {
1638                                                                                         result = -1;
1639                                                                                 }
1640                                                                                 ber_bvarray_free_x( syncUUID_set,
1641                                                                                         sop->o_tmpmemctx );
1642                                                                                 syncUUID_set = NULL;
1643                                                                                 syncUUID_set_cnt = 0;
1644                                                                         }
1645                                                                 }
1646
1647                                                         } else {
1648                                                                 result = 1;
1649                                                         }
1650                                                 }
1651
1652                                         } else {
1653 #endif
1654                                                 rs->sr_attrs = sop->oq_search.rs_attrs;
1655                                                 rs->sr_operational_attrs = NULL;
1656                                                 rs->sr_ctrls = NULL;
1657                                                 rs->sr_flags = 0;
1658                                                 rs->sr_err = LDAP_SUCCESS;
1659                                                 result = send_search_entry( sop, rs );
1660 #ifdef BDB_PSEARCH
1661                                         }
1662                                 }
1663 #endif
1664
1665                                 switch (result) {
1666                                 case 0:         /* entry sent ok */
1667                                         break;
1668                                 case 1:         /* entry not sent */
1669                                         break;
1670                                 case -1:        /* connection closed */
1671 #ifdef BDB_PSEARCH
1672                                         if (!IS_PSEARCH) {
1673 #endif
1674                                                 bdb_cache_return_entry_r(bdb->bi_dbenv,
1675                                                         &bdb->bi_cache, e, &lock);
1676 #ifdef BDB_PSEARCH
1677                                         }
1678 #endif
1679                                         e = NULL;
1680                                         rs->sr_entry = NULL;
1681                                         rs->sr_err = LDAP_OTHER;
1682                                         goto done;
1683                                 }
1684                         }
1685
1686                 } else {
1687                         Debug( LDAP_DEBUG_TRACE,
1688                                 LDAP_XSTRING(bdb_search)
1689                                 ": %ld does not match filter\n",
1690                                 (long) id, 0, 0 );
1691                 }
1692
1693 loop_continue:
1694                 if( e != NULL ) {
1695                         /* free reader lock */
1696 #ifdef BDB_PSEARCH
1697                         if (!IS_PSEARCH) {
1698                                 if (!(IS_POST_SEARCH &&
1699                                                  entry_sync_state == LDAP_SYNC_DELETE)) {
1700                                         bdb_cache_return_entry_r( bdb->bi_dbenv,
1701                                                 &bdb->bi_cache, e , &lock );
1702                                         if ( sop->o_nocaching ) {
1703                                                 bdb_cache_delete_entry( bdb, ei, locker, &lock );
1704                                         }
1705                                 }
1706                         }
1707 #else
1708                         bdb_cache_return_entry_r( bdb->bi_dbenv,
1709                                 &bdb->bi_cache, e , &lock );
1710 #endif
1711                         e = NULL;
1712                         rs->sr_entry = NULL;
1713                 }
1714                 
1715 #ifdef BDB_PSEARCH
1716                 if ( sop->o_refresh_in_progress ) {
1717                         if ( pce ) {
1718                                 pce->pc_sent = 1;
1719                         }
1720                 }
1721 #endif
1722
1723                 ldap_pvt_thread_yield();
1724         }
1725
1726 #ifdef BDB_PSEARCH
1727         if ( syncUUID_set_cnt > 0 ) {
1728                 rs->sr_err = LDAP_SUCCESS;
1729                 rs->sr_rspoid = LDAP_SYNC_INFO;
1730                 rs->sr_ctrls = NULL;
1731                 slap_send_syncinfo( sop, rs, LDAP_TAG_SYNC_ID_SET,
1732                         NULL, 0, syncUUID_set, 0 );
1733                 ber_bvarray_free_x( syncUUID_set, sop->o_tmpmemctx );
1734                 syncUUID_set_cnt = 0;
1735         }
1736 #endif
1737
1738 nochange:
1739 #ifdef BDB_PSEARCH
1740         if (!IS_PSEARCH && !IS_POST_SEARCH) {
1741                 if ( sop->o_sync_mode & SLAP_SYNC_REFRESH ) {
1742                         if ( sop->o_sync_mode & SLAP_SYNC_PERSIST ) {
1743                                 struct berval cookie;
1744                                 slap_compose_sync_cookie( sop, &cookie, search_context_csn,
1745                                         sop->o_sync_state.sid, sop->o_sync_state.rid );
1746
1747                                 if ( sync_send_present_mode ) {
1748                                         rs->sr_err = LDAP_SUCCESS;
1749                                         rs->sr_rspoid = LDAP_SYNC_INFO;
1750                                         rs->sr_ctrls = NULL;
1751                                         slap_send_syncinfo( sop, rs,
1752                                                 LDAP_TAG_SYNC_REFRESH_PRESENT, &cookie, 1, NULL, 0 );
1753
1754                                 } else {
1755                                         if ( !no_sync_state_change ) {
1756                                                 int slog_found = 0;
1757                                                 ldap_pvt_thread_rdwr_rlock( &bdb->bi_pslist_rwlock );
1758                                                 LDAP_LIST_FOREACH( ps_list, &bdb->bi_psearch_list,
1759                                                         o_ps_link )
1760                                                 {
1761                                                         if ( ps_list->o_sync_slog_size > 0 ) {
1762                                                                 if ( ps_list->o_sync_state.sid ==
1763                                                                         sop->o_sync_state.sid )
1764                                                                 {
1765                                                                         slog_found = 1;
1766                                                                         break;
1767                                                                 }
1768                                                         }
1769                                                 }
1770                 
1771                                                 if ( slog_found ) {
1772                                                         rs->sr_err = LDAP_SUCCESS;
1773                                                         rs->sr_rspoid = NULL;
1774                                                         rs->sr_ctrls = NULL;
1775                                                         slap_send_session_log( op, ps_list, rs );
1776                                                 }
1777                                                 ldap_pvt_thread_rdwr_runlock( &bdb->bi_pslist_rwlock );
1778                                         }
1779
1780                                         rs->sr_err = LDAP_SUCCESS;
1781                                         rs->sr_rspoid = LDAP_SYNC_INFO;
1782                                         rs->sr_ctrls = NULL;
1783                                         slap_send_syncinfo( sop, rs,
1784                                                 LDAP_TAG_SYNC_REFRESH_DELETE, &cookie, 1, NULL, 0 );
1785                                 }
1786
1787                                 if ( cookie.bv_val ) ch_free( cookie.bv_val );
1788
1789                         } else {
1790                                 /* refreshOnly mode */
1791                                 struct berval cookie;
1792                                 slap_compose_sync_cookie( sop, &cookie, search_context_csn,
1793                                         sop->o_sync_state.sid, sop->o_sync_state.rid );
1794
1795                                 if ( sync_send_present_mode ) {
1796                                         slap_build_sync_done_ctrl( sop, rs, ctrls,
1797                                                 num_ctrls++, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
1798
1799                                 } else {
1800                                         if ( !no_sync_state_change ) {
1801                                                 int slog_found = 0;
1802                                                 ldap_pvt_thread_rdwr_rlock( &bdb->bi_pslist_rwlock );
1803                                                 LDAP_LIST_FOREACH( ps_list, &bdb->bi_psearch_list,
1804                                                         o_ps_link )
1805                                                 {
1806                                                         if ( ps_list->o_sync_slog_size > 0 ) {
1807                                                                 if ( ps_list->o_sync_state.sid ==
1808                                                                                 sop->o_sync_state.sid ) {
1809                                                                         slog_found = 1;
1810                                                                         break;
1811                                                                 }
1812                                                         }
1813                                                 }
1814                 
1815                                                 if ( slog_found ) {
1816                                                         slap_send_session_log( op, ps_list, rs );
1817                                                 }
1818                                                 ldap_pvt_thread_rdwr_runlock( &bdb->bi_pslist_rwlock );
1819                                         }
1820
1821                                         slap_build_sync_done_ctrl( sop, rs, ctrls,
1822                                                 num_ctrls++, 1, &cookie, LDAP_SYNC_REFRESH_DELETES );
1823                                 }
1824
1825                                 rs->sr_ctrls = ctrls;
1826                                 rs->sr_ref = rs->sr_v2ref;
1827                                 rs->sr_err = (rs->sr_v2ref == NULL)
1828                                         ? LDAP_SUCCESS : LDAP_REFERRAL;
1829                                 rs->sr_rspoid = NULL;
1830                                 send_ldap_result( sop, rs );
1831                                 if ( ctrls[num_ctrls-1]->ldctl_value.bv_val != NULL ) {
1832                                         slap_sl_free( ctrls[num_ctrls-1]->ldctl_value.bv_val,
1833                                                 sop->o_tmpmemctx );
1834                                 }
1835                                 slap_sl_free( ctrls[--num_ctrls], sop->o_tmpmemctx );
1836                                 ctrls[num_ctrls] = NULL;
1837                                 if ( cookie.bv_val ) ch_free( cookie.bv_val );  
1838                         }
1839
1840                 } else {
1841 #endif
1842                         rs->sr_ctrls = NULL;
1843                         rs->sr_ref = rs->sr_v2ref;
1844                         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
1845                         rs->sr_rspoid = NULL;
1846                         if ( get_pagedresults(sop) > SLAP_CONTROL_IGNORED ) {
1847                                 send_paged_response( sop, rs, NULL, 0 );
1848                         } else {
1849                                 send_ldap_result( sop, rs );
1850                         }
1851 #ifdef BDB_PSEARCH
1852                 }
1853         }
1854
1855         if ( sop->o_refresh_in_progress ) {
1856                 sop->o_refresh_in_progress = 0;
1857         }
1858 #endif
1859
1860         rs->sr_err = LDAP_SUCCESS;
1861
1862 done:
1863 #ifdef BDB_PSEARCH
1864         if ( sop->o_psearch_finished ) {
1865                 avl_free( sop->o_psearch_finished, ch_free );
1866         }
1867
1868         if( !IS_PSEARCH && e != NULL ) {
1869                 /* free reader lock */
1870                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache, e, &lock );
1871         }
1872         ber_bvfree( search_context_csn );
1873 #endif
1874
1875         if ( !opinfo )
1876                 LOCK_ID_FREE( bdb->bi_dbenv, locker );
1877
1878         if( rs->sr_v2ref ) {
1879                 ber_bvarray_free( rs->sr_v2ref );
1880                 rs->sr_v2ref = NULL;
1881         }
1882         if( realbase.bv_val ) ch_free( realbase.bv_val );
1883
1884         return rs->sr_err;
1885 }
1886
1887
1888 static int base_candidate(
1889         BackendDB       *be,
1890         Entry   *e,
1891         ID              *ids )
1892 {
1893         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
1894                 e->e_nname.bv_val, (long) e->e_id, 0);
1895
1896         ids[0] = 1;
1897         ids[1] = e->e_id;
1898         return 0;
1899 }
1900
1901 /* Look for "objectClass Present" in this filter.
1902  * Also count depth of filter tree while we're at it.
1903  */
1904 static int oc_filter(
1905         Filter *f,
1906         int cur,
1907         int *max )
1908 {
1909         int rc = 0;
1910
1911         assert( f );
1912
1913         if( cur > *max ) *max = cur;
1914
1915         switch( f->f_choice ) {
1916         case LDAP_FILTER_PRESENT:
1917                 if (f->f_desc == slap_schema.si_ad_objectClass) {
1918                         rc = 1;
1919                 }
1920                 break;
1921
1922         case LDAP_FILTER_AND:
1923         case LDAP_FILTER_OR:
1924                 cur++;
1925                 for ( f=f->f_and; f; f=f->f_next ) {
1926                         (void) oc_filter(f, cur, max);
1927                 }
1928                 break;
1929
1930         default:
1931                 break;
1932         }
1933         return rc;
1934 }
1935
1936 static void search_stack_free( void *key, void *data )
1937 {
1938         ber_memfree_x(data, NULL);
1939 }
1940
1941 static void *search_stack( Operation *op )
1942 {
1943         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1944         void *ret = NULL;
1945
1946         if ( op->o_threadctx ) {
1947                 ldap_pvt_thread_pool_getkey( op->o_threadctx, search_stack,
1948                         &ret, NULL );
1949         } else {
1950                 ret = bdb->bi_search_stack;
1951         }
1952
1953         if ( !ret ) {
1954                 ret = ch_malloc( bdb->bi_search_stack_depth * BDB_IDL_UM_SIZE
1955                         * sizeof( ID ) );
1956                 if ( op->o_threadctx ) {
1957                         ldap_pvt_thread_pool_setkey( op->o_threadctx, search_stack,
1958                                 ret, search_stack_free );
1959                 } else {
1960                         bdb->bi_search_stack = ret;
1961                 }
1962         }
1963         return ret;
1964 }
1965
1966 static int search_candidates(
1967         Operation *stackop,
1968         Operation *op,
1969         SlapReply *rs,
1970         Entry *e,
1971         u_int32_t locker,
1972         ID      *ids,
1973         ID      *scopes )
1974 {
1975         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1976         int rc, depth = 1;
1977         Filter          f, rf, xf, nf;
1978         ID              *stack;
1979         AttributeAssertion aa_ref;
1980 #ifdef BDB_SUBENTRIES
1981         Filter  sf;
1982         AttributeAssertion aa_subentry;
1983 #endif
1984
1985         /*
1986          * This routine takes as input a filter (user-filter)
1987          * and rewrites it as follows:
1988          *      (&(scope=DN)[(objectClass=subentry)]
1989          *              (|[(objectClass=referral)(objectClass=alias)](user-filter))
1990          */
1991
1992         Debug(LDAP_DEBUG_TRACE,
1993                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1994                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1995
1996         xf.f_or = op->oq_search.rs_filter;
1997         xf.f_choice = LDAP_FILTER_OR;
1998         xf.f_next = NULL;
1999
2000         /* If the user's filter uses objectClass=*,
2001          * these clauses are redundant.
2002          */
2003         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
2004                 && !get_subentries_visibility(op)
2005 #ifdef BDB_PSEARCH
2006                 && !is_sync_protocol(op)
2007 #endif
2008         ) {
2009                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
2010                         /* match referral objects */
2011                         struct berval bv_ref = BER_BVC( "referral" );
2012                         rf.f_choice = LDAP_FILTER_EQUALITY;
2013                         rf.f_ava = &aa_ref;
2014                         rf.f_av_desc = slap_schema.si_ad_objectClass;
2015                         rf.f_av_value = bv_ref;
2016                         rf.f_next = xf.f_or;
2017                         xf.f_or = &rf;
2018                         depth++;
2019                 }
2020         }
2021
2022         f.f_next = NULL;
2023         f.f_choice = LDAP_FILTER_AND;
2024         f.f_and = &nf;
2025         /* Dummy; we compute scope separately now */
2026         nf.f_choice = SLAPD_FILTER_COMPUTED;
2027         nf.f_result = LDAP_SUCCESS;
2028         nf.f_next = ( xf.f_or == op->oq_search.rs_filter )
2029                 ? op->oq_search.rs_filter : &xf ;
2030         /* Filter depth increased again, adding dummy clause */
2031         depth++;
2032
2033 #ifdef BDB_SUBENTRIES
2034         if( get_subentries_visibility( op ) ) {
2035                 struct berval bv_subentry = BER_BVC( "subentry" );
2036                 sf.f_choice = LDAP_FILTER_EQUALITY;
2037                 sf.f_ava = &aa_subentry;
2038                 sf.f_av_desc = slap_schema.si_ad_objectClass;
2039                 sf.f_av_value = bv_subentry;
2040                 sf.f_next = nf.f_next;
2041                 nf.f_next = &sf;
2042         }
2043 #endif
2044
2045         /* Allocate IDL stack, plus 1 more for former tmp */
2046         if ( depth+1 > bdb->bi_search_stack_depth ) {
2047                 stack = ch_malloc( (depth + 1) * BDB_IDL_UM_SIZE * sizeof( ID ) );
2048         } else {
2049                 stack = search_stack( stackop );
2050         }
2051
2052         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
2053                 rc = search_aliases( op, rs, e, locker, ids, scopes, stack );
2054         } else {
2055                 rc = bdb_dn2idl( op, e, ids, stack );
2056         }
2057
2058         if ( rc == LDAP_SUCCESS ) {
2059                 rc = bdb_filter_candidates( op, &f, ids,
2060                         stack, stack+BDB_IDL_UM_SIZE );
2061         }
2062
2063         if ( depth+1 > bdb->bi_search_stack_depth ) {
2064                 ch_free( stack );
2065         }
2066
2067         if( rc ) {
2068                 Debug(LDAP_DEBUG_TRACE,
2069                         "bdb_search_candidates: failed (rc=%d)\n",
2070                         rc, NULL, NULL );
2071
2072         } else {
2073                 Debug(LDAP_DEBUG_TRACE,
2074                         "bdb_search_candidates: id=%ld first=%ld last=%ld\n",
2075                         (long) ids[0],
2076                         (long) BDB_IDL_FIRST(ids),
2077                         (long) BDB_IDL_LAST(ids) );
2078         }
2079
2080         return rc;
2081 }
2082
2083 static int
2084 parse_paged_cookie( Operation *op, SlapReply *rs )
2085 {
2086         LDAPControl     **c;
2087         int             rc = LDAP_SUCCESS;
2088         ber_tag_t       tag;
2089         ber_int_t       size;
2090         BerElement      *ber;
2091         struct berval   cookie = BER_BVNULL;
2092         PagedResultsState *ps = op->o_pagedresults_state;
2093
2094         /* this function must be invoked only if the pagedResults
2095          * control has been detected, parsed and partially checked
2096          * by the frontend */
2097         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
2098
2099         /* look for the appropriate ctrl structure */
2100         for ( c = op->o_ctrls; c[0] != NULL; c++ ) {
2101                 if ( strcmp( c[0]->ldctl_oid, LDAP_CONTROL_PAGEDRESULTS ) == 0 )
2102                 {
2103                         break;
2104                 }
2105         }
2106
2107         if ( c[0] == NULL ) {
2108                 rs->sr_text = "missing pagedResults control";
2109                 return LDAP_PROTOCOL_ERROR;
2110         }
2111
2112         /* Tested by frontend */
2113         assert( c[0]->ldctl_value.bv_len > 0 );
2114
2115         /* Parse the control value
2116          *      realSearchControlValue ::= SEQUENCE {
2117          *              size    INTEGER (0..maxInt),
2118          *                              -- requested page size from client
2119          *                              -- result set size estimate from server
2120          *              cookie  OCTET STRING
2121          * }
2122          */
2123         ber = ber_init( &c[0]->ldctl_value );
2124         if ( ber == NULL ) {
2125                 rs->sr_text = "internal error";
2126                 return LDAP_OTHER;
2127         }
2128
2129         tag = ber_scanf( ber, "{im}", &size, &cookie );
2130
2131         /* Tested by frontend */
2132         assert( tag != LBER_ERROR );
2133         assert( size >= 0 );
2134
2135         /* cookie decoding/checks deferred to backend... */
2136         if ( cookie.bv_len ) {
2137                 PagedResultsCookie reqcookie;
2138                 if( cookie.bv_len != sizeof( reqcookie ) ) {
2139                         /* bad cookie */
2140                         rs->sr_text = "paged results cookie is invalid";
2141                         rc = LDAP_PROTOCOL_ERROR;
2142                         goto done;
2143                 }
2144
2145                 AC_MEMCPY( &reqcookie, cookie.bv_val, sizeof( reqcookie ));
2146
2147                 if ( reqcookie > ps->ps_cookie ) {
2148                         /* bad cookie */
2149                         rs->sr_text = "paged results cookie is invalid";
2150                         rc = LDAP_PROTOCOL_ERROR;
2151                         goto done;
2152
2153                 } else if ( reqcookie < ps->ps_cookie ) {
2154                         rs->sr_text = "paged results cookie is invalid or old";
2155                         rc = LDAP_UNWILLING_TO_PERFORM;
2156                         goto done;
2157                 }
2158
2159         } else {
2160                 /* Initial request.  Initialize state. */
2161 #if 0
2162                 if ( op->o_conn->c_pagedresults_state.ps_cookie != 0 ) {
2163                         /* There's another pagedResults control on the
2164                          * same connection; reject new pagedResults controls 
2165                          * (allowed by RFC2696) */
2166                         rs->sr_text = "paged results cookie unavailable; try later";
2167                         rc = LDAP_UNWILLING_TO_PERFORM;
2168                         goto done;
2169                 }
2170 #endif
2171                 ps->ps_cookie = 0;
2172                 ps->ps_count = 0;
2173         }
2174
2175 done:;
2176         (void)ber_free( ber, 1 );
2177
2178         return rc;
2179 }
2180
2181 static void
2182 send_paged_response( 
2183         Operation       *op,
2184         SlapReply       *rs,
2185         ID              *lastid,
2186         int             tentries )
2187 {
2188         LDAPControl     ctrl, *ctrls[2];
2189         BerElementBuffer berbuf;
2190         BerElement      *ber = (BerElement *)&berbuf;
2191         PagedResultsCookie respcookie;
2192         struct berval cookie;
2193
2194         Debug(LDAP_DEBUG_ARGS,
2195                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
2196                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
2197
2198         BER_BVZERO( &ctrl.ldctl_value );
2199         ctrls[0] = &ctrl;
2200         ctrls[1] = NULL;
2201
2202         ber_init2( ber, NULL, LBER_USE_DER );
2203
2204         if ( lastid ) {
2205                 respcookie = ( PagedResultsCookie )(*lastid);
2206                 cookie.bv_len = sizeof( respcookie );
2207                 cookie.bv_val = (char *)&respcookie;
2208
2209         } else {
2210                 respcookie = ( PagedResultsCookie )0;
2211                 BER_BVSTR( &cookie, "" );
2212         }
2213
2214         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
2215         op->o_conn->c_pagedresults_state.ps_count =
2216                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count + rs->sr_nentries;
2217
2218         /* return size of 0 -- no estimate */
2219         ber_printf( ber, "{iO}", 0, &cookie ); 
2220
2221         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
2222                 goto done;
2223         }
2224
2225         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
2226         ctrls[0]->ldctl_iscritical = 0;
2227
2228         rs->sr_ctrls = ctrls;
2229         rs->sr_err = LDAP_SUCCESS;
2230         send_ldap_result( op, rs );
2231         rs->sr_ctrls = NULL;
2232
2233 done:
2234         (void) ber_free_buf( ber );
2235 }
2236
2237 static int
2238 bdb_pfid_cmp( const void *v_id1, const void *v_id2 )
2239 {
2240     const ID *p1 = v_id1, *p2 = v_id2;
2241         return *p1 - *p2;
2242 }
2243
2244 static ID*
2245 bdb_id_dup( Operation *op, ID *id )
2246 {
2247         ID *new;
2248         new = ch_malloc( sizeof(ID) );
2249         *new = *id;
2250         return new;
2251 }