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