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