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