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