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