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