]> git.sur5r.net Git - openldap/blob - servers/slapd/back-mdb/search.c
ITS#8036 fix regression from ITS#7904
[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, ID2 *scopes )
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
369         if ( scopes[0].mid > 1 ) {
370                 MDB_val key;
371                 int i;
372                 key.mv_size = sizeof(ID);
373                 for ( i=1; i<scopes[0].mid; i++ ) {
374                         key.mv_data = &scopes[i].mid;
375                         mdb_cursor_get( mcd, &key, &scopes[i].mval, MDB_SET );
376                 }
377         }
378
379         if ( ww->mcd ) {
380                 MDB_val key, data;
381
382                 key.mv_size = sizeof(ID);
383                 key.mv_data = &ww->key;
384                 data = ww->data;
385                 rc = mdb_cursor_get( mcd, &key, &data, MDB_GET_BOTH );
386                 if ( rc == MDB_NOTFOUND ) {
387                         data = ww->data;
388                         rc = mdb_cursor_get( mcd, &key, &data, MDB_GET_BOTH_RANGE );
389                         /* the loop will skip this node using NEXT_DUP but we want it
390                          * sent, so go back one space first
391                          */
392                         if ( rc == MDB_SUCCESS )
393                                 mdb_cursor_get( mcd, &key, &data, MDB_PREV_DUP );
394                         else
395                                 rc = LDAP_BUSY;
396                 } else if ( rc ) {
397                         rc = LDAP_OTHER;
398                 }
399                 op->o_tmpfree( ww->data.mv_data, op->o_tmpmemctx );
400                 ww->data.mv_data = NULL;
401         }
402         return rc;
403 }
404
405 int
406 mdb_search( Operation *op, SlapReply *rs )
407 {
408         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
409         ID              id, cursor, nsubs, ncand, cscope;
410         ID              lastid = NOID;
411         ID              candidates[MDB_IDL_UM_SIZE];
412         ID              iscopes[MDB_IDL_DB_SIZE];
413         ID2             *scopes;
414         void    *stack;
415         Entry           *e = NULL, *base = NULL;
416         Entry           *matched = NULL;
417         AttributeName   *attrs;
418         slap_mask_t     mask;
419         time_t          stoptime;
420         int             manageDSAit;
421         int             tentries = 0;
422         IdScopes        isc;
423         MDB_cursor      *mci, *mcd;
424         ww_ctx wwctx;
425         slap_callback cb = { 0 };
426
427         mdb_op_info     opinfo = {{{0}}}, *moi = &opinfo;
428         MDB_txn                 *ltid = NULL;
429
430         Debug( LDAP_DEBUG_TRACE, "=> " LDAP_XSTRING(mdb_search) "\n", 0, 0, 0);
431         attrs = op->oq_search.rs_attrs;
432
433         manageDSAit = get_manageDSAit( op );
434
435         rs->sr_err = mdb_opinfo_get( op, mdb, 1, &moi );
436         switch(rs->sr_err) {
437         case 0:
438                 break;
439         default:
440                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
441                 return rs->sr_err;
442         }
443
444         ltid = moi->moi_txn;
445
446         rs->sr_err = mdb_cursor_open( ltid, mdb->mi_id2entry, &mci );
447         if ( rs->sr_err ) {
448                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
449                 return rs->sr_err;
450         }
451
452         rs->sr_err = mdb_cursor_open( ltid, mdb->mi_dn2id, &mcd );
453         if ( rs->sr_err ) {
454                 mdb_cursor_close( mci );
455                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
456                 return rs->sr_err;
457         }
458
459         scopes = scope_chunk_get( op );
460         stack = search_stack( op );
461         isc.mt = ltid;
462         isc.mc = mcd;
463         isc.scopes = scopes;
464         isc.oscope = op->ors_scope;
465         isc.sctmp = stack;
466
467         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
468                 MDB_IDL_ZERO(candidates);
469         }
470 dn2entry_retry:
471         /* get entry with reader lock */
472         rs->sr_err = mdb_dn2entry( op, ltid, mcd, &op->o_req_ndn, &e, &nsubs, 1 );
473
474         switch(rs->sr_err) {
475         case MDB_NOTFOUND:
476                 matched = e;
477                 e = NULL;
478                 break;
479         case 0:
480                 break;
481         case LDAP_BUSY:
482                 send_ldap_error( op, rs, LDAP_BUSY, "ldap server busy" );
483                 goto done;
484         default:
485                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
486                 goto done;
487         }
488
489         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
490                 if ( matched && is_entry_alias( matched )) {
491                         struct berval stub;
492
493                         stub.bv_val = op->o_req_ndn.bv_val;
494                         stub.bv_len = op->o_req_ndn.bv_len - matched->e_nname.bv_len - 1;
495                         e = deref_base( op, rs, matched, &matched, ltid,
496                                 candidates, NULL );
497                         if ( e ) {
498                                 build_new_dn( &op->o_req_ndn, &e->e_nname, &stub,
499                                         op->o_tmpmemctx );
500                                 mdb_entry_return(op, e);
501                                 matched = NULL;
502                                 goto dn2entry_retry;
503                         }
504                 } else if ( e && is_entry_alias( e )) {
505                         e = deref_base( op, rs, e, &matched, ltid,
506                                 candidates, NULL );
507                 }
508         }
509
510         if ( e == NULL ) {
511                 struct berval matched_dn = BER_BVNULL;
512
513                 if ( matched != NULL ) {
514                         BerVarray erefs = NULL;
515
516                         /* return referral only if "disclose"
517                          * is granted on the object */
518                         if ( ! access_allowed( op, matched,
519                                                 slap_schema.si_ad_entry,
520                                                 NULL, ACL_DISCLOSE, NULL ) )
521                         {
522                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
523
524                         } else {
525                                 ber_dupbv( &matched_dn, &matched->e_name );
526
527                                 erefs = is_entry_referral( matched )
528                                         ? get_entry_referrals( op, matched )
529                                         : NULL;
530                                 if ( rs->sr_err == MDB_NOTFOUND )
531                                         rs->sr_err = LDAP_REFERRAL;
532                                 rs->sr_matched = matched_dn.bv_val;
533                         }
534
535                         mdb_entry_return(op, matched);
536                         matched = NULL;
537
538                         if ( erefs ) {
539                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
540                                         &op->o_req_dn, op->oq_search.rs_scope );
541                                 ber_bvarray_free( erefs );
542                         }
543
544                 } else {
545                         rs->sr_ref = referral_rewrite( default_referral,
546                                 NULL, &op->o_req_dn, op->oq_search.rs_scope );
547                         rs->sr_err = rs->sr_ref != NULL ? LDAP_REFERRAL : LDAP_NO_SUCH_OBJECT;
548                 }
549
550                 send_ldap_result( op, rs );
551
552                 if ( rs->sr_ref ) {
553                         ber_bvarray_free( rs->sr_ref );
554                         rs->sr_ref = NULL;
555                 }
556                 if ( !BER_BVISNULL( &matched_dn ) ) {
557                         ber_memfree( matched_dn.bv_val );
558                         rs->sr_matched = NULL;
559                 }
560                 goto done;
561         }
562
563         /* NOTE: __NEW__ "search" access is required
564          * on searchBase object */
565         if ( ! access_allowed_mask( op, e, slap_schema.si_ad_entry,
566                                 NULL, ACL_SEARCH, NULL, &mask ) )
567         {
568                 if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
569                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
570                 } else {
571                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
572                 }
573
574                 mdb_entry_return( op,e);
575                 send_ldap_result( op, rs );
576                 goto done;
577         }
578
579         if ( !manageDSAit && is_entry_referral( e ) ) {
580                 /* entry is a referral */
581                 struct berval matched_dn = BER_BVNULL;
582                 BerVarray erefs = NULL;
583                 
584                 ber_dupbv( &matched_dn, &e->e_name );
585                 erefs = get_entry_referrals( op, e );
586
587                 rs->sr_err = LDAP_REFERRAL;
588
589                 mdb_entry_return( op, e );
590                 e = NULL;
591
592                 if ( erefs ) {
593                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
594                                 &op->o_req_dn, op->oq_search.rs_scope );
595                         ber_bvarray_free( erefs );
596
597                         if ( !rs->sr_ref ) {
598                                 rs->sr_text = "bad_referral object";
599                         }
600                 }
601
602                 Debug( LDAP_DEBUG_TRACE,
603                         LDAP_XSTRING(mdb_search) ": entry is referral\n",
604                         0, 0, 0 );
605
606                 rs->sr_matched = matched_dn.bv_val;
607                 send_ldap_result( op, rs );
608
609                 ber_bvarray_free( rs->sr_ref );
610                 rs->sr_ref = NULL;
611                 ber_memfree( matched_dn.bv_val );
612                 rs->sr_matched = NULL;
613                 goto done;
614         }
615
616         if ( get_assert( op ) &&
617                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
618         {
619                 rs->sr_err = LDAP_ASSERTION_FAILED;
620                 mdb_entry_return( op,e);
621                 send_ldap_result( op, rs );
622                 goto done;
623         }
624
625         /* compute it anyway; root does not use it */
626         stoptime = op->o_time + op->ors_tlimit;
627
628         base = e;
629
630         e = NULL;
631
632         /* select candidates */
633         if ( op->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
634                 rs->sr_err = base_candidate( op->o_bd, base, candidates );
635                 scopes[0].mid = 0;
636                 ncand = 1;
637         } else {
638                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) {
639                         size_t nkids;
640                         MDB_val key, data;
641                         key.mv_data = &base->e_id;
642                         key.mv_size = sizeof( ID );
643                         mdb_cursor_get( mcd, &key, &data, MDB_SET );
644                         mdb_cursor_count( mcd, &nkids );
645                         nsubs = nkids - 1;
646                 } else if ( !base->e_id ) {
647                         /* we don't maintain nsubs for entryID 0.
648                          * just grab entry count from id2entry stat
649                          */
650                         MDB_stat ms;
651                         mdb_stat( ltid, mdb->mi_id2entry, &ms );
652                         nsubs = ms.ms_entries;
653                 }
654                 MDB_IDL_ZERO( candidates );
655                 scopes[0].mid = 1;
656                 scopes[1].mid = base->e_id;
657                 scopes[1].mval.mv_data = NULL;
658                 rs->sr_err = search_candidates( op, rs, base,
659                         &isc, mci, candidates, stack );
660                 ncand = MDB_IDL_N( candidates );
661                 if ( !base->e_id || ncand == NOID ) {
662                         /* grab entry count from id2entry stat
663                          */
664                         MDB_stat ms;
665                         mdb_stat( ltid, mdb->mi_id2entry, &ms );
666                         if ( !base->e_id )
667                                 nsubs = ms.ms_entries;
668                         if ( ncand == NOID )
669                                 ncand = ms.ms_entries;
670                 }
671         }
672
673         /* start cursor at beginning of candidates.
674          */
675         cursor = 0;
676
677         if ( candidates[0] == 0 ) {
678                 Debug( LDAP_DEBUG_TRACE,
679                         LDAP_XSTRING(mdb_search) ": no candidates\n",
680                         0, 0, 0 );
681
682                 goto nochange;
683         }
684
685         /* if not root and candidates exceed to-be-checked entries, abort */
686         if ( op->ors_limit      /* isroot == FALSE */ &&
687                 op->ors_limit->lms_s_unchecked != -1 &&
688                 ncand > (unsigned) op->ors_limit->lms_s_unchecked )
689         {
690                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
691                 send_ldap_result( op, rs );
692                 rs->sr_err = LDAP_SUCCESS;
693                 goto done;
694         }
695
696         if ( op->ors_limit == NULL      /* isroot == TRUE */ ||
697                 !op->ors_limit->lms_s_pr_hide )
698         {
699                 tentries = ncand;
700         }
701
702         wwctx.flag = 0;
703         /* If we're running in our own read txn */
704         if (  moi == &opinfo ) {
705                 cb.sc_writewait = mdb_writewait;
706                 cb.sc_private = &wwctx;
707                 wwctx.txn = ltid;
708                 wwctx.mcd = NULL;
709                 cb.sc_next = op->o_callback;
710                 op->o_callback = &cb;
711         }
712
713         if ( get_pagedresults( op ) > SLAP_CONTROL_IGNORED ) {
714                 PagedResultsState *ps = op->o_pagedresults_state;
715                 /* deferred cookie parsing */
716                 rs->sr_err = parse_paged_cookie( op, rs );
717                 if ( rs->sr_err != LDAP_SUCCESS ) {
718                         send_ldap_result( op, rs );
719                         goto done;
720                 }
721
722                 cursor = (ID) ps->ps_cookie;
723                 if ( cursor && ps->ps_size == 0 ) {
724                         rs->sr_err = LDAP_SUCCESS;
725                         rs->sr_text = "search abandoned by pagedResult size=0";
726                         send_ldap_result( op, rs );
727                         goto done;
728                 }
729                 id = mdb_idl_first( candidates, &cursor );
730                 if ( id == NOID ) {
731                         Debug( LDAP_DEBUG_TRACE, 
732                                 LDAP_XSTRING(mdb_search)
733                                 ": no paged results candidates\n",
734                                 0, 0, 0 );
735                         send_paged_response( op, rs, &lastid, 0 );
736
737                         rs->sr_err = LDAP_OTHER;
738                         goto done;
739                 }
740                 if ( id == (ID)ps->ps_cookie )
741                         id = mdb_idl_next( candidates, &cursor );
742                 nsubs = ncand;  /* always bypass scope'd search */
743                 goto loop_begin;
744         }
745         if ( nsubs < ncand ) {
746                 int rc;
747                 /* Do scope-based search */
748
749                 /* if any alias scopes were set, save them */
750                 if (scopes[0].mid > 1) {
751                         cursor = 1;
752                         for (cscope = 1; cscope <= scopes[0].mid; cscope++) {
753                                 /* Ignore the original base */
754                                 if (scopes[cscope].mid == base->e_id)
755                                         continue;
756                                 iscopes[cursor++] = scopes[cscope].mid;
757                         }
758                         iscopes[0] = scopes[0].mid - 1;
759                 } else {
760                         iscopes[0] = 0;
761                 }
762
763                 wwctx.mcd = mcd;
764                 isc.id = base->e_id;
765                 isc.numrdns = 0;
766                 rc = mdb_dn2id_walk( op, &isc );
767                 if ( rc )
768                         id = NOID;
769                 else
770                         id = isc.id;
771                 cscope = 0;
772         } else {
773                 id = mdb_idl_first( candidates, &cursor );
774         }
775
776         while (id != NOID)
777         {
778                 int scopeok;
779                 MDB_val edata;
780
781 loop_begin:
782
783                 /* check for abandon */
784                 if ( op->o_abandon ) {
785                         rs->sr_err = SLAPD_ABANDON;
786                         send_ldap_result( op, rs );
787                         goto done;
788                 }
789
790                 /* mostly needed by internal searches,
791                  * e.g. related to syncrepl, for whom
792                  * abandon does not get set... */
793                 if ( slapd_shutdown ) {
794                         rs->sr_err = LDAP_UNAVAILABLE;
795                         send_ldap_disconnect( op, rs );
796                         goto done;
797                 }
798
799                 /* check time limit */
800                 if ( op->ors_tlimit != SLAP_NO_LIMIT
801                                 && slap_get_time() > stoptime )
802                 {
803                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
804                         rs->sr_ref = rs->sr_v2ref;
805                         send_ldap_result( op, rs );
806                         rs->sr_err = LDAP_SUCCESS;
807                         goto done;
808                 }
809
810
811                 if ( nsubs < ncand ) {
812                         unsigned i;
813                         /* Is this entry in the candidate list? */
814                         scopeok = 0;
815                         if (MDB_IDL_IS_RANGE( candidates )) {
816                                 if ( id >= MDB_IDL_RANGE_FIRST( candidates ) &&
817                                         id <= MDB_IDL_RANGE_LAST( candidates ))
818                                         scopeok = 1;
819                         } else {
820                                 i = mdb_idl_search( candidates, id );
821                                 if (i <= candidates[0] && candidates[i] == id )
822                                         scopeok = 1;
823                         }
824                         if ( scopeok )
825                                 goto scopeok;
826                         goto loop_continue;
827                 }
828
829                 /* Does this candidate actually satisfy the search scope?
830                  */
831                 scopeok = 0;
832                 isc.numrdns = 0;
833                 switch( op->ors_scope ) {
834                 case LDAP_SCOPE_BASE:
835                         /* This is always true, yes? */
836                         if ( id == base->e_id ) scopeok = 1;
837                         break;
838
839 #ifdef LDAP_SCOPE_CHILDREN
840                 case LDAP_SCOPE_CHILDREN:
841                         if ( id == base->e_id ) break;
842                         /* Fall-thru */
843 #endif
844                 case LDAP_SCOPE_SUBTREE:
845                         if ( id == base->e_id ) {
846                                 scopeok = 1;
847                                 break;
848                         }
849                         /* Fall-thru */
850                 case LDAP_SCOPE_ONELEVEL:
851                         if ( id == base->e_id ) break;
852                         isc.id = id;
853                         isc.nscope = 0;
854                         rs->sr_err = mdb_idscopes( op, &isc );
855                         if ( rs->sr_err == MDB_SUCCESS ) {
856                                 if ( isc.nscope )
857                                         scopeok = 1;
858                         } else {
859                                 if ( rs->sr_err == MDB_NOTFOUND )
860                                         goto notfound;
861                         }
862                         break;
863                 }
864
865                 /* Not in scope, ignore it */
866                 if ( !scopeok )
867                 {
868                         Debug( LDAP_DEBUG_TRACE,
869                                 LDAP_XSTRING(mdb_search)
870                                 ": %ld scope not okay\n",
871                                 (long) id, 0, 0 );
872                         goto loop_continue;
873                 }
874
875 scopeok:
876                 if ( id == base->e_id ) {
877                         e = base;
878                 } else {
879
880                         /* get the entry */
881                         rs->sr_err = mdb_id2edata( op, mci, id, &edata );
882                         if ( rs->sr_err == MDB_NOTFOUND ) {
883 notfound:
884                                 if( nsubs < ncand )
885                                         goto loop_continue;
886
887                                 if( !MDB_IDL_IS_RANGE(candidates) ) {
888                                         /* only complain for non-range IDLs */
889                                         Debug( LDAP_DEBUG_TRACE,
890                                                 LDAP_XSTRING(mdb_search)
891                                                 ": candidate %ld not found\n",
892                                                 (long) id, 0, 0 );
893                                 } else {
894                                         /* get the next ID from the DB */
895                                         rs->sr_err = mdb_get_nextid( mci, &cursor );
896                                         if ( rs->sr_err == MDB_NOTFOUND ) {
897                                                 break;
898                                         }
899                                         if ( rs->sr_err ) {
900                                                 rs->sr_err = LDAP_OTHER;
901                                                 rs->sr_text = "internal error in get_nextid";
902                                                 send_ldap_result( op, rs );
903                                                 goto done;
904                                         }
905                                         cursor--;
906                                 }
907
908                                 goto loop_continue;
909                         } else if ( rs->sr_err ) {
910                                 rs->sr_err = LDAP_OTHER;
911                                 rs->sr_text = "internal error in mdb_id2edata";
912                                 send_ldap_result( op, rs );
913                                 goto done;
914                         }
915
916                         rs->sr_err = mdb_entry_decode( op, ltid, &edata, &e );
917                         if ( rs->sr_err ) {
918                                 rs->sr_err = LDAP_OTHER;
919                                 rs->sr_text = "internal error in mdb_entry_decode";
920                                 send_ldap_result( op, rs );
921                                 goto done;
922                         }
923                         e->e_id = id;
924                         e->e_name.bv_val = NULL;
925                         e->e_nname.bv_val = NULL;
926                 }
927
928                 if ( is_entry_subentry( e ) ) {
929                         if( op->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
930                                 if(!get_subentries_visibility( op )) {
931                                         /* only subentries are visible */
932                                         goto loop_continue;
933                                 }
934
935                         } else if ( get_subentries( op ) &&
936                                 !get_subentries_visibility( op ))
937                         {
938                                 /* only subentries are visible */
939                                 goto loop_continue;
940                         }
941
942                 } else if ( get_subentries_visibility( op )) {
943                         /* only subentries are visible */
944                         goto loop_continue;
945                 }
946
947                 /* aliases were already dereferenced in candidate list */
948                 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
949                         /* but if the search base is an alias, and we didn't
950                          * deref it when finding, return it.
951                          */
952                         if ( is_entry_alias(e) &&
953                                 ((op->ors_deref & LDAP_DEREF_FINDING) || e != base ))
954                         {
955                                 goto loop_continue;
956                         }
957                 }
958
959                 if ( !manageDSAit && is_entry_glue( e )) {
960                         goto loop_continue;
961                 }
962
963                 if (e != base) {
964                         struct berval pdn, pndn;
965                         char *d, *n;
966                         int i;
967
968                         /* child of base, just append RDNs to base->e_name */
969                         if ( nsubs < ncand || isc.scopes[isc.nscope].mid == base->e_id ) {
970                                 pdn = base->e_name;
971                                 pndn = base->e_nname;
972                         } else {
973                                 mdb_id2name( op, ltid, &isc.mc, scopes[isc.nscope].mid, &pdn, &pndn );
974                         }
975                         e->e_name.bv_len = pdn.bv_len;
976                         e->e_nname.bv_len = pndn.bv_len;
977                         for (i=0; i<isc.numrdns; i++) {
978                                 e->e_name.bv_len += isc.rdns[i].bv_len + 1;
979                                 e->e_nname.bv_len += isc.nrdns[i].bv_len + 1;
980                         }
981                         e->e_name.bv_val = op->o_tmpalloc(e->e_name.bv_len + 1, op->o_tmpmemctx);
982                         e->e_nname.bv_val = op->o_tmpalloc(e->e_nname.bv_len + 1, op->o_tmpmemctx);
983                         d = e->e_name.bv_val;
984                         n = e->e_nname.bv_val;
985                         if (nsubs < ncand) {
986                                 /* RDNs are in top-down order */
987                                 for (i=isc.numrdns-1; i>=0; i--) {
988                                         memcpy(d, isc.rdns[i].bv_val, isc.rdns[i].bv_len);
989                                         d += isc.rdns[i].bv_len;
990                                         *d++ = ',';
991                                         memcpy(n, isc.nrdns[i].bv_val, isc.nrdns[i].bv_len);
992                                         n += isc.nrdns[i].bv_len;
993                                         *n++ = ',';
994                                 }
995                         } else {
996                                 /* RDNs are in bottom-up order */
997                                 for (i=0; i<isc.numrdns; i++) {
998                                         memcpy(d, isc.rdns[i].bv_val, isc.rdns[i].bv_len);
999                                         d += isc.rdns[i].bv_len;
1000                                         *d++ = ',';
1001                                         memcpy(n, isc.nrdns[i].bv_val, isc.nrdns[i].bv_len);
1002                                         n += isc.nrdns[i].bv_len;
1003                                         *n++ = ',';
1004                                 }
1005                         }
1006
1007                         if (pdn.bv_len) {
1008                                 memcpy(d, pdn.bv_val, pdn.bv_len+1);
1009                                 memcpy(n, pndn.bv_val, pndn.bv_len+1);
1010                         } else {
1011                                 *--d = '\0';
1012                                 *--n = '\0';
1013                                 e->e_name.bv_len--;
1014                                 e->e_nname.bv_len--;
1015                         }
1016                         if (pndn.bv_val != base->e_nname.bv_val) {
1017                                 op->o_tmpfree(pndn.bv_val, op->o_tmpmemctx);
1018                                 op->o_tmpfree(pdn.bv_val, op->o_tmpmemctx);
1019                         }
1020                 }
1021
1022                 /*
1023                  * if it's a referral, add it to the list of referrals. only do
1024                  * this for non-base searches, and don't check the filter
1025                  * explicitly here since it's only a candidate anyway.
1026                  */
1027                 if ( !manageDSAit && op->oq_search.rs_scope != LDAP_SCOPE_BASE
1028                         && is_entry_referral( e ) )
1029                 {
1030                         BerVarray erefs = get_entry_referrals( op, e );
1031                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
1032                                 op->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
1033                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
1034
1035                         rs->sr_entry = e;
1036                         rs->sr_flags = 0;
1037
1038                         send_search_reference( op, rs );
1039
1040                         if (e != base)
1041                                 mdb_entry_return( op, e );
1042                         rs->sr_entry = NULL;
1043                         e = NULL;
1044
1045                         ber_bvarray_free( rs->sr_ref );
1046                         ber_bvarray_free( erefs );
1047                         rs->sr_ref = NULL;
1048
1049                         if ( wwctx.flag ) {
1050                                 rs->sr_err = mdb_waitfixup( op, &wwctx, mci, mcd, scopes );
1051                                 if ( rs->sr_err ) {
1052                                         send_ldap_result( op, rs );
1053                                         goto done;
1054                                 }
1055                         }
1056
1057                         goto loop_continue;
1058                 }
1059
1060                 /* if it matches the filter and scope, send it */
1061                 rs->sr_err = test_filter( op, e, op->oq_search.rs_filter );
1062
1063                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
1064                         /* check size limit */
1065                         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
1066                                 if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
1067                                         mdb_entry_return( op, e );
1068                                         e = NULL;
1069                                         send_paged_response( op, rs, &lastid, tentries );
1070                                         goto done;
1071                                 }
1072                                 lastid = id;
1073                         }
1074
1075                         if (e) {
1076                                 /* safe default */
1077                                 rs->sr_attrs = op->oq_search.rs_attrs;
1078                                 rs->sr_operational_attrs = NULL;
1079                                 rs->sr_ctrls = NULL;
1080                                 rs->sr_entry = e;
1081                                 RS_ASSERT( e->e_private != NULL );
1082                                 rs->sr_flags = 0;
1083                                 rs->sr_err = LDAP_SUCCESS;
1084                                 rs->sr_err = send_search_entry( op, rs );
1085                                 rs->sr_attrs = NULL;
1086                                 rs->sr_entry = NULL;
1087                                 if (e != base)
1088                                         mdb_entry_return( op, e );
1089                                 e = NULL;
1090
1091                                 switch ( rs->sr_err ) {
1092                                 case LDAP_SUCCESS:      /* entry sent ok */
1093                                         break;
1094                                 default:                /* entry not sent */
1095                                         break;
1096                                 case LDAP_BUSY:
1097                                         send_ldap_result( op, rs );
1098                                         goto done;
1099                                 case LDAP_UNAVAILABLE:
1100                                 case LDAP_SIZELIMIT_EXCEEDED:
1101                                         if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
1102                                                 rs->sr_ref = rs->sr_v2ref;
1103                                                 send_ldap_result( op, rs );
1104                                                 rs->sr_err = LDAP_SUCCESS;
1105
1106                                         } else {
1107                                                 rs->sr_err = LDAP_OTHER;
1108                                         }
1109                                         goto done;
1110                                 }
1111                                 if ( wwctx.flag ) {
1112                                         rs->sr_err = mdb_waitfixup( op, &wwctx, mci, mcd, scopes );
1113                                         if ( rs->sr_err ) {
1114                                                 send_ldap_result( op, rs );
1115                                                 goto done;
1116                                         }
1117                                 }
1118                         }
1119
1120                 } else {
1121                         Debug( LDAP_DEBUG_TRACE,
1122                                 LDAP_XSTRING(mdb_search)
1123                                 ": %ld does not match filter\n",
1124                                 (long) id, 0, 0 );
1125                 }
1126
1127 loop_continue:
1128                 if( e != NULL ) {
1129                         if ( e != base )
1130                                 mdb_entry_return( op, e );
1131                         RS_ASSERT( rs->sr_entry == NULL );
1132                         e = NULL;
1133                         rs->sr_entry = NULL;
1134                 }
1135
1136                 if ( nsubs < ncand ) {
1137                         int rc = mdb_dn2id_walk( op, &isc );
1138                         if (rc) {
1139                                 id = NOID;
1140                                 /* We got to the end of a subtree. If there are any
1141                                  * alias scopes left, search them too.
1142                                  */
1143                                 while (iscopes[0] && cscope < iscopes[0]) {
1144                                         cscope++;
1145                                         isc.id = iscopes[cscope];
1146                                         if ( base )
1147                                                 mdb_entry_return( op, base );
1148                                         rs->sr_err = mdb_id2entry(op, mci, isc.id, &base);
1149                                         if ( !rs->sr_err ) {
1150                                                 mdb_id2name( op, ltid, &isc.mc, isc.id, &base->e_name, &base->e_nname );
1151                                                 isc.numrdns = 0;
1152                                                 if (isc.oscope == LDAP_SCOPE_ONELEVEL)
1153                                                         isc.oscope = LDAP_SCOPE_BASE;
1154                                                 rc = mdb_dn2id_walk( op, &isc );
1155                                                 if ( !rc ) {
1156                                                         id = isc.id;
1157                                                         break;
1158                                                 }
1159                                         }
1160                                 }
1161                         } else
1162                                 id = isc.id;
1163                 } else {
1164                         id = mdb_idl_next( candidates, &cursor );
1165                 }
1166         }
1167
1168 nochange:
1169         rs->sr_ctrls = NULL;
1170         rs->sr_ref = rs->sr_v2ref;
1171         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
1172         rs->sr_rspoid = NULL;
1173         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
1174                 send_paged_response( op, rs, NULL, 0 );
1175         } else {
1176                 send_ldap_result( op, rs );
1177         }
1178
1179         rs->sr_err = LDAP_SUCCESS;
1180
1181 done:
1182         if ( cb.sc_private ) {
1183                 /* remove our writewait callback */
1184                 slap_callback **scp = &op->o_callback;
1185                 while ( *scp ) {
1186                         if ( *scp == &cb ) {
1187                                 *scp = cb.sc_next;
1188                                 cb.sc_private = NULL;
1189                                 break;
1190                         }
1191                 }
1192         }
1193         mdb_cursor_close( mcd );
1194         mdb_cursor_close( mci );
1195         if ( moi == &opinfo ) {
1196                 mdb_txn_reset( moi->moi_txn );
1197                 LDAP_SLIST_REMOVE( &op->o_extra, &moi->moi_oe, OpExtra, oe_next );
1198         } else {
1199                 moi->moi_ref--;
1200         }
1201         if( rs->sr_v2ref ) {
1202                 ber_bvarray_free( rs->sr_v2ref );
1203                 rs->sr_v2ref = NULL;
1204         }
1205         if (base)
1206                 mdb_entry_return( op, base );
1207         scope_chunk_ret( op, scopes );
1208
1209         return rs->sr_err;
1210 }
1211
1212
1213 static int base_candidate(
1214         BackendDB       *be,
1215         Entry   *e,
1216         ID              *ids )
1217 {
1218         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
1219                 e->e_nname.bv_val, (long) e->e_id, 0);
1220
1221         ids[0] = 1;
1222         ids[1] = e->e_id;
1223         return 0;
1224 }
1225
1226 /* Look for "objectClass Present" in this filter.
1227  * Also count depth of filter tree while we're at it.
1228  */
1229 static int oc_filter(
1230         Filter *f,
1231         int cur,
1232         int *max )
1233 {
1234         int rc = 0;
1235
1236         assert( f != NULL );
1237
1238         if( cur > *max ) *max = cur;
1239
1240         switch( f->f_choice ) {
1241         case LDAP_FILTER_PRESENT:
1242                 if (f->f_desc == slap_schema.si_ad_objectClass) {
1243                         rc = 1;
1244                 }
1245                 break;
1246
1247         case LDAP_FILTER_AND:
1248         case LDAP_FILTER_OR:
1249                 cur++;
1250                 for ( f=f->f_and; f; f=f->f_next ) {
1251                         (void) oc_filter(f, cur, max);
1252                 }
1253                 break;
1254
1255         default:
1256                 break;
1257         }
1258         return rc;
1259 }
1260
1261 static void search_stack_free( void *key, void *data )
1262 {
1263         ber_memfree_x(data, NULL);
1264 }
1265
1266 static void *search_stack( Operation *op )
1267 {
1268         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
1269         void *ret = NULL;
1270
1271         if ( op->o_threadctx ) {
1272                 ldap_pvt_thread_pool_getkey( op->o_threadctx, (void *)search_stack,
1273                         &ret, NULL );
1274         } else {
1275                 ret = mdb->mi_search_stack;
1276         }
1277
1278         if ( !ret ) {
1279                 ret = ch_malloc( mdb->mi_search_stack_depth * MDB_IDL_UM_SIZE
1280                         * sizeof( ID ) );
1281                 if ( op->o_threadctx ) {
1282                         ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)search_stack,
1283                                 ret, search_stack_free, NULL, NULL );
1284                 } else {
1285                         mdb->mi_search_stack = ret;
1286                 }
1287         }
1288         return ret;
1289 }
1290
1291 static int search_candidates(
1292         Operation *op,
1293         SlapReply *rs,
1294         Entry *e,
1295         IdScopes *isc,
1296         MDB_cursor *mci,
1297         ID      *ids,
1298         ID *stack )
1299 {
1300         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
1301         int rc, depth = 1;
1302         Filter          *f, rf, xf, nf, sf;
1303         AttributeAssertion aa_ref = ATTRIBUTEASSERTION_INIT;
1304         AttributeAssertion aa_subentry = ATTRIBUTEASSERTION_INIT;
1305
1306         /*
1307          * This routine takes as input a filter (user-filter)
1308          * and rewrites it as follows:
1309          *      (&(scope=DN)[(objectClass=subentry)]
1310          *              (|[(objectClass=referral)](user-filter))
1311          */
1312
1313         Debug(LDAP_DEBUG_TRACE,
1314                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1315                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1316
1317         f = op->oq_search.rs_filter;
1318
1319         /* If the user's filter uses objectClass=*,
1320          * these clauses are redundant.
1321          */
1322         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
1323                 && !get_subentries_visibility(op)) {
1324                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
1325                         /* match referral objects */
1326                         struct berval bv_ref = BER_BVC( "referral" );
1327                         rf.f_choice = LDAP_FILTER_EQUALITY;
1328                         rf.f_ava = &aa_ref;
1329                         rf.f_av_desc = slap_schema.si_ad_objectClass;
1330                         rf.f_av_value = bv_ref;
1331                         rf.f_next = f;
1332                         xf.f_or = &rf;
1333                         xf.f_choice = LDAP_FILTER_OR;
1334                         xf.f_next = NULL;
1335                         f = &xf;
1336                         depth++;
1337                 }
1338         }
1339
1340         if( get_subentries_visibility( op ) ) {
1341                 struct berval bv_subentry = BER_BVC( "subentry" );
1342                 sf.f_choice = LDAP_FILTER_EQUALITY;
1343                 sf.f_ava = &aa_subentry;
1344                 sf.f_av_desc = slap_schema.si_ad_objectClass;
1345                 sf.f_av_value = bv_subentry;
1346                 sf.f_next = f;
1347                 nf.f_choice = LDAP_FILTER_AND;
1348                 nf.f_and = &sf;
1349                 nf.f_next = NULL;
1350                 f = &nf;
1351                 depth++;
1352         }
1353
1354         /* Allocate IDL stack, plus 1 more for former tmp */
1355         if ( depth+1 > mdb->mi_search_stack_depth ) {
1356                 stack = ch_malloc( (depth + 1) * MDB_IDL_UM_SIZE * sizeof( ID ) );
1357         }
1358
1359         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1360                 rc = search_aliases( op, rs, e->e_id, isc, mci, stack );
1361         } else {
1362                 rc = LDAP_SUCCESS;
1363         }
1364
1365         if ( rc == LDAP_SUCCESS ) {
1366                 rc = mdb_filter_candidates( op, isc->mt, f, ids,
1367                         stack, stack+MDB_IDL_UM_SIZE );
1368         }
1369
1370         if ( depth+1 > mdb->mi_search_stack_depth ) {
1371                 ch_free( stack );
1372         }
1373
1374         if( rc ) {
1375                 Debug(LDAP_DEBUG_TRACE,
1376                         "mdb_search_candidates: failed (rc=%d)\n",
1377                         rc, NULL, NULL );
1378
1379         } else {
1380                 Debug(LDAP_DEBUG_TRACE,
1381                         "mdb_search_candidates: id=%ld first=%ld last=%ld\n",
1382                         (long) ids[0],
1383                         (long) MDB_IDL_FIRST(ids),
1384                         (long) MDB_IDL_LAST(ids) );
1385         }
1386
1387         return rc;
1388 }
1389
1390 static int
1391 parse_paged_cookie( Operation *op, SlapReply *rs )
1392 {
1393         int             rc = LDAP_SUCCESS;
1394         PagedResultsState *ps = op->o_pagedresults_state;
1395
1396         /* this function must be invoked only if the pagedResults
1397          * control has been detected, parsed and partially checked
1398          * by the frontend */
1399         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
1400
1401         /* cookie decoding/checks deferred to backend... */
1402         if ( ps->ps_cookieval.bv_len ) {
1403                 PagedResultsCookie reqcookie;
1404                 if( ps->ps_cookieval.bv_len != sizeof( reqcookie ) ) {
1405                         /* bad cookie */
1406                         rs->sr_text = "paged results cookie is invalid";
1407                         rc = LDAP_PROTOCOL_ERROR;
1408                         goto done;
1409                 }
1410
1411                 AC_MEMCPY( &reqcookie, ps->ps_cookieval.bv_val, sizeof( reqcookie ));
1412
1413                 if ( reqcookie > ps->ps_cookie ) {
1414                         /* bad cookie */
1415                         rs->sr_text = "paged results cookie is invalid";
1416                         rc = LDAP_PROTOCOL_ERROR;
1417                         goto done;
1418
1419                 } else if ( reqcookie < ps->ps_cookie ) {
1420                         rs->sr_text = "paged results cookie is invalid or old";
1421                         rc = LDAP_UNWILLING_TO_PERFORM;
1422                         goto done;
1423                 }
1424
1425         } else {
1426                 /* we're going to use ps_cookie */
1427                 op->o_conn->c_pagedresults_state.ps_cookie = 0;
1428         }
1429
1430 done:;
1431
1432         return rc;
1433 }
1434
1435 static void
1436 send_paged_response( 
1437         Operation       *op,
1438         SlapReply       *rs,
1439         ID              *lastid,
1440         int             tentries )
1441 {
1442         LDAPControl     *ctrls[2];
1443         BerElementBuffer berbuf;
1444         BerElement      *ber = (BerElement *)&berbuf;
1445         PagedResultsCookie respcookie;
1446         struct berval cookie;
1447
1448         Debug(LDAP_DEBUG_ARGS,
1449                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1450                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1451
1452         ctrls[1] = NULL;
1453
1454         ber_init2( ber, NULL, LBER_USE_DER );
1455
1456         if ( lastid ) {
1457                 respcookie = ( PagedResultsCookie )(*lastid);
1458                 cookie.bv_len = sizeof( respcookie );
1459                 cookie.bv_val = (char *)&respcookie;
1460
1461         } else {
1462                 respcookie = ( PagedResultsCookie )0;
1463                 BER_BVSTR( &cookie, "" );
1464         }
1465
1466         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1467         op->o_conn->c_pagedresults_state.ps_count =
1468                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
1469                 rs->sr_nentries;
1470
1471         /* return size of 0 -- no estimate */
1472         ber_printf( ber, "{iO}", 0, &cookie ); 
1473
1474         ctrls[0] = op->o_tmpalloc( sizeof(LDAPControl), op->o_tmpmemctx );
1475         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1476                 goto done;
1477         }
1478
1479         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1480         ctrls[0]->ldctl_iscritical = 0;
1481
1482         slap_add_ctrls( op, rs, ctrls );
1483         rs->sr_err = LDAP_SUCCESS;
1484         send_ldap_result( op, rs );
1485
1486 done:
1487         (void) ber_free_buf( ber );
1488 }