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