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