]> git.sur5r.net Git - openldap/blob - servers/slapd/back-mdb/search.c
Revert "ITS#7702 fix results with aliases"
[openldap] / servers / slapd / back-mdb / 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-2014 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-mdb.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         MDB_txn *txn,
35         MDB_cursor *mci,
36         ID      *ids,
37         ID2L    scopes,
38         ID *stack );
39
40 static int parse_paged_cookie( Operation *op, SlapReply *rs );
41
42 static void send_paged_response( 
43         Operation *op,
44         SlapReply *rs,
45         ID  *lastid,
46         int tentries );
47
48 /* Dereference aliases for a single alias entry. Return the final
49  * dereferenced entry on success, NULL on any failure.
50  */
51 static Entry * deref_base (
52         Operation *op,
53         SlapReply *rs,
54         Entry *e,
55         Entry **matched,
56         MDB_txn *txn,
57         ID      *tmp,
58         ID      *visited )
59 {
60         struct berval ndn;
61
62         rs->sr_err = LDAP_ALIAS_DEREF_PROBLEM;
63         rs->sr_text = "maximum deref depth exceeded";
64
65         for (;;) {
66                 /* Remember the last entry we looked at, so we can
67                  * report broken links
68                  */
69                 *matched = e;
70
71                 if (MDB_IDL_N(tmp) >= op->o_bd->be_max_deref_depth) {
72                         e = NULL;
73                         break;
74                 }
75
76                 /* If this is part of a subtree or onelevel search,
77                  * have we seen this ID before? If so, quit.
78                  */
79                 if ( visited && mdb_idl_insert( visited, e->e_id ) ) {
80                         e = NULL;
81                         break;
82                 }
83
84                 /* If we've seen this ID during this deref iteration,
85                  * we've hit a loop.
86                  */
87                 if ( mdb_idl_insert( tmp, e->e_id ) ) {
88                         rs->sr_err = LDAP_ALIAS_PROBLEM;
89                         rs->sr_text = "circular alias";
90                         e = NULL;
91                         break;
92                 }
93
94                 /* If there was a problem getting the aliasedObjectName,
95                  * get_alias_dn will have set the error status.
96                  */
97                 if ( get_alias_dn(e, &ndn, &rs->sr_err, &rs->sr_text) ) {
98                         e = NULL;
99                         break;
100                 }
101
102                 rs->sr_err = mdb_dn2entry( op, txn, NULL, &ndn, &e, NULL, 0 );
103                 if (rs->sr_err) {
104                         rs->sr_err = LDAP_ALIAS_PROBLEM;
105                         rs->sr_text = "aliasedObject not found";
106                         break;
107                 }
108
109                 /* Free the previous entry, continue to work with the
110                  * one we just retrieved.
111                  */
112                 mdb_entry_return( op, *matched );
113
114                 /* We found a regular entry. Return this to the caller.
115                  */
116                 if (!is_entry_alias(e)) {
117                         rs->sr_err = LDAP_SUCCESS;
118                         rs->sr_text = NULL;
119                         break;
120                 }
121         }
122         return e;
123 }
124
125 /* Look for and dereference all aliases within the search scope.
126  * Requires "stack" to be able to hold 6 levels of DB_SIZE IDLs.
127  * Of course we're hardcoded to require a minimum of 8 UM_SIZE
128  * IDLs so this is never a problem.
129  */
130 static int search_aliases(
131         Operation *op,
132         SlapReply *rs,
133         ID e_id,
134         MDB_txn *txn,
135         MDB_cursor *mci,
136         ID2L scopes,
137         ID *stack )
138 {
139         ID *aliases, *curscop, *visited, *newsubs, *oldsubs, *tmp;
140         ID cursora, ida, cursoro, ido;
141         Entry *matched, *a;
142         struct berval bv_alias = BER_BVC( "alias" );
143         AttributeAssertion aa_alias = ATTRIBUTEASSERTION_INIT;
144         Filter  af;
145         int first = 1;
146
147         aliases = stack;        /* IDL of all aliases in the database */
148         curscop = aliases + MDB_IDL_DB_SIZE;    /* Aliases in the current scope */
149         visited = curscop + MDB_IDL_DB_SIZE;    /* IDs we've seen in this search */
150         newsubs = visited + MDB_IDL_DB_SIZE;    /* New subtrees we've added */
151         oldsubs = newsubs + MDB_IDL_DB_SIZE;    /* Subtrees added previously */
152         tmp = oldsubs + MDB_IDL_DB_SIZE;        /* Scratch space for deref_base() */
153
154         af.f_choice = LDAP_FILTER_EQUALITY;
155         af.f_ava = &aa_alias;
156         af.f_av_desc = slap_schema.si_ad_objectClass;
157         af.f_av_value = bv_alias;
158         af.f_next = NULL;
159
160         /* Find all aliases in database */
161         MDB_IDL_ZERO( aliases );
162         rs->sr_err = mdb_filter_candidates( op, txn, &af, aliases,
163                 curscop, visited );
164         if (rs->sr_err != LDAP_SUCCESS || MDB_IDL_IS_ZERO( aliases )) {
165                 return rs->sr_err;
166         }
167         oldsubs[0] = 1;
168         oldsubs[1] = e_id;
169
170         MDB_IDL_ZERO( visited );
171         MDB_IDL_ZERO( newsubs );
172
173         cursoro = 0;
174         ido = mdb_idl_first( oldsubs, &cursoro );
175
176         for (;;) {
177                 /* Set curscop to only the aliases in the current scope. Start with
178                  * all the aliases, then get the intersection with the scope.
179                  */
180                 rs->sr_err = mdb_idscope( op, txn, e_id, aliases, curscop );
181
182                 /* Dereference all of the aliases in the current scope. */
183                 cursora = 0;
184                 for (ida = mdb_idl_first(curscop, &cursora); ida != NOID;
185                         ida = mdb_idl_next(curscop, &cursora))
186                 {
187                         rs->sr_err = mdb_id2entry(op, mci, ida, &a);
188                         if (rs->sr_err != LDAP_SUCCESS) {
189                                 continue;
190                         }
191
192                         /* This should only happen if the curscop IDL has maxed out and
193                          * turned into a range that spans IDs indiscriminately
194                          */
195                         if (!is_entry_alias(a)) {
196                                 mdb_entry_return(op, a);
197                                 continue;
198                         }
199
200                         /* Actually dereference the alias */
201                         MDB_IDL_ZERO(tmp);
202                         a = deref_base( op, rs, a, &matched, txn,
203                                 tmp, visited );
204                         if (a) {
205                                 /* If the target was not already in our current scopes,
206                                  * make note of it in the newsubs list.
207                                  */
208                                 ID2 mid;
209                                 mid.mid = a->e_id;
210                                 mid.mval.mv_data = NULL;
211                                 if (mdb_id2l_insert(scopes, &mid) == 0) {
212                                         mdb_idl_insert(newsubs, a->e_id);
213                                 }
214                                 mdb_entry_return( op, a );
215
216                         } else if (matched) {
217                                 /* Alias could not be dereferenced, or it deref'd to
218                                  * an ID we've already seen. Ignore it.
219                                  */
220                                 mdb_entry_return( op, matched );
221                                 rs->sr_text = NULL;
222                                 rs->sr_err = 0;
223                         }
224                 }
225                 /* If this is a OneLevel search, we're done; oldsubs only had one
226                  * ID in it. For a Subtree search, oldsubs may be a list of scope IDs.
227                  */
228                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) break;
229 nextido:
230                 ido = mdb_idl_next( oldsubs, &cursoro );
231                 
232                 /* If we're done processing the old scopes, did we add any new
233                  * scopes in this iteration? If so, go back and do those now.
234                  */
235                 if (ido == NOID) {
236                         if (MDB_IDL_IS_ZERO(newsubs)) break;
237                         MDB_IDL_CPY(oldsubs, newsubs);
238                         MDB_IDL_ZERO(newsubs);
239                         cursoro = 0;
240                         ido = mdb_idl_first( oldsubs, &cursoro );
241                 }
242
243                 /* Find the entry corresponding to the next scope. If it can't
244                  * be found, ignore it and move on. This should never happen;
245                  * we should never see the ID of an entry that doesn't exist.
246                  */
247                 {
248                         MDB_val edata;
249                         rs->sr_err = mdb_id2edata(op, mci, ido, &edata);
250                         if ( rs->sr_err != MDB_SUCCESS ) {
251                                 goto nextido;
252                         }
253                         e_id = ido;
254                 }
255         }
256         return rs->sr_err;
257 }
258
259 /* Get the next ID from the DB. Used if the candidate list is
260  * a range and simple iteration hits missing entryIDs
261  */
262 static int
263 mdb_get_nextid(MDB_cursor *mci, ID *cursor)
264 {
265         MDB_val key;
266         ID id;
267         int rc;
268
269         id = *cursor + 1;
270         key.mv_data = &id;
271         key.mv_size = sizeof(ID);
272         rc = mdb_cursor_get( mci, &key, NULL, MDB_SET_RANGE );
273         if ( rc )
274                 return rc;
275         memcpy( cursor, key.mv_data, sizeof(ID));
276         return 0;
277 }
278
279 static void scope_chunk_free( void *key, void *data )
280 {
281         ID2 *p1, *p2;
282         for (p1 = data; p1; p1 = p2) {
283                 p2 = p1[0].mval.mv_data;
284                 ber_memfree_x(p1, NULL);
285         }
286 }
287
288 static ID2 *scope_chunk_get( Operation *op )
289 {
290         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
291         ID2 *ret = NULL;
292
293         ldap_pvt_thread_pool_getkey( op->o_threadctx, (void *)scope_chunk_get,
294                         (void *)&ret, NULL );
295         if ( !ret ) {
296                 ret = ch_malloc( MDB_IDL_UM_SIZE * sizeof( ID2 ));
297         } else {
298                 void *r2 = ret[0].mval.mv_data;
299                 ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)scope_chunk_get,
300                         r2, scope_chunk_free, NULL, NULL );
301         }
302         return ret;
303 }
304
305 static void scope_chunk_ret( Operation *op, ID2 *scopes )
306 {
307         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
308         void *ret = NULL;
309
310         ldap_pvt_thread_pool_getkey( op->o_threadctx, (void *)scope_chunk_get,
311                         &ret, NULL );
312         scopes[0].mval.mv_data = ret;
313         ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)scope_chunk_get,
314                         (void *)scopes, scope_chunk_free, NULL, NULL );
315 }
316
317 static void *search_stack( Operation *op );
318
319 typedef struct ww_ctx {
320         MDB_txn *txn;
321         MDB_cursor *mcd;        /* if set, save cursor context */
322         ID key;
323         MDB_val data;
324         int flag;
325 } ww_ctx;
326
327 /* ITS#7904 if we get blocked while writing results to client,
328  * release the current reader txn and reacquire it after we
329  * unblock.
330  * Slight problem - if we're doing a scope-based walk (mdb_dn2id_walk)
331  * to return results, we need to remember the state of the mcd cursor.
332  * If the node that cursor was pointing to gets deleted while we're
333  * blocked, we may be unable to restore the cursor position. In that
334  * case return an LDAP_BUSY error - let the client know this search
335  * couldn't succeed, but might succeed on a retry.
336  */
337 static void
338 mdb_writewait( Operation *op, slap_callback *sc )
339 {
340         ww_ctx *ww = sc->sc_private;
341         if ( !ww->flag ) {
342                 if ( ww->mcd ) {
343                         MDB_val key, data;
344                         mdb_cursor_get( ww->mcd, &key, &data, MDB_GET_CURRENT );
345                         memcpy( &ww->key, key.mv_data, sizeof(ID) );
346                         ww->data.mv_size = data.mv_size;
347                         ww->data.mv_data = op->o_tmpalloc( data.mv_size, op->o_tmpmemctx );
348                         memcpy(ww->data.mv_data, data.mv_data, data.mv_size);
349                 }
350                 mdb_txn_reset( ww->txn );
351                 ww->flag = 1;
352         }
353 }
354
355 static int
356 mdb_waitfixup( Operation *op, ww_ctx *ww, MDB_cursor *mci, MDB_cursor *mcd )
357 {
358         int rc = 0;
359         ww->flag = 0;
360         mdb_txn_renew( ww->txn );
361         mdb_cursor_renew( ww->txn, mci );
362         mdb_cursor_renew( ww->txn, mcd );
363         if ( ww->mcd ) {
364                 MDB_val key, data;
365                 key.mv_size = sizeof(ID);
366                 key.mv_data = &ww->key;
367                 data = ww->data;
368                 rc = mdb_cursor_get( mcd, &key, &data, MDB_GET_BOTH );
369                 if ( rc == MDB_NOTFOUND ) {
370                         data = ww->data;
371                         rc = mdb_cursor_get( mcd, &key, &data, MDB_GET_BOTH_RANGE );
372                         /* the loop will skip this node using NEXT_DUP but we want it
373                          * sent, so go back one space first
374                          */
375                         if ( rc == MDB_SUCCESS )
376                                 mdb_cursor_get( mcd, &key, &data, MDB_PREV_DUP );
377                         else
378                                 rc = LDAP_BUSY;
379                 } else if ( rc ) {
380                         rc = LDAP_OTHER;
381                 }
382                 op->o_tmpfree( ww->data.mv_data, op->o_tmpmemctx );
383                 ww->data.mv_data = NULL;
384         }
385         return rc;
386 }
387
388 int
389 mdb_search( Operation *op, SlapReply *rs )
390 {
391         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
392         ID              id, cursor, nsubs, ncand, cscope;
393         ID              lastid = NOID;
394         ID              candidates[MDB_IDL_UM_SIZE];
395         ID              iscopes[MDB_IDL_DB_SIZE];
396         ID2             *scopes;
397         void    *stack;
398         Entry           *e = NULL, *base = NULL;
399         Entry           *matched = NULL;
400         AttributeName   *attrs;
401         slap_mask_t     mask;
402         time_t          stoptime;
403         int             manageDSAit;
404         int             tentries = 0;
405         IdScopes        isc;
406         MDB_cursor      *mci, *mcd;
407         ww_ctx wwctx;
408         slap_callback cb = { 0 };
409
410         mdb_op_info     opinfo = {{{0}}}, *moi = &opinfo;
411         MDB_txn                 *ltid = NULL;
412
413         Debug( LDAP_DEBUG_TRACE, "=> " LDAP_XSTRING(mdb_search) "\n", 0, 0, 0);
414         attrs = op->oq_search.rs_attrs;
415
416         manageDSAit = get_manageDSAit( op );
417
418         rs->sr_err = mdb_opinfo_get( op, mdb, 1, &moi );
419         switch(rs->sr_err) {
420         case 0:
421                 break;
422         default:
423                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
424                 return rs->sr_err;
425         }
426
427         ltid = moi->moi_txn;
428
429         rs->sr_err = mdb_cursor_open( ltid, mdb->mi_id2entry, &mci );
430         if ( rs->sr_err ) {
431                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
432                 return rs->sr_err;
433         }
434
435         rs->sr_err = mdb_cursor_open( ltid, mdb->mi_dn2id, &mcd );
436         if ( rs->sr_err ) {
437                 mdb_cursor_close( mci );
438                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
439                 return rs->sr_err;
440         }
441
442         scopes = scope_chunk_get( op );
443         stack = search_stack( op );
444         isc.mt = ltid;
445         isc.mc = mcd;
446         isc.scopes = scopes;
447         isc.oscope = op->ors_scope;
448         isc.sctmp = stack;
449
450         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
451                 MDB_IDL_ZERO(candidates);
452         }
453 dn2entry_retry:
454         /* get entry with reader lock */
455         rs->sr_err = mdb_dn2entry( op, ltid, mcd, &op->o_req_ndn, &e, &nsubs, 1 );
456
457         switch(rs->sr_err) {
458         case MDB_NOTFOUND:
459                 matched = e;
460                 e = NULL;
461                 break;
462         case 0:
463                 break;
464         case LDAP_BUSY:
465                 send_ldap_error( op, rs, LDAP_BUSY, "ldap server busy" );
466                 goto done;
467         default:
468                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
469                 goto done;
470         }
471
472         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
473                 if ( matched && is_entry_alias( matched )) {
474                         struct berval stub;
475
476                         stub.bv_val = op->o_req_ndn.bv_val;
477                         stub.bv_len = op->o_req_ndn.bv_len - matched->e_nname.bv_len - 1;
478                         e = deref_base( op, rs, matched, &matched, ltid,
479                                 candidates, NULL );
480                         if ( e ) {
481                                 build_new_dn( &op->o_req_ndn, &e->e_nname, &stub,
482                                         op->o_tmpmemctx );
483                                 mdb_entry_return(op, e);
484                                 matched = NULL;
485                                 goto dn2entry_retry;
486                         }
487                 } else if ( e && is_entry_alias( e )) {
488                         e = deref_base( op, rs, e, &matched, ltid,
489                                 candidates, NULL );
490                 }
491         }
492
493         if ( e == NULL ) {
494                 struct berval matched_dn = BER_BVNULL;
495
496                 if ( matched != NULL ) {
497                         BerVarray erefs = NULL;
498
499                         /* return referral only if "disclose"
500                          * is granted on the object */
501                         if ( ! access_allowed( op, matched,
502                                                 slap_schema.si_ad_entry,
503                                                 NULL, ACL_DISCLOSE, NULL ) )
504                         {
505                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
506
507                         } else {
508                                 ber_dupbv( &matched_dn, &matched->e_name );
509
510                                 erefs = is_entry_referral( matched )
511                                         ? get_entry_referrals( op, matched )
512                                         : NULL;
513                                 if ( rs->sr_err == MDB_NOTFOUND )
514                                         rs->sr_err = LDAP_REFERRAL;
515                                 rs->sr_matched = matched_dn.bv_val;
516                         }
517
518                         mdb_entry_return(op, matched);
519                         matched = NULL;
520
521                         if ( erefs ) {
522                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
523                                         &op->o_req_dn, op->oq_search.rs_scope );
524                                 ber_bvarray_free( erefs );
525                         }
526
527                 } else {
528                         rs->sr_ref = referral_rewrite( default_referral,
529                                 NULL, &op->o_req_dn, op->oq_search.rs_scope );
530                         rs->sr_err = rs->sr_ref != NULL ? LDAP_REFERRAL : LDAP_NO_SUCH_OBJECT;
531                 }
532
533                 send_ldap_result( op, rs );
534
535                 if ( rs->sr_ref ) {
536                         ber_bvarray_free( rs->sr_ref );
537                         rs->sr_ref = NULL;
538                 }
539                 if ( !BER_BVISNULL( &matched_dn ) ) {
540                         ber_memfree( matched_dn.bv_val );
541                         rs->sr_matched = NULL;
542                 }
543                 goto done;
544         }
545
546         /* NOTE: __NEW__ "search" access is required
547          * on searchBase object */
548         if ( ! access_allowed_mask( op, e, slap_schema.si_ad_entry,
549                                 NULL, ACL_SEARCH, NULL, &mask ) )
550         {
551                 if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
552                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
553                 } else {
554                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
555                 }
556
557                 mdb_entry_return( op,e);
558                 send_ldap_result( op, rs );
559                 goto done;
560         }
561
562         if ( !manageDSAit && is_entry_referral( e ) ) {
563                 /* entry is a referral */
564                 struct berval matched_dn = BER_BVNULL;
565                 BerVarray erefs = NULL;
566                 
567                 ber_dupbv( &matched_dn, &e->e_name );
568                 erefs = get_entry_referrals( op, e );
569
570                 rs->sr_err = LDAP_REFERRAL;
571
572                 mdb_entry_return( op, e );
573                 e = NULL;
574
575                 if ( erefs ) {
576                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
577                                 &op->o_req_dn, op->oq_search.rs_scope );
578                         ber_bvarray_free( erefs );
579
580                         if ( !rs->sr_ref ) {
581                                 rs->sr_text = "bad_referral object";
582                         }
583                 }
584
585                 Debug( LDAP_DEBUG_TRACE,
586                         LDAP_XSTRING(mdb_search) ": entry is referral\n",
587                         0, 0, 0 );
588
589                 rs->sr_matched = matched_dn.bv_val;
590                 send_ldap_result( op, rs );
591
592                 ber_bvarray_free( rs->sr_ref );
593                 rs->sr_ref = NULL;
594                 ber_memfree( matched_dn.bv_val );
595                 rs->sr_matched = NULL;
596                 goto done;
597         }
598
599         if ( get_assert( op ) &&
600                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
601         {
602                 rs->sr_err = LDAP_ASSERTION_FAILED;
603                 mdb_entry_return( op,e);
604                 send_ldap_result( op, rs );
605                 goto done;
606         }
607
608         /* compute it anyway; root does not use it */
609         stoptime = op->o_time + op->ors_tlimit;
610
611         base = e;
612
613         e = NULL;
614
615         /* select candidates */
616         if ( op->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
617                 rs->sr_err = base_candidate( op->o_bd, base, candidates );
618                 scopes[0].mid = 0;
619                 ncand = 1;
620         } else {
621                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) {
622                         size_t nkids;
623                         MDB_val key, data;
624                         key.mv_data = &base->e_id;
625                         key.mv_size = sizeof( ID );
626                         mdb_cursor_get( mcd, &key, &data, MDB_SET );
627                         mdb_cursor_count( mcd, &nkids );
628                         nsubs = nkids - 1;
629                 } else if ( !base->e_id ) {
630                         /* we don't maintain nsubs for entryID 0.
631                          * just grab entry count from id2entry stat
632                          */
633                         MDB_stat ms;
634                         mdb_stat( ltid, mdb->mi_id2entry, &ms );
635                         nsubs = ms.ms_entries;
636                 }
637                 MDB_IDL_ZERO( candidates );
638                 scopes[0].mid = 1;
639                 scopes[1].mid = base->e_id;
640                 scopes[1].mval.mv_data = NULL;
641                 rs->sr_err = search_candidates( op, rs, base,
642                         ltid, mci, candidates, scopes, stack );
643                 ncand = MDB_IDL_N( candidates );
644                 if ( !base->e_id || ncand == NOID ) {
645                         /* grab entry count from id2entry stat
646                          */
647                         MDB_stat ms;
648                         mdb_stat( ltid, mdb->mi_id2entry, &ms );
649                         if ( !base->e_id )
650                                 nsubs = ms.ms_entries;
651                         if ( ncand == NOID )
652                                 ncand = ms.ms_entries;
653                 }
654         }
655
656         /* start cursor at beginning of candidates.
657          */
658         cursor = 0;
659
660         if ( candidates[0] == 0 ) {
661                 Debug( LDAP_DEBUG_TRACE,
662                         LDAP_XSTRING(mdb_search) ": no candidates\n",
663                         0, 0, 0 );
664
665                 goto nochange;
666         }
667
668         /* if not root and candidates exceed to-be-checked entries, abort */
669         if ( op->ors_limit      /* isroot == FALSE */ &&
670                 op->ors_limit->lms_s_unchecked != -1 &&
671                 ncand > (unsigned) op->ors_limit->lms_s_unchecked )
672         {
673                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
674                 send_ldap_result( op, rs );
675                 rs->sr_err = LDAP_SUCCESS;
676                 goto done;
677         }
678
679         if ( op->ors_limit == NULL      /* isroot == TRUE */ ||
680                 !op->ors_limit->lms_s_pr_hide )
681         {
682                 tentries = ncand;
683         }
684
685         wwctx.flag = 0;
686         /* If we're running in our own read txn */
687         if (  moi == &opinfo ) {
688                 cb.sc_writewait = mdb_writewait;
689                 cb.sc_private = &wwctx;
690                 wwctx.txn = ltid;
691                 wwctx.mcd = NULL;
692                 cb.sc_next = op->o_callback;
693                 op->o_callback = &cb;
694         }
695
696         if ( get_pagedresults( op ) > SLAP_CONTROL_IGNORED ) {
697                 PagedResultsState *ps = op->o_pagedresults_state;
698                 /* deferred cookie parsing */
699                 rs->sr_err = parse_paged_cookie( op, rs );
700                 if ( rs->sr_err != LDAP_SUCCESS ) {
701                         send_ldap_result( op, rs );
702                         goto done;
703                 }
704
705                 cursor = (ID) ps->ps_cookie;
706                 if ( cursor && ps->ps_size == 0 ) {
707                         rs->sr_err = LDAP_SUCCESS;
708                         rs->sr_text = "search abandoned by pagedResult size=0";
709                         send_ldap_result( op, rs );
710                         goto done;
711                 }
712                 id = mdb_idl_first( candidates, &cursor );
713                 if ( id == NOID ) {
714                         Debug( LDAP_DEBUG_TRACE, 
715                                 LDAP_XSTRING(mdb_search)
716                                 ": no paged results candidates\n",
717                                 0, 0, 0 );
718                         send_paged_response( op, rs, &lastid, 0 );
719
720                         rs->sr_err = LDAP_OTHER;
721                         goto done;
722                 }
723                 if ( id == (ID)ps->ps_cookie )
724                         id = mdb_idl_next( candidates, &cursor );
725                 nsubs = ncand;  /* always bypass scope'd search */
726                 goto loop_begin;
727         }
728         if ( nsubs < ncand ) {
729                 int rc;
730                 /* Do scope-based search */
731
732                 /* if any alias scopes were set, save them */
733                 if (scopes[0].mid > 1) {
734                         cursor = 1;
735                         for (cscope = 1; cscope <= scopes[0].mid; cscope++) {
736                                 /* Ignore the original base */
737                                 if (scopes[cscope].mid == base->e_id)
738                                         continue;
739                                 iscopes[cursor++] = scopes[cscope].mid;
740                         }
741                         iscopes[0] = scopes[0].mid - 1;
742                 } else {
743                         iscopes[0] = 0;
744                 }
745
746                 wwctx.mcd = mcd;
747                 isc.id = base->e_id;
748                 isc.numrdns = 0;
749                 rc = mdb_dn2id_walk( op, &isc );
750                 if ( rc )
751                         id = NOID;
752                 else
753                         id = isc.id;
754                 cscope = 0;
755         } else {
756                 id = mdb_idl_first( candidates, &cursor );
757         }
758
759         while (id != NOID)
760         {
761                 int scopeok;
762                 MDB_val edata;
763
764 loop_begin:
765
766                 /* check for abandon */
767                 if ( op->o_abandon ) {
768                         rs->sr_err = SLAPD_ABANDON;
769                         send_ldap_result( op, rs );
770                         goto done;
771                 }
772
773                 /* mostly needed by internal searches,
774                  * e.g. related to syncrepl, for whom
775                  * abandon does not get set... */
776                 if ( slapd_shutdown ) {
777                         rs->sr_err = LDAP_UNAVAILABLE;
778                         send_ldap_disconnect( op, rs );
779                         goto done;
780                 }
781
782                 /* check time limit */
783                 if ( op->ors_tlimit != SLAP_NO_LIMIT
784                                 && slap_get_time() > stoptime )
785                 {
786                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
787                         rs->sr_ref = rs->sr_v2ref;
788                         send_ldap_result( op, rs );
789                         rs->sr_err = LDAP_SUCCESS;
790                         goto done;
791                 }
792
793
794                 if ( nsubs < ncand ) {
795                         unsigned i;
796                         /* Is this entry in the candidate list? */
797                         scopeok = 0;
798                         if (MDB_IDL_IS_RANGE( candidates )) {
799                                 if ( id >= MDB_IDL_RANGE_FIRST( candidates ) &&
800                                         id <= MDB_IDL_RANGE_LAST( candidates ))
801                                         scopeok = 1;
802                         } else {
803                                 i = mdb_idl_search( candidates, id );
804                                 if ( candidates[i] == id )
805                                         scopeok = 1;
806                         }
807                         if ( scopeok )
808                                 goto scopeok;
809                         goto loop_continue;
810                 }
811
812                 /* Does this candidate actually satisfy the search scope?
813                  */
814                 scopeok = 0;
815                 isc.numrdns = 0;
816                 switch( op->ors_scope ) {
817                 case LDAP_SCOPE_BASE:
818                         /* This is always true, yes? */
819                         if ( id == base->e_id ) scopeok = 1;
820                         break;
821
822 #ifdef LDAP_SCOPE_CHILDREN
823                 case LDAP_SCOPE_CHILDREN:
824                         if ( id == base->e_id ) break;
825                         /* Fall-thru */
826 #endif
827                 case LDAP_SCOPE_SUBTREE:
828                         if ( id == base->e_id ) {
829                                 scopeok = 1;
830                                 break;
831                         }
832                         /* Fall-thru */
833                 case LDAP_SCOPE_ONELEVEL:
834                         isc.id = id;
835                         isc.nscope = 0;
836                         rs->sr_err = mdb_idscopes( op, &isc );
837                         if ( rs->sr_err == MDB_SUCCESS ) {
838                                 if ( isc.nscope )
839                                         scopeok = 1;
840                         } else {
841                                 if ( rs->sr_err == MDB_NOTFOUND )
842                                         goto notfound;
843                         }
844                         break;
845                 }
846
847                 /* Not in scope, ignore it */
848                 if ( !scopeok )
849                 {
850                         Debug( LDAP_DEBUG_TRACE,
851                                 LDAP_XSTRING(mdb_search)
852                                 ": %ld scope not okay\n",
853                                 (long) id, 0, 0 );
854                         goto loop_continue;
855                 }
856
857 scopeok:
858                 if ( id == base->e_id ) {
859                         e = base;
860                 } else {
861
862                         /* get the entry */
863                         rs->sr_err = mdb_id2edata( op, mci, id, &edata );
864                         if ( rs->sr_err == MDB_NOTFOUND ) {
865 notfound:
866                                 if( nsubs < ncand )
867                                         goto loop_continue;
868
869                                 if( !MDB_IDL_IS_RANGE(candidates) ) {
870                                         /* only complain for non-range IDLs */
871                                         Debug( LDAP_DEBUG_TRACE,
872                                                 LDAP_XSTRING(mdb_search)
873                                                 ": candidate %ld not found\n",
874                                                 (long) id, 0, 0 );
875                                 } else {
876                                         /* get the next ID from the DB */
877                                         rs->sr_err = mdb_get_nextid( mci, &cursor );
878                                         if ( rs->sr_err == MDB_NOTFOUND ) {
879                                                 break;
880                                         }
881                                         if ( rs->sr_err ) {
882                                                 rs->sr_err = LDAP_OTHER;
883                                                 rs->sr_text = "internal error in get_nextid";
884                                                 send_ldap_result( op, rs );
885                                                 goto done;
886                                         }
887                                         cursor--;
888                                 }
889
890                                 goto loop_continue;
891                         } else if ( rs->sr_err ) {
892                                 rs->sr_err = LDAP_OTHER;
893                                 rs->sr_text = "internal error in mdb_id2edata";
894                                 send_ldap_result( op, rs );
895                                 goto done;
896                         }
897
898                         rs->sr_err = mdb_entry_decode( op, ltid, &edata, &e );
899                         if ( rs->sr_err ) {
900                                 rs->sr_err = LDAP_OTHER;
901                                 rs->sr_text = "internal error in mdb_entry_decode";
902                                 send_ldap_result( op, rs );
903                                 goto done;
904                         }
905                         e->e_id = id;
906                         e->e_name.bv_val = NULL;
907                         e->e_nname.bv_val = NULL;
908                 }
909
910                 if ( is_entry_subentry( e ) ) {
911                         if( op->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
912                                 if(!get_subentries_visibility( op )) {
913                                         /* only subentries are visible */
914                                         goto loop_continue;
915                                 }
916
917                         } else if ( get_subentries( op ) &&
918                                 !get_subentries_visibility( op ))
919                         {
920                                 /* only subentries are visible */
921                                 goto loop_continue;
922                         }
923
924                 } else if ( get_subentries_visibility( op )) {
925                         /* only subentries are visible */
926                         goto loop_continue;
927                 }
928
929                 /* aliases were already dereferenced in candidate list */
930                 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
931                         /* but if the search base is an alias, and we didn't
932                          * deref it when finding, return it.
933                          */
934                         if ( is_entry_alias(e) &&
935                                 ((op->ors_deref & LDAP_DEREF_FINDING) || e != base ))
936                         {
937                                 goto loop_continue;
938                         }
939                 }
940
941                 if ( !manageDSAit && is_entry_glue( e )) {
942                         goto loop_continue;
943                 }
944
945                 if (e != base) {
946                         struct berval pdn, pndn;
947                         char *d, *n;
948                         int i;
949
950                         /* child of base, just append RDNs to base->e_name */
951                         if ( nsubs < ncand || isc.scopes[isc.nscope].mid == base->e_id ) {
952                                 pdn = base->e_name;
953                                 pndn = base->e_nname;
954                         } else {
955                                 mdb_id2name( op, ltid, &isc.mc, scopes[isc.nscope].mid, &pdn, &pndn );
956                         }
957                         e->e_name.bv_len = pdn.bv_len;
958                         e->e_nname.bv_len = pndn.bv_len;
959                         for (i=0; i<isc.numrdns; i++) {
960                                 e->e_name.bv_len += isc.rdns[i].bv_len + 1;
961                                 e->e_nname.bv_len += isc.nrdns[i].bv_len + 1;
962                         }
963                         e->e_name.bv_val = op->o_tmpalloc(e->e_name.bv_len + 1, op->o_tmpmemctx);
964                         e->e_nname.bv_val = op->o_tmpalloc(e->e_nname.bv_len + 1, op->o_tmpmemctx);
965                         d = e->e_name.bv_val;
966                         n = e->e_nname.bv_val;
967                         if (nsubs < ncand) {
968                                 /* RDNs are in top-down order */
969                                 for (i=isc.numrdns-1; i>=0; i--) {
970                                         memcpy(d, isc.rdns[i].bv_val, isc.rdns[i].bv_len);
971                                         d += isc.rdns[i].bv_len;
972                                         *d++ = ',';
973                                         memcpy(n, isc.nrdns[i].bv_val, isc.nrdns[i].bv_len);
974                                         n += isc.nrdns[i].bv_len;
975                                         *n++ = ',';
976                                 }
977                         } else {
978                                 /* RDNs are in bottom-up order */
979                                 for (i=0; i<isc.numrdns; i++) {
980                                         memcpy(d, isc.rdns[i].bv_val, isc.rdns[i].bv_len);
981                                         d += isc.rdns[i].bv_len;
982                                         *d++ = ',';
983                                         memcpy(n, isc.nrdns[i].bv_val, isc.nrdns[i].bv_len);
984                                         n += isc.nrdns[i].bv_len;
985                                         *n++ = ',';
986                                 }
987                         }
988
989                         if (pdn.bv_len) {
990                                 memcpy(d, pdn.bv_val, pdn.bv_len+1);
991                                 memcpy(n, pndn.bv_val, pndn.bv_len+1);
992                         } else {
993                                 *--d = '\0';
994                                 *--n = '\0';
995                                 e->e_name.bv_len--;
996                                 e->e_nname.bv_len--;
997                         }
998                         if (pndn.bv_val != base->e_nname.bv_val) {
999                                 op->o_tmpfree(pndn.bv_val, op->o_tmpmemctx);
1000                                 op->o_tmpfree(pdn.bv_val, op->o_tmpmemctx);
1001                         }
1002                 }
1003
1004                 /*
1005                  * if it's a referral, add it to the list of referrals. only do
1006                  * this for non-base searches, and don't check the filter
1007                  * explicitly here since it's only a candidate anyway.
1008                  */
1009                 if ( !manageDSAit && op->oq_search.rs_scope != LDAP_SCOPE_BASE
1010                         && is_entry_referral( e ) )
1011                 {
1012                         BerVarray erefs = get_entry_referrals( op, e );
1013                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
1014                                 op->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
1015                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
1016
1017                         rs->sr_entry = e;
1018                         rs->sr_flags = 0;
1019
1020                         send_search_reference( op, rs );
1021
1022                         if (e != base)
1023                                 mdb_entry_return( op, e );
1024                         rs->sr_entry = NULL;
1025                         e = NULL;
1026
1027                         ber_bvarray_free( rs->sr_ref );
1028                         ber_bvarray_free( erefs );
1029                         rs->sr_ref = NULL;
1030
1031                         if ( wwctx.flag ) {
1032                                 rs->sr_err = mdb_waitfixup( op, &wwctx, mci, mcd );
1033                                 if ( rs->sr_err ) {
1034                                         send_ldap_result( op, rs );
1035                                         goto done;
1036                                 }
1037                         }
1038
1039                         goto loop_continue;
1040                 }
1041
1042                 /* if it matches the filter and scope, send it */
1043                 rs->sr_err = test_filter( op, e, op->oq_search.rs_filter );
1044
1045                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
1046                         /* check size limit */
1047                         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
1048                                 if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
1049                                         mdb_entry_return( op, e );
1050                                         e = NULL;
1051                                         send_paged_response( op, rs, &lastid, tentries );
1052                                         goto done;
1053                                 }
1054                                 lastid = id;
1055                         }
1056
1057                         if (e) {
1058                                 /* safe default */
1059                                 rs->sr_attrs = op->oq_search.rs_attrs;
1060                                 rs->sr_operational_attrs = NULL;
1061                                 rs->sr_ctrls = NULL;
1062                                 rs->sr_entry = e;
1063                                 RS_ASSERT( e->e_private != NULL );
1064                                 rs->sr_flags = 0;
1065                                 rs->sr_err = LDAP_SUCCESS;
1066                                 rs->sr_err = send_search_entry( op, rs );
1067                                 rs->sr_attrs = NULL;
1068                                 rs->sr_entry = NULL;
1069                                 if (e != base)
1070                                         mdb_entry_return( op, e );
1071                                 e = NULL;
1072
1073                                 switch ( rs->sr_err ) {
1074                                 case LDAP_SUCCESS:      /* entry sent ok */
1075                                         break;
1076                                 default:                /* entry not sent */
1077                                         break;
1078                                 case LDAP_BUSY:
1079                                         send_ldap_result( op, rs );
1080                                         goto done;
1081                                 case LDAP_UNAVAILABLE:
1082                                 case LDAP_SIZELIMIT_EXCEEDED:
1083                                         if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
1084                                                 rs->sr_ref = rs->sr_v2ref;
1085                                                 send_ldap_result( op, rs );
1086                                                 rs->sr_err = LDAP_SUCCESS;
1087
1088                                         } else {
1089                                                 rs->sr_err = LDAP_OTHER;
1090                                         }
1091                                         goto done;
1092                                 }
1093                                 if ( wwctx.flag ) {
1094                                         rs->sr_err = mdb_waitfixup( op, &wwctx, mci, mcd );
1095                                         if ( rs->sr_err ) {
1096                                                 send_ldap_result( op, rs );
1097                                                 goto done;
1098                                         }
1099                                 }
1100                         }
1101
1102                 } else {
1103                         Debug( LDAP_DEBUG_TRACE,
1104                                 LDAP_XSTRING(mdb_search)
1105                                 ": %ld does not match filter\n",
1106                                 (long) id, 0, 0 );
1107                 }
1108
1109 loop_continue:
1110                 if( e != NULL ) {
1111                         if ( e != base )
1112                                 mdb_entry_return( op, e );
1113                         RS_ASSERT( rs->sr_entry == NULL );
1114                         e = NULL;
1115                         rs->sr_entry = NULL;
1116                 }
1117
1118                 if ( nsubs < ncand ) {
1119                         int rc = mdb_dn2id_walk( op, &isc );
1120                         if (rc) {
1121                                 id = NOID;
1122                                 /* We got to the end of a subtree. If there are any
1123                                  * alias scopes left, search them too.
1124                                  */
1125                                 while (iscopes[0] && cscope < iscopes[0]) {
1126                                         cscope++;
1127                                         isc.id = iscopes[cscope];
1128                                         if ( base )
1129                                                 mdb_entry_return( op, base );
1130                                         rs->sr_err = mdb_id2entry(op, mci, isc.id, &base);
1131                                         if ( !rs->sr_err ) {
1132                                                 mdb_id2name( op, ltid, &isc.mc, isc.id, &base->e_name, &base->e_nname );
1133                                                 isc.numrdns = 0;
1134                                                 if (isc.oscope == LDAP_SCOPE_ONELEVEL)
1135                                                         isc.oscope = LDAP_SCOPE_BASE;
1136                                                 rc = mdb_dn2id_walk( op, &isc );
1137                                                 if ( !rc ) {
1138                                                         id = isc.id;
1139                                                         break;
1140                                                 }
1141                                         }
1142                                 }
1143                         } else
1144                                 id = isc.id;
1145                 } else {
1146                         id = mdb_idl_next( candidates, &cursor );
1147                 }
1148         }
1149
1150 nochange:
1151         rs->sr_ctrls = NULL;
1152         rs->sr_ref = rs->sr_v2ref;
1153         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
1154         rs->sr_rspoid = NULL;
1155         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
1156                 send_paged_response( op, rs, NULL, 0 );
1157         } else {
1158                 send_ldap_result( op, rs );
1159         }
1160
1161         rs->sr_err = LDAP_SUCCESS;
1162
1163 done:
1164         if ( cb.sc_private ) {
1165                 /* remove our writewait callback */
1166                 slap_callback **scp = &op->o_callback;
1167                 while ( *scp ) {
1168                         if ( *scp == &cb ) {
1169                                 *scp = cb.sc_next;
1170                                 cb.sc_private = NULL;
1171                                 break;
1172                         }
1173                 }
1174         }
1175         mdb_cursor_close( mcd );
1176         mdb_cursor_close( mci );
1177         if ( moi == &opinfo ) {
1178                 mdb_txn_reset( moi->moi_txn );
1179                 LDAP_SLIST_REMOVE( &op->o_extra, &moi->moi_oe, OpExtra, oe_next );
1180         } else {
1181                 moi->moi_ref--;
1182         }
1183         if( rs->sr_v2ref ) {
1184                 ber_bvarray_free( rs->sr_v2ref );
1185                 rs->sr_v2ref = NULL;
1186         }
1187         if (base)
1188                 mdb_entry_return( op, base );
1189         scope_chunk_ret( op, scopes );
1190
1191         return rs->sr_err;
1192 }
1193
1194
1195 static int base_candidate(
1196         BackendDB       *be,
1197         Entry   *e,
1198         ID              *ids )
1199 {
1200         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
1201                 e->e_nname.bv_val, (long) e->e_id, 0);
1202
1203         ids[0] = 1;
1204         ids[1] = e->e_id;
1205         return 0;
1206 }
1207
1208 /* Look for "objectClass Present" in this filter.
1209  * Also count depth of filter tree while we're at it.
1210  */
1211 static int oc_filter(
1212         Filter *f,
1213         int cur,
1214         int *max )
1215 {
1216         int rc = 0;
1217
1218         assert( f != NULL );
1219
1220         if( cur > *max ) *max = cur;
1221
1222         switch( f->f_choice ) {
1223         case LDAP_FILTER_PRESENT:
1224                 if (f->f_desc == slap_schema.si_ad_objectClass) {
1225                         rc = 1;
1226                 }
1227                 break;
1228
1229         case LDAP_FILTER_AND:
1230         case LDAP_FILTER_OR:
1231                 cur++;
1232                 for ( f=f->f_and; f; f=f->f_next ) {
1233                         (void) oc_filter(f, cur, max);
1234                 }
1235                 break;
1236
1237         default:
1238                 break;
1239         }
1240         return rc;
1241 }
1242
1243 static void search_stack_free( void *key, void *data )
1244 {
1245         ber_memfree_x(data, NULL);
1246 }
1247
1248 static void *search_stack( Operation *op )
1249 {
1250         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
1251         void *ret = NULL;
1252
1253         if ( op->o_threadctx ) {
1254                 ldap_pvt_thread_pool_getkey( op->o_threadctx, (void *)search_stack,
1255                         &ret, NULL );
1256         } else {
1257                 ret = mdb->mi_search_stack;
1258         }
1259
1260         if ( !ret ) {
1261                 ret = ch_malloc( mdb->mi_search_stack_depth * MDB_IDL_UM_SIZE
1262                         * sizeof( ID ) );
1263                 if ( op->o_threadctx ) {
1264                         ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)search_stack,
1265                                 ret, search_stack_free, NULL, NULL );
1266                 } else {
1267                         mdb->mi_search_stack = ret;
1268                 }
1269         }
1270         return ret;
1271 }
1272
1273 static int search_candidates(
1274         Operation *op,
1275         SlapReply *rs,
1276         Entry *e,
1277         MDB_txn *txn,
1278         MDB_cursor *mci,
1279         ID      *ids,
1280         ID2L    scopes,
1281         ID *stack )
1282 {
1283         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
1284         int rc, depth = 1;
1285         Filter          *f, rf, xf, nf, sf;
1286         AttributeAssertion aa_ref = ATTRIBUTEASSERTION_INIT;
1287         AttributeAssertion aa_subentry = ATTRIBUTEASSERTION_INIT;
1288
1289         /*
1290          * This routine takes as input a filter (user-filter)
1291          * and rewrites it as follows:
1292          *      (&(scope=DN)[(objectClass=subentry)]
1293          *              (|[(objectClass=referral)](user-filter))
1294          */
1295
1296         Debug(LDAP_DEBUG_TRACE,
1297                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1298                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1299
1300         f = op->oq_search.rs_filter;
1301
1302         /* If the user's filter uses objectClass=*,
1303          * these clauses are redundant.
1304          */
1305         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
1306                 && !get_subentries_visibility(op)) {
1307                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
1308                         /* match referral objects */
1309                         struct berval bv_ref = BER_BVC( "referral" );
1310                         rf.f_choice = LDAP_FILTER_EQUALITY;
1311                         rf.f_ava = &aa_ref;
1312                         rf.f_av_desc = slap_schema.si_ad_objectClass;
1313                         rf.f_av_value = bv_ref;
1314                         rf.f_next = f;
1315                         xf.f_or = &rf;
1316                         xf.f_choice = LDAP_FILTER_OR;
1317                         xf.f_next = NULL;
1318                         f = &xf;
1319                         depth++;
1320                 }
1321         }
1322
1323         if( get_subentries_visibility( op ) ) {
1324                 struct berval bv_subentry = BER_BVC( "subentry" );
1325                 sf.f_choice = LDAP_FILTER_EQUALITY;
1326                 sf.f_ava = &aa_subentry;
1327                 sf.f_av_desc = slap_schema.si_ad_objectClass;
1328                 sf.f_av_value = bv_subentry;
1329                 sf.f_next = f;
1330                 nf.f_choice = LDAP_FILTER_AND;
1331                 nf.f_and = &sf;
1332                 nf.f_next = NULL;
1333                 f = &nf;
1334                 depth++;
1335         }
1336
1337         /* Allocate IDL stack, plus 1 more for former tmp */
1338         if ( depth+1 > mdb->mi_search_stack_depth ) {
1339                 stack = ch_malloc( (depth + 1) * MDB_IDL_UM_SIZE * sizeof( ID ) );
1340         }
1341
1342         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1343                 rc = search_aliases( op, rs, e->e_id, txn, mci, scopes, stack );
1344         } else {
1345                 rc = LDAP_SUCCESS;
1346         }
1347
1348         if ( rc == LDAP_SUCCESS ) {
1349                 rc = mdb_filter_candidates( op, txn, f, ids,
1350                         stack, stack+MDB_IDL_UM_SIZE );
1351         }
1352
1353         if ( depth+1 > mdb->mi_search_stack_depth ) {
1354                 ch_free( stack );
1355         }
1356
1357         if( rc ) {
1358                 Debug(LDAP_DEBUG_TRACE,
1359                         "mdb_search_candidates: failed (rc=%d)\n",
1360                         rc, NULL, NULL );
1361
1362         } else {
1363                 Debug(LDAP_DEBUG_TRACE,
1364                         "mdb_search_candidates: id=%ld first=%ld last=%ld\n",
1365                         (long) ids[0],
1366                         (long) MDB_IDL_FIRST(ids),
1367                         (long) MDB_IDL_LAST(ids) );
1368         }
1369
1370         return rc;
1371 }
1372
1373 static int
1374 parse_paged_cookie( Operation *op, SlapReply *rs )
1375 {
1376         int             rc = LDAP_SUCCESS;
1377         PagedResultsState *ps = op->o_pagedresults_state;
1378
1379         /* this function must be invoked only if the pagedResults
1380          * control has been detected, parsed and partially checked
1381          * by the frontend */
1382         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
1383
1384         /* cookie decoding/checks deferred to backend... */
1385         if ( ps->ps_cookieval.bv_len ) {
1386                 PagedResultsCookie reqcookie;
1387                 if( ps->ps_cookieval.bv_len != sizeof( reqcookie ) ) {
1388                         /* bad cookie */
1389                         rs->sr_text = "paged results cookie is invalid";
1390                         rc = LDAP_PROTOCOL_ERROR;
1391                         goto done;
1392                 }
1393
1394                 AC_MEMCPY( &reqcookie, ps->ps_cookieval.bv_val, sizeof( reqcookie ));
1395
1396                 if ( reqcookie > ps->ps_cookie ) {
1397                         /* bad cookie */
1398                         rs->sr_text = "paged results cookie is invalid";
1399                         rc = LDAP_PROTOCOL_ERROR;
1400                         goto done;
1401
1402                 } else if ( reqcookie < ps->ps_cookie ) {
1403                         rs->sr_text = "paged results cookie is invalid or old";
1404                         rc = LDAP_UNWILLING_TO_PERFORM;
1405                         goto done;
1406                 }
1407
1408         } else {
1409                 /* we're going to use ps_cookie */
1410                 op->o_conn->c_pagedresults_state.ps_cookie = 0;
1411         }
1412
1413 done:;
1414
1415         return rc;
1416 }
1417
1418 static void
1419 send_paged_response( 
1420         Operation       *op,
1421         SlapReply       *rs,
1422         ID              *lastid,
1423         int             tentries )
1424 {
1425         LDAPControl     *ctrls[2];
1426         BerElementBuffer berbuf;
1427         BerElement      *ber = (BerElement *)&berbuf;
1428         PagedResultsCookie respcookie;
1429         struct berval cookie;
1430
1431         Debug(LDAP_DEBUG_ARGS,
1432                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1433                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1434
1435         ctrls[1] = NULL;
1436
1437         ber_init2( ber, NULL, LBER_USE_DER );
1438
1439         if ( lastid ) {
1440                 respcookie = ( PagedResultsCookie )(*lastid);
1441                 cookie.bv_len = sizeof( respcookie );
1442                 cookie.bv_val = (char *)&respcookie;
1443
1444         } else {
1445                 respcookie = ( PagedResultsCookie )0;
1446                 BER_BVSTR( &cookie, "" );
1447         }
1448
1449         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1450         op->o_conn->c_pagedresults_state.ps_count =
1451                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
1452                 rs->sr_nentries;
1453
1454         /* return size of 0 -- no estimate */
1455         ber_printf( ber, "{iO}", 0, &cookie ); 
1456
1457         ctrls[0] = op->o_tmpalloc( sizeof(LDAPControl), op->o_tmpmemctx );
1458         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1459                 goto done;
1460         }
1461
1462         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1463         ctrls[0]->ldctl_iscritical = 0;
1464
1465         slap_add_ctrls( op, rs, ctrls );
1466         rs->sr_err = LDAP_SUCCESS;
1467         send_ldap_result( op, rs );
1468
1469 done:
1470         (void) ber_free_buf( ber );
1471 }