]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/search.c
74258eee23011d7f3072ad4ffaf8ccd6ed233e92
[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-2008 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16
17 #include "portable.h"
18
19 #include <stdio.h>
20 #include <ac/string.h>
21
22 #include "back-bdb.h"
23 #include "idl.h"
24
25 static int base_candidate(
26         BackendDB       *be,
27         Entry   *e,
28         ID              *ids );
29
30 static int search_candidates(
31         Operation *op,
32         SlapReply *rs,
33         Entry *e,
34         u_int32_t locker,
35         ID      *ids,
36         ID      *scopes );
37
38 static int parse_paged_cookie( Operation *op, SlapReply *rs );
39
40 static void send_paged_response( 
41         Operation *op,
42         SlapReply *rs,
43         ID  *lastid,
44         int tentries );
45
46 /* Dereference aliases for a single alias entry. Return the final
47  * dereferenced entry on success, NULL on any failure.
48  */
49 static Entry * deref_base (
50         Operation *op,
51         SlapReply *rs,
52         Entry *e,
53         Entry **matched,
54         u_int32_t locker,
55         DB_LOCK *lock,
56         ID      *tmp,
57         ID      *visited )
58 {
59         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
60         struct berval ndn;
61         EntryInfo *ei;
62         DB_LOCK lockr;
63
64         rs->sr_err = LDAP_ALIAS_DEREF_PROBLEM;
65         rs->sr_text = "maximum deref depth exceeded";
66
67         for (;;) {
68                 /* Remember the last entry we looked at, so we can
69                  * report broken links
70                  */
71                 *matched = e;
72
73                 if (BDB_IDL_N(tmp) >= op->o_bd->be_max_deref_depth) {
74                         e = NULL;
75                         break;
76                 }
77
78                 /* If this is part of a subtree or onelevel search,
79                  * have we seen this ID before? If so, quit.
80                  */
81                 if ( visited && bdb_idl_insert( visited, e->e_id ) ) {
82                         e = NULL;
83                         break;
84                 }
85
86                 /* If we've seen this ID during this deref iteration,
87                  * we've hit a loop.
88                  */
89                 if ( bdb_idl_insert( tmp, e->e_id ) ) {
90                         rs->sr_err = LDAP_ALIAS_PROBLEM;
91                         rs->sr_text = "circular alias";
92                         e = NULL;
93                         break;
94                 }
95
96                 /* If there was a problem getting the aliasedObjectName,
97                  * get_alias_dn will have set the error status.
98                  */
99                 if ( get_alias_dn(e, &ndn, &rs->sr_err, &rs->sr_text) ) {
100                         e = NULL;
101                         break;
102                 }
103
104                 rs->sr_err = bdb_dn2entry( op, NULL, &ndn, &ei,
105                         0, locker, &lockr );
106
107                 if ( ei ) {
108                         e = ei->bei_e;
109                 } else {
110                         e = NULL;
111                 }
112
113                 if (!e) {
114                         rs->sr_err = LDAP_ALIAS_PROBLEM;
115                         rs->sr_text = "aliasedObject not found";
116                         break;
117                 }
118
119                 /* Free the previous entry, continue to work with the
120                  * one we just retrieved.
121                  */
122                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
123                         *matched, lock);
124                 *lock = lockr;
125
126                 /* We found a regular entry. Return this to the caller. The
127                  * entry is still locked for Read.
128                  */
129                 if (!is_entry_alias(e)) {
130                         rs->sr_err = LDAP_SUCCESS;
131                         rs->sr_text = NULL;
132                         break;
133                 }
134         }
135         return e;
136 }
137
138 /* Look for and dereference all aliases within the search scope. Adds
139  * the dereferenced entries to the "ids" list. Requires "stack" to be
140  * able to hold 8 levels of DB_SIZE IDLs. Of course we're hardcoded to
141  * require a minimum of 8 UM_SIZE IDLs so this is never a problem.
142  */
143 static int search_aliases(
144         Operation *op,
145         SlapReply *rs,
146         Entry *e,
147         u_int32_t locker,
148         ID *ids,
149         ID *scopes,
150         ID *stack )
151 {
152         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
153         ID *aliases, *curscop, *subscop, *visited, *newsubs, *oldsubs, *tmp;
154         ID cursora, ida, cursoro, ido, *subscop2;
155         Entry *matched, *a;
156         EntryInfo *ei;
157         struct berval bv_alias = BER_BVC( "alias" );
158 #ifdef LDAP_COMP_MATCH
159         AttributeAssertion aa_alias = { NULL, BER_BVNULL, NULL };
160 #else
161         AttributeAssertion aa_alias = { NULL, BER_BVNULL };
162 #endif
163         Filter  af;
164         DB_LOCK locka, lockr;
165         int first = 1;
166
167         aliases = stack;        /* IDL of all aliases in the database */
168         curscop = aliases + BDB_IDL_DB_SIZE;    /* Aliases in the current scope */
169         subscop = curscop + BDB_IDL_DB_SIZE;    /* The current scope */
170         visited = subscop + BDB_IDL_DB_SIZE;    /* IDs we've seen in this search */
171         newsubs = visited + BDB_IDL_DB_SIZE;    /* New subtrees we've added */
172         oldsubs = newsubs + BDB_IDL_DB_SIZE;    /* Subtrees added previously */
173         tmp = oldsubs + BDB_IDL_DB_SIZE;        /* Scratch space for deref_base() */
174
175         /* A copy of subscop, because subscop gets clobbered by
176          * the bdb_idl_union/intersection routines
177          */
178         subscop2 = tmp + BDB_IDL_DB_SIZE;
179
180         af.f_choice = LDAP_FILTER_EQUALITY;
181         af.f_ava = &aa_alias;
182         af.f_av_desc = slap_schema.si_ad_objectClass;
183         af.f_av_value = bv_alias;
184         af.f_next = NULL;
185
186         /* Find all aliases in database */
187         BDB_IDL_ZERO( aliases );
188         rs->sr_err = bdb_filter_candidates( op, &af, aliases,
189                 curscop, visited );
190         if (rs->sr_err != LDAP_SUCCESS) {
191                 return rs->sr_err;
192         }
193         oldsubs[0] = 1;
194         oldsubs[1] = e->e_id;
195
196         BDB_IDL_ZERO( ids );
197         BDB_IDL_ZERO( visited );
198         BDB_IDL_ZERO( newsubs );
199
200         cursoro = 0;
201         ido = bdb_idl_first( oldsubs, &cursoro );
202
203         for (;;) {
204                 /* Set curscop to only the aliases in the current scope. Start with
205                  * all the aliases, obtain the IDL for the current scope, and then
206                  * get the intersection of these two IDLs. Add the current scope
207                  * to the cumulative list of candidates.
208                  */
209                 BDB_IDL_CPY( curscop, aliases );
210                 rs->sr_err = bdb_dn2idl( op, e, subscop,
211                         subscop2+BDB_IDL_DB_SIZE );
212                 if (first) {
213                         first = 0;
214                 } else {
215                         bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache, e, &locka);
216                 }
217                 BDB_IDL_CPY(subscop2, subscop);
218                 rs->sr_err = bdb_idl_intersection(curscop, subscop);
219                 bdb_idl_union( ids, subscop2 );
220
221                 /* Dereference all of the aliases in the current scope. */
222                 cursora = 0;
223                 for (ida = bdb_idl_first(curscop, &cursora); ida != NOID;
224                         ida = bdb_idl_next(curscop, &cursora))
225                 {
226                         ei = NULL;
227 retry1:
228                         rs->sr_err = bdb_cache_find_id(op, NULL,
229                                 ida, &ei, 0, locker, &lockr );
230                         if (rs->sr_err != LDAP_SUCCESS) {
231                                 if ( rs->sr_err == DB_LOCK_DEADLOCK ||
232                                         rs->sr_err == DB_LOCK_NOTGRANTED ) goto retry1;
233                                 continue;
234                         }
235                         a = ei->bei_e;
236
237                         /* This should only happen if the curscop IDL has maxed out and
238                          * turned into a range that spans IDs indiscriminately
239                          */
240                         if (!is_entry_alias(a)) {
241                                 bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache,
242                                         a, &lockr);
243                                 continue;
244                         }
245
246                         /* Actually dereference the alias */
247                         BDB_IDL_ZERO(tmp);
248                         a = deref_base( op, rs, a, &matched, locker, &lockr,
249                                 tmp, visited );
250                         if (a) {
251                                 /* If the target was not already in our current candidates,
252                                  * make note of it in the newsubs list. Also
253                                  * set it in the scopes list so that bdb_search
254                                  * can check it.
255                                  */
256                                 if (bdb_idl_insert(ids, a->e_id) == 0) {
257                                         bdb_idl_insert(newsubs, a->e_id);
258                                         bdb_idl_insert(scopes, a->e_id);
259                                 }
260                                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
261                                         a, &lockr);
262
263                         } else if (matched) {
264                                 /* Alias could not be dereferenced, or it deref'd to
265                                  * an ID we've already seen. Ignore it.
266                                  */
267                                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache,
268                                         matched, &lockr );
269                                 rs->sr_text = NULL;
270                         }
271                 }
272                 /* If this is a OneLevel search, we're done; oldsubs only had one
273                  * ID in it. For a Subtree search, oldsubs may be a list of scope IDs.
274                  */
275                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) break;
276 nextido:
277                 ido = bdb_idl_next( oldsubs, &cursoro );
278                 
279                 /* If we're done processing the old scopes, did we add any new
280                  * scopes in this iteration? If so, go back and do those now.
281                  */
282                 if (ido == NOID) {
283                         if (BDB_IDL_IS_ZERO(newsubs)) break;
284                         BDB_IDL_CPY(oldsubs, newsubs);
285                         BDB_IDL_ZERO(newsubs);
286                         cursoro = 0;
287                         ido = bdb_idl_first( oldsubs, &cursoro );
288                 }
289
290                 /* Find the entry corresponding to the next scope. If it can't
291                  * be found, ignore it and move on. This should never happen;
292                  * we should never see the ID of an entry that doesn't exist.
293                  * Set the name so that the scope's IDL can be retrieved.
294                  */
295                 ei = NULL;
296 sameido:
297                 rs->sr_err = bdb_cache_find_id(op, NULL, ido, &ei,
298                         0, locker, &locka );
299                 if ( rs->sr_err != LDAP_SUCCESS ) {
300                         if ( rs->sr_err == DB_LOCK_DEADLOCK ||
301                                 rs->sr_err == DB_LOCK_NOTGRANTED )
302                                 goto sameido;
303                         goto nextido;
304                 }
305                 e = ei->bei_e;
306         }
307         return rs->sr_err;
308 }
309
310 int
311 bdb_search( Operation *op, SlapReply *rs )
312 {
313         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
314         time_t          stoptime;
315         ID              id, cursor;
316         ID              candidates[BDB_IDL_UM_SIZE];
317         ID              scopes[BDB_IDL_DB_SIZE];
318         Entry           *e = NULL, base, e_root = {0};
319         Entry           *matched = NULL;
320         EntryInfo       *ei, ei_root = {0};
321         struct berval   realbase = BER_BVNULL;
322 #ifdef SLAP_ACL_HONOR_DISCLOSE
323         slap_mask_t     mask;
324 #endif
325         int             manageDSAit;
326         int             tentries = 0;
327         ID              lastid = NOID;
328         AttributeName   *attrs;
329
330         u_int32_t       locker = 0;
331         DB_LOCK         lock;
332         struct  bdb_op_info     *opinfo = NULL;
333         DB_TXN                  *ltid = NULL;
334
335         Debug( LDAP_DEBUG_TRACE, "=> " LDAP_XSTRING(bdb_search) "\n", 0, 0, 0);
336         attrs = op->oq_search.rs_attrs;
337
338         opinfo = (struct bdb_op_info *) op->o_private;
339
340         manageDSAit = get_manageDSAit( op );
341
342         if ( opinfo && opinfo->boi_txn ) {
343                 ltid = opinfo->boi_txn;
344                 locker = TXN_ID( ltid );
345         } else {
346                 rs->sr_err = LOCK_ID( bdb->bi_dbenv, &locker );
347
348                 switch(rs->sr_err) {
349                 case 0:
350                         break;
351                 default:
352                         send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
353                         return rs->sr_err;
354                 }
355         }
356
357         if ( op->o_req_ndn.bv_len == 0 ) {
358                 /* DIT root special case */
359                 ei_root.bei_e = &e_root;
360                 ei_root.bei_parent = &ei_root;
361                 e_root.e_private = &ei_root;
362                 e_root.e_id = 0;
363                 e_root.e_ocflags = SLAP_OC_GLUE | SLAP_OC__END;
364                 BER_BVSTR( &e_root.e_nname, "" );
365                 BER_BVSTR( &e_root.e_name, "" );
366                 ei = &ei_root;
367                 rs->sr_err = LDAP_SUCCESS;
368         } else {
369                 if ( op->ors_deref & LDAP_DEREF_FINDING ) {
370                         BDB_IDL_ZERO(candidates);
371                 }
372 dn2entry_retry:
373                 /* get entry with reader lock */
374                 rs->sr_err = bdb_dn2entry( op, ltid, &op->o_req_ndn, &ei,
375                         1, locker, &lock );
376         }
377
378         switch(rs->sr_err) {
379         case DB_NOTFOUND:
380                 matched = ei->bei_e;
381                 break;
382         case 0:
383                 e = ei->bei_e;
384                 break;
385         case LDAP_BUSY:
386                 send_ldap_error( op, rs, LDAP_BUSY, "ldap server busy" );
387                 if ( !opinfo )
388                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
389                 return LDAP_BUSY;
390         case DB_LOCK_DEADLOCK:
391         case DB_LOCK_NOTGRANTED:
392                 goto dn2entry_retry;
393         default:
394                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
395                 if ( !opinfo )
396                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
397                 return rs->sr_err;
398         }
399
400         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
401                 if ( matched && is_entry_alias( matched )) {
402                         struct berval stub;
403
404                         stub.bv_val = op->o_req_ndn.bv_val;
405                         stub.bv_len = op->o_req_ndn.bv_len - matched->e_nname.bv_len - 1;
406                         e = deref_base( op, rs, matched, &matched, locker, &lock,
407                                 candidates, NULL );
408                         if ( e ) {
409                                 build_new_dn( &op->o_req_ndn, &e->e_nname, &stub,
410                                         op->o_tmpmemctx );
411                                 bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache,
412                                         e, &lock);
413                                 matched = NULL;
414                                 goto dn2entry_retry;
415                         }
416                 } else if ( e && is_entry_alias( e )) {
417                         e = deref_base( op, rs, e, &matched, locker, &lock,
418                                 candidates, NULL );
419                 }
420         }
421
422         if ( e == NULL ) {
423                 struct berval matched_dn = BER_BVNULL;
424
425                 if ( matched != NULL ) {
426                         BerVarray erefs = NULL;
427
428 #ifdef SLAP_ACL_HONOR_DISCLOSE
429                         /* return referral only if "disclose"
430                          * is granted on the object */
431                         if ( ! access_allowed( op, matched,
432                                                 slap_schema.si_ad_entry,
433                                                 NULL, ACL_DISCLOSE, NULL ) )
434                         {
435                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
436
437                         } else
438 #endif /* SLAP_ACL_HONOR_DISCLOSE */
439                         {
440                                 ber_dupbv( &matched_dn, &matched->e_name );
441
442                                 erefs = is_entry_referral( matched )
443                                         ? get_entry_referrals( op, matched )
444                                         : NULL;
445                                 if ( rs->sr_err == DB_NOTFOUND )
446                                         rs->sr_err = LDAP_REFERRAL;
447                                 rs->sr_matched = matched_dn.bv_val;
448                         }
449
450 #ifdef SLAP_ZONE_ALLOC
451                         slap_zn_runlock(bdb->bi_cache.c_zctx, matched);
452 #endif
453                         bdb_cache_return_entry_r (bdb->bi_dbenv, &bdb->bi_cache,
454                                 matched, &lock);
455                         matched = NULL;
456
457                         if ( erefs ) {
458                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
459                                         &op->o_req_dn, op->oq_search.rs_scope );
460                                 ber_bvarray_free( erefs );
461                         }
462
463                 } else {
464 #ifdef SLAP_ZONE_ALLOC
465                         slap_zn_runlock(bdb->bi_cache.c_zctx, matched);
466 #endif
467                         rs->sr_ref = referral_rewrite( default_referral,
468                                 NULL, &op->o_req_dn, op->oq_search.rs_scope );
469                         rs->sr_err = rs->sr_ref != NULL ? LDAP_REFERRAL : LDAP_NO_SUCH_OBJECT;
470                 }
471
472                 send_ldap_result( op, rs );
473
474                 if ( !opinfo )
475                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
476                 if ( rs->sr_ref ) {
477                         ber_bvarray_free( rs->sr_ref );
478                         rs->sr_ref = NULL;
479                 }
480                 if ( !BER_BVISNULL( &matched_dn ) ) {
481                         ber_memfree( matched_dn.bv_val );
482                         rs->sr_matched = NULL;
483                 }
484                 return rs->sr_err;
485         }
486
487 #ifdef SLAP_ACL_HONOR_DISCLOSE
488         /* NOTE: __NEW__ "search" access is required
489          * on searchBase object */
490         if ( ! access_allowed_mask( op, e, slap_schema.si_ad_entry,
491                                 NULL, ACL_SEARCH, NULL, &mask ) )
492         {
493                 if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
494                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
495                 } else {
496                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
497                 }
498
499 #ifdef SLAP_ZONE_ALLOC
500                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
501 #endif
502                 if ( e != &e_root ) {
503                         bdb_cache_return_entry_r(bdb->bi_dbenv, &bdb->bi_cache, e, &lock);
504                 }
505                 send_ldap_result( op, rs );
506                 return rs->sr_err;
507         }
508 #endif /* SLAP_ACL_HONOR_DISCLOSE */
509
510         if ( !manageDSAit && e != &e_root && is_entry_referral( e ) ) {
511                 /* entry is a referral, don't allow add */
512                 struct berval matched_dn = BER_BVNULL;
513                 BerVarray erefs = NULL;
514                 
515                 ber_dupbv( &matched_dn, &e->e_name );
516                 erefs = get_entry_referrals( op, e );
517
518                 rs->sr_err = LDAP_REFERRAL;
519
520 #ifdef SLAP_ZONE_ALLOC
521                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
522 #endif
523                 bdb_cache_return_entry_r( bdb->bi_dbenv, &bdb->bi_cache, e, &lock );
524                 e = NULL;
525
526                 if ( erefs ) {
527                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
528                                 &op->o_req_dn, op->oq_search.rs_scope );
529                         ber_bvarray_free( erefs );
530
531                         if ( !rs->sr_ref ) {
532                                 rs->sr_text = "bad_referral object";
533                         }
534                 }
535
536                 Debug( LDAP_DEBUG_TRACE,
537                         LDAP_XSTRING(bdb_search) ": entry is referral\n",
538                         0, 0, 0 );
539
540                 rs->sr_matched = matched_dn.bv_val;
541                 send_ldap_result( op, rs );
542
543                 if ( !opinfo ) {
544                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
545                 }
546                 ber_bvarray_free( rs->sr_ref );
547                 rs->sr_ref = NULL;
548                 ber_memfree( matched_dn.bv_val );
549                 rs->sr_matched = NULL;
550                 return 1;
551         }
552
553         if ( get_assert( op ) &&
554                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
555         {
556                 rs->sr_err = LDAP_ASSERTION_FAILED;
557 #ifdef SLAP_ZONE_ALLOC
558                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
559 #endif
560                 if ( e != &e_root ) {
561                         bdb_cache_return_entry_r(bdb->bi_dbenv, &bdb->bi_cache, e, &lock);
562                 }
563                 send_ldap_result( op, rs );
564                 return 1;
565         }
566
567         /* compute it anyway; root does not use it */
568         stoptime = op->o_time + op->ors_tlimit;
569
570         /* need normalized dn below */
571         ber_dupbv( &realbase, &e->e_nname );
572
573         /* Copy info to base, must free entry before accessing the database
574          * in search_candidates, to avoid deadlocks.
575          */
576         base.e_private = e->e_private;
577         base.e_nname = realbase;
578         base.e_id = e->e_id;
579
580 #ifdef SLAP_ZONE_ALLOC
581         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
582 #endif
583         if ( e != &e_root ) {
584                 bdb_cache_return_entry_r(bdb->bi_dbenv, &bdb->bi_cache, e, &lock);
585         }
586         e = NULL;
587
588         /* select candidates */
589         if ( op->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
590                 rs->sr_err = base_candidate( op->o_bd, &base, candidates );
591
592         } else {
593                 BDB_IDL_ZERO( candidates );
594                 BDB_IDL_ZERO( scopes );
595                 rs->sr_err = search_candidates( op, rs, &base,
596                         locker, candidates, scopes );
597         }
598
599         /* start cursor at beginning of candidates.
600          */
601         cursor = 0;
602
603         if ( candidates[0] == 0 ) {
604                 Debug( LDAP_DEBUG_TRACE,
605                         LDAP_XSTRING(bdb_search) ": no candidates\n",
606                         0, 0, 0 );
607
608                 goto nochange;
609         }
610
611         /* if not root and candidates exceed to-be-checked entries, abort */
612         if ( op->ors_limit      /* isroot == FALSE */ &&
613                 op->ors_limit->lms_s_unchecked != -1 &&
614                 BDB_IDL_N(candidates) > (unsigned) op->ors_limit->lms_s_unchecked )
615         {
616                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
617                 send_ldap_result( op, rs );
618                 rs->sr_err = LDAP_SUCCESS;
619                 goto done;
620         }
621
622         if ( op->ors_limit == NULL      /* isroot == TRUE */ ||
623                 !op->ors_limit->lms_s_pr_hide )
624         {
625                 tentries = BDB_IDL_N(candidates);
626         }
627
628         if ( get_pagedresults( op ) > SLAP_CONTROL_IGNORED ) {
629                 PagedResultsState *ps = op->o_pagedresults_state;
630                 /* deferred cookie parsing */
631                 rs->sr_err = parse_paged_cookie( op, rs );
632                 if ( rs->sr_err != LDAP_SUCCESS ) {
633                         send_ldap_result( op, rs );
634                         goto done;
635                 }
636
637                 if ( (ID)( ps->ps_cookie ) == 0 ) {
638                         id = bdb_idl_first( candidates, &cursor );
639
640                 } else {
641                         if ( ps->ps_size == 0 ) {
642                                 rs->sr_err = LDAP_SUCCESS;
643                                 rs->sr_text = "search abandoned by pagedResult size=0";
644                                 send_ldap_result( op, rs );
645                                 goto done;
646                         }
647                         for ( id = bdb_idl_first( candidates, &cursor );
648                                 id != NOID &&
649                                         id <= (ID)( ps->ps_cookie );
650                                 id = bdb_idl_next( candidates, &cursor ) )
651                         {
652                                 /* empty */;
653                         }
654                 }
655
656                 if ( cursor == NOID ) {
657                         Debug( LDAP_DEBUG_TRACE, 
658                                 LDAP_XSTRING(bdb_search)
659                                 ": no paged results candidates\n",
660                                 0, 0, 0 );
661                         send_paged_response( op, rs, &lastid, 0 );
662
663                         rs->sr_err = LDAP_OTHER;
664                         goto done;
665                 }
666                 goto loop_begin;
667         }
668
669         for ( id = bdb_idl_first( candidates, &cursor );
670                   id != NOID ; id = bdb_idl_next( candidates, &cursor ) )
671         {
672                 int scopeok;
673
674 loop_begin:
675
676                 /* check for abandon */
677                 if ( op->o_abandon ) {
678                         rs->sr_err = SLAPD_ABANDON;
679                         goto done;
680                 }
681
682                 /* check time limit */
683                 if ( op->ors_tlimit != SLAP_NO_LIMIT
684                                 && slap_get_time() > stoptime )
685                 {
686                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
687                         rs->sr_ref = rs->sr_v2ref;
688                         send_ldap_result( op, rs );
689                         rs->sr_err = LDAP_SUCCESS;
690                         goto done;
691                 }
692
693 fetch_entry_retry:
694                         /* get the entry with reader lock */
695                         ei = NULL;
696                         rs->sr_err = bdb_cache_find_id( op, ltid,
697                                 id, &ei, 0, locker, &lock );
698
699                         if (rs->sr_err == LDAP_BUSY) {
700                                 rs->sr_text = "ldap server busy";
701                                 send_ldap_result( op, rs );
702                                 goto done;
703
704                         } else if ( rs->sr_err == DB_LOCK_DEADLOCK
705                                 || rs->sr_err == DB_LOCK_NOTGRANTED )
706                         {
707                                 goto fetch_entry_retry;
708                         }
709
710                         if ( ei && rs->sr_err == LDAP_SUCCESS ) {
711                                 e = ei->bei_e;
712                         } else {
713                                 e = NULL;
714                         }
715
716                         if ( e == NULL ) {
717                                 if( !BDB_IDL_IS_RANGE(candidates) ) {
718                                         /* only complain for non-range IDLs */
719                                         Debug( LDAP_DEBUG_TRACE,
720                                                 LDAP_XSTRING(bdb_search)
721                                                 ": candidate %ld not found\n",
722                                                 (long) id, 0, 0 );
723                                 }
724
725                                 goto loop_continue;
726                         }
727
728                 rs->sr_entry = e;
729
730                 if ( is_entry_subentry( e ) ) {
731                         if( op->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
732                                 if(!get_subentries_visibility( op )) {
733                                         /* only subentries are visible */
734                                         goto loop_continue;
735                                 }
736
737                         } else if ( get_subentries( op ) &&
738                                 !get_subentries_visibility( op ))
739                         {
740                                 /* only subentries are visible */
741                                 goto loop_continue;
742                         }
743
744                 } else if ( get_subentries_visibility( op )) {
745                         /* only subentries are visible */
746                         goto loop_continue;
747                 }
748
749                 /* Does this candidate actually satisfy the search scope?
750                  *
751                  * Note that we don't lock access to the bei_parent pointer.
752                  * Since only leaf nodes can be deleted, the parent of any
753                  * node will always be a valid node. Also since we have
754                  * a Read lock on the data, it cannot be renamed out of the
755                  * scope while we are looking at it, and unless we're using
756                  * BDB_HIER, its parents cannot be moved either.
757                  */
758                 scopeok = 0;
759                 switch( op->ors_scope ) {
760                 case LDAP_SCOPE_BASE:
761                         /* This is always true, yes? */
762                         if ( id == base.e_id ) scopeok = 1;
763                         break;
764
765                 case LDAP_SCOPE_ONELEVEL:
766                         if ( ei->bei_parent->bei_id == base.e_id ) scopeok = 1;
767                         break;
768
769 #ifdef LDAP_SCOPE_CHILDREN
770                 case LDAP_SCOPE_CHILDREN:
771                         if ( id == base.e_id ) break;
772                         /* Fall-thru */
773 #endif
774                 case LDAP_SCOPE_SUBTREE: {
775                         EntryInfo *tmp;
776                         for ( tmp = BEI(e); tmp; tmp = tmp->bei_parent ) {
777                                 if ( tmp->bei_id == base.e_id ) {
778                                         scopeok = 1;
779                                         break;
780                                 }
781                         }
782                         } break;
783                 }
784
785                 /* aliases were already dereferenced in candidate list */
786                 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
787                         /* but if the search base is an alias, and we didn't
788                          * deref it when finding, return it.
789                          */
790                         if ( is_entry_alias(e) &&
791                                 ((op->ors_deref & LDAP_DEREF_FINDING) ||
792                                         !bvmatch(&e->e_nname, &op->o_req_ndn)))
793                         {
794                                 goto loop_continue;
795                         }
796
797                         /* scopes is only non-empty for onelevel or subtree */
798                         if ( !scopeok && BDB_IDL_N(scopes) ) {
799                                 unsigned x;
800                                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) {
801                                         x = bdb_idl_search( scopes, e->e_id );
802                                         if ( scopes[x] == e->e_id ) scopeok = 1;
803                                 } else {
804                                         /* subtree, walk up the tree */
805                                         EntryInfo *tmp = BEI(e);
806                                         for (;tmp->bei_parent; tmp=tmp->bei_parent) {
807                                                 x = bdb_idl_search( scopes, tmp->bei_id );
808                                                 if ( scopes[x] == tmp->bei_id ) {
809                                                         scopeok = 1;
810                                                         break;
811                                                 }
812                                         }
813                                 }
814                         }
815                 }
816
817                 /* Not in scope, ignore it */
818                 if ( !scopeok )
819                 {
820                         Debug( LDAP_DEBUG_TRACE,
821                                 LDAP_XSTRING(bdb_search)
822                                 ": %ld scope not okay\n",
823                                 (long) id, 0, 0 );
824                         goto loop_continue;
825                 }
826
827                 /*
828                  * if it's a referral, add it to the list of referrals. only do
829                  * this for non-base searches, and don't check the filter
830                  * explicitly here since it's only a candidate anyway.
831                  */
832                 if ( !manageDSAit && op->oq_search.rs_scope != LDAP_SCOPE_BASE
833                         && is_entry_referral( e ) )
834                 {
835                         struct bdb_op_info bois, *boi2;
836                         struct bdb_lock_info blis;
837                         BerVarray erefs = get_entry_referrals( op, e );
838                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
839                                 op->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
840                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
841
842                         /* Must set lockinfo so that entry_release will work */
843                         if (!opinfo) {
844                                 boi2 = &bois;
845                                 op->o_private = boi2;
846                                 bois.boi_bdb = op->o_bd;
847                                 bois.boi_txn = NULL;
848                                 bois.boi_locker = locker;
849                                 bois.boi_err = 0;
850                                 bois.boi_locks = &blis;
851                                 blis.bli_next = NULL;
852                                 bois.boi_flag = BOI_DONTFREE;
853                         } else {
854                                 boi2 = opinfo;
855                                 blis.bli_next = boi2->boi_locks;
856                                 boi2->boi_locks = &blis;
857                         }
858                         blis.bli_id = e->e_id;
859                         blis.bli_lock = lock;
860                         blis.bli_flag = BLI_DONTFREE;
861
862                         rs->sr_flags = REP_ENTRY_MUSTRELEASE;
863
864                         send_search_reference( op, rs );
865
866                         if ( blis.bli_flag ) {
867 #ifdef SLAP_ZONE_ALLOC
868                                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
869 #endif
870                                 bdb_cache_return_entry_r(bdb->bi_dbenv,
871                                         &bdb->bi_cache, e, &lock);
872                                 op->o_private = opinfo;
873                                 if ( opinfo ) {
874                                         opinfo->boi_locks = blis.bli_next;
875                                 }
876                         }
877                         rs->sr_entry = NULL;
878                         e = NULL;
879
880                         ber_bvarray_free( rs->sr_ref );
881                         ber_bvarray_free( erefs );
882                         rs->sr_ref = NULL;
883
884                         goto loop_continue;
885                 }
886
887                 if ( !manageDSAit && is_entry_glue( e )) {
888                         goto loop_continue;
889                 }
890
891                 /* if it matches the filter and scope, send it */
892                 rs->sr_err = test_filter( op, rs->sr_entry, op->oq_search.rs_filter );
893
894                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
895                         /* check size limit */
896                         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
897                                 if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
898 #ifdef SLAP_ZONE_ALLOC
899                                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
900 #endif
901                                         bdb_cache_return_entry_r( bdb->bi_dbenv,
902                                                         &bdb->bi_cache, e, &lock );
903                                         e = NULL;
904                                         send_paged_response( op, rs, &lastid, tentries );
905                                         goto done;
906                                 }
907                                 lastid = id;
908                         }
909
910                         if (e) {
911                                 struct bdb_op_info bois, *boi2;
912                                 struct bdb_lock_info blis;
913
914                                 /* Must set lockinfo so that entry_release will work */
915                                 if (!opinfo) {
916                                         boi2 = &bois;
917                                         op->o_private = boi2;
918                                         bois.boi_bdb = op->o_bd;
919                                         bois.boi_txn = NULL;
920                                         bois.boi_locker = locker;
921                                         bois.boi_err = 0;
922                                         bois.boi_locks = &blis;
923                                         blis.bli_next = NULL;
924                                         bois.boi_flag = BOI_DONTFREE;
925                                 } else {
926                                         boi2 = opinfo;
927                                         blis.bli_next = boi2->boi_locks;
928                                         boi2->boi_locks = &blis;
929                                 }
930                                 blis.bli_id = e->e_id;
931                                 blis.bli_lock = lock;
932                                 blis.bli_flag = BLI_DONTFREE;
933
934                                 /* safe default */
935                                 rs->sr_attrs = op->oq_search.rs_attrs;
936                                 rs->sr_operational_attrs = NULL;
937                                 rs->sr_ctrls = NULL;
938                                 rs->sr_flags = REP_ENTRY_MUSTRELEASE;
939                                 rs->sr_err = LDAP_SUCCESS;
940                                 rs->sr_err = send_search_entry( op, rs );
941
942                                 /* send_search_entry will usually free it.
943                                  * an overlay might leave its own copy here;
944                                  * bli_flag will be 0 if lock was already released.
945                                  */
946                                 if ( blis.bli_flag ) {
947 #ifdef SLAP_ZONE_ALLOC
948                                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
949 #endif
950                                         bdb_cache_return_entry_r(bdb->bi_dbenv,
951                                                 &bdb->bi_cache, e, &lock);
952                                         op->o_private = opinfo;
953                                         if ( opinfo ) {
954                                                 opinfo->boi_locks = blis.bli_next;
955                                         }
956                                 }
957                                 rs->sr_entry = NULL;
958                                 e = NULL;
959
960                                 switch ( rs->sr_err ) {
961                                 case LDAP_SUCCESS:      /* entry sent ok */
962                                         break;
963                                 default:                /* entry not sent */
964                                         break;
965                                 case LDAP_UNAVAILABLE:
966                                 case LDAP_SIZELIMIT_EXCEEDED:
967                                         if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
968                                                 rs->sr_ref = rs->sr_v2ref;
969                                                 send_ldap_result( op, rs );
970                                                 rs->sr_err = LDAP_SUCCESS;
971
972                                         } else {
973                                                 rs->sr_err = LDAP_OTHER;
974                                         }
975                                         goto done;
976                                 }
977                         }
978
979                 } else {
980                         Debug( LDAP_DEBUG_TRACE,
981                                 LDAP_XSTRING(bdb_search)
982                                 ": %ld does not match filter\n",
983                                 (long) id, 0, 0 );
984                 }
985
986 loop_continue:
987                 if( e != NULL ) {
988                         /* free reader lock */
989 #ifdef SLAP_ZONE_ALLOC
990                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
991 #endif
992                         bdb_cache_return_entry_r( bdb->bi_dbenv,
993                                 &bdb->bi_cache, e , &lock );
994                         e = NULL;
995                         rs->sr_entry = NULL;
996                 }
997         }
998
999 nochange:
1000         rs->sr_ctrls = NULL;
1001         rs->sr_ref = rs->sr_v2ref;
1002         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
1003         rs->sr_rspoid = NULL;
1004         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
1005                 send_paged_response( op, rs, NULL, 0 );
1006         } else {
1007                 send_ldap_result( op, rs );
1008         }
1009
1010         rs->sr_err = LDAP_SUCCESS;
1011
1012 done:
1013         if ( !opinfo )
1014                 LOCK_ID_FREE( bdb->bi_dbenv, locker );
1015
1016         if( rs->sr_v2ref ) {
1017                 ber_bvarray_free( rs->sr_v2ref );
1018                 rs->sr_v2ref = NULL;
1019         }
1020         if( realbase.bv_val ) ch_free( realbase.bv_val );
1021
1022         return rs->sr_err;
1023 }
1024
1025
1026 static int base_candidate(
1027         BackendDB       *be,
1028         Entry   *e,
1029         ID              *ids )
1030 {
1031         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
1032                 e->e_nname.bv_val, (long) e->e_id, 0);
1033
1034         ids[0] = 1;
1035         ids[1] = e->e_id;
1036         return 0;
1037 }
1038
1039 /* Look for "objectClass Present" in this filter.
1040  * Also count depth of filter tree while we're at it.
1041  */
1042 static int oc_filter(
1043         Filter *f,
1044         int cur,
1045         int *max )
1046 {
1047         int rc = 0;
1048
1049         assert( f != NULL );
1050
1051         if( cur > *max ) *max = cur;
1052
1053         switch( f->f_choice ) {
1054         case LDAP_FILTER_PRESENT:
1055                 if (f->f_desc == slap_schema.si_ad_objectClass) {
1056                         rc = 1;
1057                 }
1058                 break;
1059
1060         case LDAP_FILTER_AND:
1061         case LDAP_FILTER_OR:
1062                 cur++;
1063                 for ( f=f->f_and; f; f=f->f_next ) {
1064                         (void) oc_filter(f, cur, max);
1065                 }
1066                 break;
1067
1068         default:
1069                 break;
1070         }
1071         return rc;
1072 }
1073
1074 static void search_stack_free( void *key, void *data )
1075 {
1076         ber_memfree_x(data, NULL);
1077 }
1078
1079 static void *search_stack( Operation *op )
1080 {
1081         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1082         void *ret = NULL;
1083
1084         if ( op->o_threadctx ) {
1085                 ldap_pvt_thread_pool_getkey( op->o_threadctx, search_stack,
1086                         &ret, NULL );
1087         } else {
1088                 ret = bdb->bi_search_stack;
1089         }
1090
1091         if ( !ret ) {
1092                 ret = ch_malloc( bdb->bi_search_stack_depth * BDB_IDL_UM_SIZE
1093                         * sizeof( ID ) );
1094                 if ( op->o_threadctx ) {
1095                         ldap_pvt_thread_pool_setkey( op->o_threadctx, search_stack,
1096                                 ret, search_stack_free );
1097                 } else {
1098                         bdb->bi_search_stack = ret;
1099                 }
1100         }
1101         return ret;
1102 }
1103
1104 static int search_candidates(
1105         Operation *op,
1106         SlapReply *rs,
1107         Entry *e,
1108         u_int32_t locker,
1109         ID      *ids,
1110         ID      *scopes )
1111 {
1112         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1113         int rc, depth = 1;
1114         Filter          f, rf, xf, nf;
1115         ID              *stack;
1116 #ifdef LDAP_COMP_MATCH
1117         AttributeAssertion aa_ref = { NULL, BER_BVNULL, NULL };
1118 #else
1119         AttributeAssertion aa_ref = { NULL, BER_BVNULL };
1120 #endif
1121         Filter  sf;
1122 #ifdef LDAP_COMP_MATCH
1123         AttributeAssertion aa_subentry = { NULL, BER_BVNULL, NULL };
1124 #else
1125         AttributeAssertion aa_subentry = { NULL, BER_BVNULL };
1126 #endif
1127
1128         /*
1129          * This routine takes as input a filter (user-filter)
1130          * and rewrites it as follows:
1131          *      (&(scope=DN)[(objectClass=subentry)]
1132          *              (|[(objectClass=referral)(objectClass=alias)](user-filter))
1133          */
1134
1135         Debug(LDAP_DEBUG_TRACE,
1136                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1137                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1138
1139         xf.f_or = op->oq_search.rs_filter;
1140         xf.f_choice = LDAP_FILTER_OR;
1141         xf.f_next = NULL;
1142
1143         /* If the user's filter uses objectClass=*,
1144          * these clauses are redundant.
1145          */
1146         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
1147                 && !get_subentries_visibility(op)) {
1148                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
1149                         /* match referral objects */
1150                         struct berval bv_ref = BER_BVC( "referral" );
1151                         rf.f_choice = LDAP_FILTER_EQUALITY;
1152                         rf.f_ava = &aa_ref;
1153                         rf.f_av_desc = slap_schema.si_ad_objectClass;
1154                         rf.f_av_value = bv_ref;
1155                         rf.f_next = xf.f_or;
1156                         xf.f_or = &rf;
1157                         depth++;
1158                 }
1159         }
1160
1161         f.f_next = NULL;
1162         f.f_choice = LDAP_FILTER_AND;
1163         f.f_and = &nf;
1164         /* Dummy; we compute scope separately now */
1165         nf.f_choice = SLAPD_FILTER_COMPUTED;
1166         nf.f_result = LDAP_SUCCESS;
1167         nf.f_next = ( xf.f_or == op->oq_search.rs_filter )
1168                 ? op->oq_search.rs_filter : &xf ;
1169         /* Filter depth increased again, adding dummy clause */
1170         depth++;
1171
1172         if( get_subentries_visibility( op ) ) {
1173                 struct berval bv_subentry = BER_BVC( "subentry" );
1174                 sf.f_choice = LDAP_FILTER_EQUALITY;
1175                 sf.f_ava = &aa_subentry;
1176                 sf.f_av_desc = slap_schema.si_ad_objectClass;
1177                 sf.f_av_value = bv_subentry;
1178                 sf.f_next = nf.f_next;
1179                 nf.f_next = &sf;
1180         }
1181
1182         /* Allocate IDL stack, plus 1 more for former tmp */
1183         if ( depth+1 > bdb->bi_search_stack_depth ) {
1184                 stack = ch_malloc( (depth + 1) * BDB_IDL_UM_SIZE * sizeof( ID ) );
1185         } else {
1186                 stack = search_stack( op );
1187         }
1188
1189         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1190                 rc = search_aliases( op, rs, e, locker, ids, scopes, stack );
1191         } else {
1192                 rc = bdb_dn2idl( op, e, ids, stack );
1193         }
1194
1195         if ( rc == LDAP_SUCCESS ) {
1196                 rc = bdb_filter_candidates( op, &f, ids,
1197                         stack, stack+BDB_IDL_UM_SIZE );
1198         }
1199
1200         if ( depth+1 > bdb->bi_search_stack_depth ) {
1201                 ch_free( stack );
1202         }
1203
1204         if( rc ) {
1205                 Debug(LDAP_DEBUG_TRACE,
1206                         "bdb_search_candidates: failed (rc=%d)\n",
1207                         rc, NULL, NULL );
1208
1209         } else {
1210                 Debug(LDAP_DEBUG_TRACE,
1211                         "bdb_search_candidates: id=%ld first=%ld last=%ld\n",
1212                         (long) ids[0],
1213                         (long) BDB_IDL_FIRST(ids),
1214                         (long) BDB_IDL_LAST(ids) );
1215         }
1216
1217         return rc;
1218 }
1219
1220 static int
1221 parse_paged_cookie( Operation *op, SlapReply *rs )
1222 {
1223         LDAPControl     **c;
1224         int             rc = LDAP_SUCCESS;
1225         ber_tag_t       tag;
1226         ber_int_t       size;
1227         BerElement      *ber;
1228         struct berval   cookie = BER_BVNULL;
1229         PagedResultsState *ps = op->o_pagedresults_state;
1230
1231         /* this function must be invoked only if the pagedResults
1232          * control has been detected, parsed and partially checked
1233          * by the frontend */
1234         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
1235
1236         /* look for the appropriate ctrl structure */
1237         for ( c = op->o_ctrls; c[0] != NULL; c++ ) {
1238                 if ( strcmp( c[0]->ldctl_oid, LDAP_CONTROL_PAGEDRESULTS ) == 0 )
1239                 {
1240                         break;
1241                 }
1242         }
1243
1244         if ( c[0] == NULL ) {
1245                 rs->sr_text = "missing pagedResults control";
1246                 return LDAP_PROTOCOL_ERROR;
1247         }
1248
1249         /* Tested by frontend */
1250         assert( c[0]->ldctl_value.bv_len > 0 );
1251
1252         /* Parse the control value
1253          *      realSearchControlValue ::= SEQUENCE {
1254          *              size    INTEGER (0..maxInt),
1255          *                              -- requested page size from client
1256          *                              -- result set size estimate from server
1257          *              cookie  OCTET STRING
1258          * }
1259          */
1260         ber = ber_init( &c[0]->ldctl_value );
1261         if ( ber == NULL ) {
1262                 rs->sr_text = "internal error";
1263                 return LDAP_OTHER;
1264         }
1265
1266         tag = ber_scanf( ber, "{im}", &size, &cookie );
1267
1268         /* Tested by frontend */
1269         assert( tag != LBER_ERROR );
1270         assert( size >= 0 );
1271
1272         /* cookie decoding/checks deferred to backend... */
1273         if ( cookie.bv_len ) {
1274                 PagedResultsCookie reqcookie;
1275                 if( cookie.bv_len != sizeof( reqcookie ) ) {
1276                         /* bad cookie */
1277                         rs->sr_text = "paged results cookie is invalid";
1278                         rc = LDAP_PROTOCOL_ERROR;
1279                         goto done;
1280                 }
1281
1282                 AC_MEMCPY( &reqcookie, cookie.bv_val, sizeof( reqcookie ));
1283
1284                 if ( reqcookie > ps->ps_cookie ) {
1285                         /* bad cookie */
1286                         rs->sr_text = "paged results cookie is invalid";
1287                         rc = LDAP_PROTOCOL_ERROR;
1288                         goto done;
1289
1290                 } else if ( reqcookie < ps->ps_cookie ) {
1291                         rs->sr_text = "paged results cookie is invalid or old";
1292                         rc = LDAP_UNWILLING_TO_PERFORM;
1293                         goto done;
1294                 }
1295
1296         }
1297
1298 done:;
1299         (void)ber_free( ber, 1 );
1300
1301         return rc;
1302 }
1303
1304 static void
1305 send_paged_response( 
1306         Operation       *op,
1307         SlapReply       *rs,
1308         ID              *lastid,
1309         int             tentries )
1310 {
1311         LDAPControl     ctrl, *ctrls[2];
1312         BerElementBuffer berbuf;
1313         BerElement      *ber = (BerElement *)&berbuf;
1314         PagedResultsCookie respcookie;
1315         struct berval cookie;
1316
1317         Debug(LDAP_DEBUG_ARGS,
1318                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1319                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1320
1321         BER_BVZERO( &ctrl.ldctl_value );
1322         ctrls[0] = &ctrl;
1323         ctrls[1] = NULL;
1324
1325         ber_init2( ber, NULL, LBER_USE_DER );
1326
1327         if ( lastid ) {
1328                 respcookie = ( PagedResultsCookie )(*lastid);
1329                 cookie.bv_len = sizeof( respcookie );
1330                 cookie.bv_val = (char *)&respcookie;
1331
1332         } else {
1333                 respcookie = ( PagedResultsCookie )0;
1334                 BER_BVSTR( &cookie, "" );
1335         }
1336
1337         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1338         op->o_conn->c_pagedresults_state.ps_count =
1339                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
1340                 rs->sr_nentries;
1341
1342         /* return size of 0 -- no estimate */
1343         ber_printf( ber, "{iO}", 0, &cookie ); 
1344
1345         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1346                 goto done;
1347         }
1348
1349         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1350         ctrls[0]->ldctl_iscritical = 0;
1351
1352         rs->sr_ctrls = ctrls;
1353         rs->sr_err = LDAP_SUCCESS;
1354         send_ldap_result( op, rs );
1355         rs->sr_ctrls = NULL;
1356
1357 done:
1358         (void) ber_free_buf( ber );
1359 }
1360