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