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