]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/search.c
fix typo
[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-2008 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         DB_TXN *txn,
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         DB_TXN *txn,
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, txn, &ndn, &ei,
105                         0, &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         DB_TXN *txn,
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         AttributeAssertion aa_alias = ATTRIBUTEASSERTION_INIT;
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, txn, &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, txn, &e->e_nname, BEI(e), subscop,
206                         subscop2+BDB_IDL_DB_SIZE );
207                 if (first) {
208                         first = 0;
209                 } else {
210                         bdb_cache_return_entry_r (bdb, 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, txn,
224                                 ida, &ei, 0, &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, a, &lockr);
237                                 continue;
238                         }
239
240                         /* Actually dereference the alias */
241                         BDB_IDL_ZERO(tmp);
242                         a = deref_base( op, rs, a, &matched, txn, &lockr,
243                                 tmp, visited );
244                         if (a) {
245                                 /* If the target was not already in our current candidates,
246                                  * make note of it in the newsubs list. Also
247                                  * set it in the scopes list so that bdb_search
248                                  * can check it.
249                                  */
250                                 if (bdb_idl_insert(ids, a->e_id) == 0) {
251                                         bdb_idl_insert(newsubs, a->e_id);
252                                         bdb_idl_insert(scopes, a->e_id);
253                                 }
254                                 bdb_cache_return_entry_r( bdb, a, &lockr);
255
256                         } else if (matched) {
257                                 /* Alias could not be dereferenced, or it deref'd to
258                                  * an ID we've already seen. Ignore it.
259                                  */
260                                 bdb_cache_return_entry_r( bdb, matched, &lockr );
261                                 rs->sr_text = NULL;
262                         }
263                 }
264                 /* If this is a OneLevel search, we're done; oldsubs only had one
265                  * ID in it. For a Subtree search, oldsubs may be a list of scope IDs.
266                  */
267                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) break;
268 nextido:
269                 ido = bdb_idl_next( oldsubs, &cursoro );
270                 
271                 /* If we're done processing the old scopes, did we add any new
272                  * scopes in this iteration? If so, go back and do those now.
273                  */
274                 if (ido == NOID) {
275                         if (BDB_IDL_IS_ZERO(newsubs)) break;
276                         BDB_IDL_CPY(oldsubs, newsubs);
277                         BDB_IDL_ZERO(newsubs);
278                         cursoro = 0;
279                         ido = bdb_idl_first( oldsubs, &cursoro );
280                 }
281
282                 /* Find the entry corresponding to the next scope. If it can't
283                  * be found, ignore it and move on. This should never happen;
284                  * we should never see the ID of an entry that doesn't exist.
285                  * Set the name so that the scope's IDL can be retrieved.
286                  */
287                 ei = NULL;
288 sameido:
289                 rs->sr_err = bdb_cache_find_id(op, txn, ido, &ei,
290                         0, &locka );
291                 if ( rs->sr_err != LDAP_SUCCESS ) {
292                         if ( rs->sr_err == DB_LOCK_DEADLOCK ||
293                                 rs->sr_err == DB_LOCK_NOTGRANTED )
294                                 goto sameido;
295                         goto nextido;
296                 }
297                 e = ei->bei_e;
298         }
299         return rs->sr_err;
300 }
301
302 int
303 bdb_search( Operation *op, SlapReply *rs )
304 {
305         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
306         ID              id, cursor;
307         ID              lastid = NOID;
308         ID              candidates[BDB_IDL_UM_SIZE];
309         ID              scopes[BDB_IDL_DB_SIZE];
310         Entry           *e = NULL, base, *e_root;
311         Entry           *matched = NULL;
312         EntryInfo       *ei;
313         AttributeName   *attrs;
314         struct berval   realbase = BER_BVNULL;
315         slap_mask_t     mask;
316         time_t          stoptime;
317         int             manageDSAit;
318         int             tentries = 0, nentries = 0;
319         int             idflag = 0;
320
321         DB_LOCK         lock;
322         struct  bdb_op_info     *opinfo = NULL;
323         DB_TXN                  *ltid = NULL;
324         OpExtra *oex;
325
326         Debug( LDAP_DEBUG_TRACE, "=> " LDAP_XSTRING(bdb_search) "\n", 0, 0, 0);
327         attrs = op->oq_search.rs_attrs;
328
329         LDAP_SLIST_FOREACH( oex, &op->o_extra, oe_next ) {
330                 if ( oex->oe_key == bdb )
331                         break;
332         }
333         opinfo = (struct bdb_op_info *) oex;
334
335         manageDSAit = get_manageDSAit( op );
336
337         if ( opinfo && opinfo->boi_txn ) {
338                 ltid = opinfo->boi_txn;
339         } else {
340                 rs->sr_err = bdb_reader_get( op, bdb->bi_dbenv, &ltid );
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         e_root = bdb->bi_cache.c_dntree.bei_e;
352         if ( op->o_req_ndn.bv_len == 0 ) {
353                 /* DIT root special case */
354                 ei = e_root->e_private;
355                 rs->sr_err = LDAP_SUCCESS;
356         } else {
357                 if ( op->ors_deref & LDAP_DEREF_FINDING ) {
358                         BDB_IDL_ZERO(candidates);
359                 }
360 dn2entry_retry:
361                 /* get entry with reader lock */
362                 rs->sr_err = bdb_dn2entry( op, ltid, &op->o_req_ndn, &ei,
363                         1, &lock );
364         }
365
366         switch(rs->sr_err) {
367         case DB_NOTFOUND:
368                 matched = ei->bei_e;
369                 break;
370         case 0:
371                 e = ei->bei_e;
372                 break;
373         case LDAP_BUSY:
374                 send_ldap_error( op, rs, LDAP_BUSY, "ldap server busy" );
375                 return LDAP_BUSY;
376         case DB_LOCK_DEADLOCK:
377         case DB_LOCK_NOTGRANTED:
378                 goto dn2entry_retry;
379         default:
380                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
381                 return rs->sr_err;
382         }
383
384         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
385                 if ( matched && is_entry_alias( matched )) {
386                         struct berval stub;
387
388                         stub.bv_val = op->o_req_ndn.bv_val;
389                         stub.bv_len = op->o_req_ndn.bv_len - matched->e_nname.bv_len - 1;
390                         e = deref_base( op, rs, matched, &matched, ltid, &lock,
391                                 candidates, NULL );
392                         if ( e ) {
393                                 build_new_dn( &op->o_req_ndn, &e->e_nname, &stub,
394                                         op->o_tmpmemctx );
395                                 bdb_cache_return_entry_r (bdb, e, &lock);
396                                 matched = NULL;
397                                 goto dn2entry_retry;
398                         }
399                 } else if ( e && is_entry_alias( e )) {
400                         e = deref_base( op, rs, e, &matched, ltid, &lock,
401                                 candidates, NULL );
402                 }
403         }
404
405         if ( e == NULL ) {
406                 struct berval matched_dn = BER_BVNULL;
407
408                 if ( matched != NULL ) {
409                         BerVarray erefs = NULL;
410
411                         /* return referral only if "disclose"
412                          * is granted on the object */
413                         if ( ! access_allowed( op, matched,
414                                                 slap_schema.si_ad_entry,
415                                                 NULL, ACL_DISCLOSE, NULL ) )
416                         {
417                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
418
419                         } else {
420                                 ber_dupbv( &matched_dn, &matched->e_name );
421
422                                 erefs = is_entry_referral( matched )
423                                         ? get_entry_referrals( op, matched )
424                                         : NULL;
425                                 if ( rs->sr_err == DB_NOTFOUND )
426                                         rs->sr_err = LDAP_REFERRAL;
427                                 rs->sr_matched = matched_dn.bv_val;
428                         }
429
430 #ifdef SLAP_ZONE_ALLOC
431                         slap_zn_runlock(bdb->bi_cache.c_zctx, matched);
432 #endif
433                         bdb_cache_return_entry_r (bdb, matched, &lock);
434                         matched = NULL;
435
436                         if ( erefs ) {
437                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
438                                         &op->o_req_dn, op->oq_search.rs_scope );
439                                 ber_bvarray_free( erefs );
440                         }
441
442                 } else {
443 #ifdef SLAP_ZONE_ALLOC
444                         slap_zn_runlock(bdb->bi_cache.c_zctx, matched);
445 #endif
446                         rs->sr_ref = referral_rewrite( default_referral,
447                                 NULL, &op->o_req_dn, op->oq_search.rs_scope );
448                         rs->sr_err = rs->sr_ref != NULL ? LDAP_REFERRAL : LDAP_NO_SUCH_OBJECT;
449                 }
450
451                 send_ldap_result( op, rs );
452
453                 if ( rs->sr_ref ) {
454                         ber_bvarray_free( rs->sr_ref );
455                         rs->sr_ref = NULL;
456                 }
457                 if ( !BER_BVISNULL( &matched_dn ) ) {
458                         ber_memfree( matched_dn.bv_val );
459                         rs->sr_matched = NULL;
460                 }
461                 return rs->sr_err;
462         }
463
464         /* NOTE: __NEW__ "search" access is required
465          * on searchBase object */
466         if ( ! access_allowed_mask( op, e, slap_schema.si_ad_entry,
467                                 NULL, ACL_SEARCH, NULL, &mask ) )
468         {
469                 if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
470                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
471                 } else {
472                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
473                 }
474
475 #ifdef SLAP_ZONE_ALLOC
476                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
477 #endif
478                 if ( e != e_root ) {
479                         bdb_cache_return_entry_r(bdb, e, &lock);
480                 }
481                 send_ldap_result( op, rs );
482                 return rs->sr_err;
483         }
484
485         if ( !manageDSAit && e != e_root && is_entry_referral( e ) ) {
486                 /* entry is a referral, don't allow add */
487                 struct berval matched_dn = BER_BVNULL;
488                 BerVarray erefs = NULL;
489                 
490                 ber_dupbv( &matched_dn, &e->e_name );
491                 erefs = get_entry_referrals( op, e );
492
493                 rs->sr_err = LDAP_REFERRAL;
494
495 #ifdef SLAP_ZONE_ALLOC
496                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
497 #endif
498                 bdb_cache_return_entry_r( bdb, e, &lock );
499                 e = NULL;
500
501                 if ( erefs ) {
502                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
503                                 &op->o_req_dn, op->oq_search.rs_scope );
504                         ber_bvarray_free( erefs );
505
506                         if ( !rs->sr_ref ) {
507                                 rs->sr_text = "bad_referral object";
508                         }
509                 }
510
511                 Debug( LDAP_DEBUG_TRACE,
512                         LDAP_XSTRING(bdb_search) ": entry is referral\n",
513                         0, 0, 0 );
514
515                 rs->sr_matched = matched_dn.bv_val;
516                 send_ldap_result( op, rs );
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, 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, 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                         ltid, 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                 cursor = (ID) ps->ps_cookie;
610                 if ( cursor && ps->ps_size == 0 ) {
611                         rs->sr_err = LDAP_SUCCESS;
612                         rs->sr_text = "search abandoned by pagedResult size=0";
613                         send_ldap_result( op, rs );
614                         goto done;
615                 }
616                 id = bdb_idl_first( candidates, &cursor );
617                 if ( id == NOID ) {
618                         Debug( LDAP_DEBUG_TRACE, 
619                                 LDAP_XSTRING(bdb_search)
620                                 ": no paged results candidates\n",
621                                 0, 0, 0 );
622                         send_paged_response( op, rs, &lastid, 0 );
623
624                         rs->sr_err = LDAP_OTHER;
625                         goto done;
626                 }
627                 nentries = ps->ps_count;
628                 if ( id == (ID)ps->ps_cookie )
629                         id = bdb_idl_next( candidates, &cursor );
630                 goto loop_begin;
631         }
632
633         for ( id = bdb_idl_first( candidates, &cursor );
634                   id != NOID ; id = bdb_idl_next( candidates, &cursor ) )
635         {
636                 int scopeok;
637
638 loop_begin:
639
640                 /* check for abandon */
641                 if ( op->o_abandon ) {
642                         rs->sr_err = SLAPD_ABANDON;
643                         goto done;
644                 }
645
646                 /* mostly needed by internal searches,
647                  * e.g. related to syncrepl, for whom
648                  * abandon does not get set... */
649                 if ( slapd_shutdown ) {
650                         rs->sr_err = LDAP_UNAVAILABLE;
651                         send_ldap_disconnect( op, rs );
652                         goto done;
653                 }
654
655                 /* check time limit */
656                 if ( op->ors_tlimit != SLAP_NO_LIMIT
657                                 && slap_get_time() > stoptime )
658                 {
659                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
660                         rs->sr_ref = rs->sr_v2ref;
661                         send_ldap_result( op, rs );
662                         rs->sr_err = LDAP_SUCCESS;
663                         goto done;
664                 }
665
666                 /* If we inspect more entries than will
667                  * fit into the entry cache, stop caching
668                  * any subsequent entries
669                  */
670                 nentries++;
671                 if ( nentries > bdb->bi_cache.c_maxsize && !idflag )
672                         idflag = ID_NOCACHE;
673
674 fetch_entry_retry:
675                         /* get the entry with reader lock */
676                         ei = NULL;
677                         rs->sr_err = bdb_cache_find_id( op, ltid,
678                                 id, &ei, idflag, &lock );
679
680                         if (rs->sr_err == LDAP_BUSY) {
681                                 rs->sr_text = "ldap server busy";
682                                 send_ldap_result( op, rs );
683                                 goto done;
684
685                         } else if ( rs->sr_err == DB_LOCK_DEADLOCK
686                                 || rs->sr_err == DB_LOCK_NOTGRANTED )
687                         {
688                                 goto fetch_entry_retry;
689                         } else if ( rs->sr_err == LDAP_OTHER ) {
690                                 rs->sr_text = "internal error";
691                                 send_ldap_result( op, rs );
692                                 goto done;
693                         }
694
695                         if ( ei && rs->sr_err == LDAP_SUCCESS ) {
696                                 e = ei->bei_e;
697                         } else {
698                                 e = NULL;
699                         }
700
701                         if ( e == NULL ) {
702                                 if( !BDB_IDL_IS_RANGE(candidates) ) {
703                                         /* only complain for non-range IDLs */
704                                         Debug( LDAP_DEBUG_TRACE,
705                                                 LDAP_XSTRING(bdb_search)
706                                                 ": candidate %ld not found\n",
707                                                 (long) id, 0, 0 );
708                                 }
709
710                                 goto loop_continue;
711                         }
712
713                 rs->sr_entry = e;
714
715                 if ( is_entry_subentry( e ) ) {
716                         if( op->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
717                                 if(!get_subentries_visibility( op )) {
718                                         /* only subentries are visible */
719                                         goto loop_continue;
720                                 }
721
722                         } else if ( get_subentries( op ) &&
723                                 !get_subentries_visibility( op ))
724                         {
725                                 /* only subentries are visible */
726                                 goto loop_continue;
727                         }
728
729                 } else if ( get_subentries_visibility( op )) {
730                         /* only subentries are visible */
731                         goto loop_continue;
732                 }
733
734                 /* Does this candidate actually satisfy the search scope?
735                  *
736                  * Note that we don't lock access to the bei_parent pointer.
737                  * Since only leaf nodes can be deleted, the parent of any
738                  * node will always be a valid node. Also since we have
739                  * a Read lock on the data, it cannot be renamed out of the
740                  * scope while we are looking at it, and unless we're using
741                  * BDB_HIER, its parents cannot be moved either.
742                  */
743                 scopeok = 0;
744                 switch( op->ors_scope ) {
745                 case LDAP_SCOPE_BASE:
746                         /* This is always true, yes? */
747                         if ( id == base.e_id ) scopeok = 1;
748                         break;
749
750                 case LDAP_SCOPE_ONELEVEL:
751                         if ( ei->bei_parent->bei_id == base.e_id ) scopeok = 1;
752                         break;
753
754 #ifdef LDAP_SCOPE_CHILDREN
755                 case LDAP_SCOPE_CHILDREN:
756                         if ( id == base.e_id ) break;
757                         /* Fall-thru */
758 #endif
759                 case LDAP_SCOPE_SUBTREE: {
760                         EntryInfo *tmp;
761                         for ( tmp = BEI(e); tmp; tmp = tmp->bei_parent ) {
762                                 if ( tmp->bei_id == base.e_id ) {
763                                         scopeok = 1;
764                                         break;
765                                 }
766                         }
767                         } break;
768                 }
769
770                 /* aliases were already dereferenced in candidate list */
771                 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
772                         /* but if the search base is an alias, and we didn't
773                          * deref it when finding, return it.
774                          */
775                         if ( is_entry_alias(e) &&
776                                 ((op->ors_deref & LDAP_DEREF_FINDING) ||
777                                         !bvmatch(&e->e_nname, &op->o_req_ndn)))
778                         {
779                                 goto loop_continue;
780                         }
781
782                         /* scopes is only non-empty for onelevel or subtree */
783                         if ( !scopeok && BDB_IDL_N(scopes) ) {
784                                 unsigned x;
785                                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) {
786                                         x = bdb_idl_search( scopes, e->e_id );
787                                         if ( scopes[x] == e->e_id ) scopeok = 1;
788                                 } else {
789                                         /* subtree, walk up the tree */
790                                         EntryInfo *tmp = BEI(e);
791                                         for (;tmp->bei_parent; tmp=tmp->bei_parent) {
792                                                 x = bdb_idl_search( scopes, tmp->bei_id );
793                                                 if ( scopes[x] == tmp->bei_id ) {
794                                                         scopeok = 1;
795                                                         break;
796                                                 }
797                                         }
798                                 }
799                         }
800                 }
801
802                 /* Not in scope, ignore it */
803                 if ( !scopeok )
804                 {
805                         Debug( LDAP_DEBUG_TRACE,
806                                 LDAP_XSTRING(bdb_search)
807                                 ": %ld scope not okay\n",
808                                 (long) id, 0, 0 );
809                         goto loop_continue;
810                 }
811
812                 /*
813                  * if it's a referral, add it to the list of referrals. only do
814                  * this for non-base searches, and don't check the filter
815                  * explicitly here since it's only a candidate anyway.
816                  */
817                 if ( !manageDSAit && op->oq_search.rs_scope != LDAP_SCOPE_BASE
818                         && is_entry_referral( e ) )
819                 {
820                         BerVarray erefs = get_entry_referrals( op, e );
821                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
822                                 op->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
823                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
824
825                         send_search_reference( op, rs );
826
827                         ber_bvarray_free( rs->sr_ref );
828                         ber_bvarray_free( erefs );
829                         rs->sr_ref = NULL;
830
831                         goto loop_continue;
832                 }
833
834                 if ( !manageDSAit && is_entry_glue( e )) {
835                         goto loop_continue;
836                 }
837
838                 /* if it matches the filter and scope, send it */
839                 rs->sr_err = test_filter( op, rs->sr_entry, op->oq_search.rs_filter );
840
841                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
842                         /* check size limit */
843                         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
844                                 if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
845 #ifdef SLAP_ZONE_ALLOC
846                                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
847 #endif
848                                         bdb_cache_return_entry_r( bdb, e, &lock );
849                                         e = NULL;
850                                         send_paged_response( op, rs, &lastid, tentries );
851                                         goto done;
852                                 }
853                                 lastid = id;
854                         }
855
856                         if (e) {
857                                 /* safe default */
858                                 rs->sr_attrs = op->oq_search.rs_attrs;
859                                 rs->sr_operational_attrs = NULL;
860                                 rs->sr_ctrls = NULL;
861                                 rs->sr_flags = 0;
862                                 rs->sr_err = LDAP_SUCCESS;
863                                 rs->sr_err = send_search_entry( op, rs );
864
865                                 switch ( rs->sr_err ) {
866                                 case LDAP_SUCCESS:      /* entry sent ok */
867                                         break;
868                                 default:                /* entry not sent */
869                                         break;
870                                 case LDAP_UNAVAILABLE:
871                                 case LDAP_SIZELIMIT_EXCEEDED:
872 #ifdef SLAP_ZONE_ALLOC
873                                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
874 #endif
875                                         bdb_cache_return_entry_r(bdb, e, &lock);
876                                         e = NULL;
877                                         rs->sr_entry = NULL;
878                                         if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
879                                                 rs->sr_ref = rs->sr_v2ref;
880                                                 send_ldap_result( op, rs );
881                                                 rs->sr_err = LDAP_SUCCESS;
882
883                                         } else {
884                                                 rs->sr_err = LDAP_OTHER;
885                                         }
886                                         goto done;
887                                 }
888                         }
889
890                 } else {
891                         Debug( LDAP_DEBUG_TRACE,
892                                 LDAP_XSTRING(bdb_search)
893                                 ": %ld does not match filter\n",
894                                 (long) id, 0, 0 );
895                 }
896
897 loop_continue:
898                 if( e != NULL ) {
899                         /* free reader lock */
900 #ifdef SLAP_ZONE_ALLOC
901                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
902 #endif
903                         bdb_cache_return_entry_r( bdb, e , &lock );
904                         e = NULL;
905                         rs->sr_entry = NULL;
906                 }
907         }
908
909 nochange:
910         rs->sr_ctrls = NULL;
911         rs->sr_ref = rs->sr_v2ref;
912         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
913         rs->sr_rspoid = NULL;
914         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
915                 send_paged_response( op, rs, NULL, 0 );
916         } else {
917                 send_ldap_result( op, rs );
918         }
919
920         rs->sr_err = LDAP_SUCCESS;
921
922 done:
923         if( rs->sr_v2ref ) {
924                 ber_bvarray_free( rs->sr_v2ref );
925                 rs->sr_v2ref = NULL;
926         }
927         if( realbase.bv_val ) ch_free( realbase.bv_val );
928
929         return rs->sr_err;
930 }
931
932
933 static int base_candidate(
934         BackendDB       *be,
935         Entry   *e,
936         ID              *ids )
937 {
938         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
939                 e->e_nname.bv_val, (long) e->e_id, 0);
940
941         ids[0] = 1;
942         ids[1] = e->e_id;
943         return 0;
944 }
945
946 /* Look for "objectClass Present" in this filter.
947  * Also count depth of filter tree while we're at it.
948  */
949 static int oc_filter(
950         Filter *f,
951         int cur,
952         int *max )
953 {
954         int rc = 0;
955
956         assert( f != NULL );
957
958         if( cur > *max ) *max = cur;
959
960         switch( f->f_choice ) {
961         case LDAP_FILTER_PRESENT:
962                 if (f->f_desc == slap_schema.si_ad_objectClass) {
963                         rc = 1;
964                 }
965                 break;
966
967         case LDAP_FILTER_AND:
968         case LDAP_FILTER_OR:
969                 cur++;
970                 for ( f=f->f_and; f; f=f->f_next ) {
971                         (void) oc_filter(f, cur, max);
972                 }
973                 break;
974
975         default:
976                 break;
977         }
978         return rc;
979 }
980
981 static void search_stack_free( void *key, void *data )
982 {
983         ber_memfree_x(data, NULL);
984 }
985
986 static void *search_stack( Operation *op )
987 {
988         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
989         void *ret = NULL;
990
991         if ( op->o_threadctx ) {
992                 ldap_pvt_thread_pool_getkey( op->o_threadctx, (void *)search_stack,
993                         &ret, NULL );
994         } else {
995                 ret = bdb->bi_search_stack;
996         }
997
998         if ( !ret ) {
999                 ret = ch_malloc( bdb->bi_search_stack_depth * BDB_IDL_UM_SIZE
1000                         * sizeof( ID ) );
1001                 if ( op->o_threadctx ) {
1002                         ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)search_stack,
1003                                 ret, search_stack_free, NULL, NULL );
1004                 } else {
1005                         bdb->bi_search_stack = ret;
1006                 }
1007         }
1008         return ret;
1009 }
1010
1011 static int search_candidates(
1012         Operation *op,
1013         SlapReply *rs,
1014         Entry *e,
1015         DB_TXN *txn,
1016         ID      *ids,
1017         ID      *scopes )
1018 {
1019         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1020         int rc, depth = 1;
1021         Filter          f, rf, xf, nf;
1022         ID              *stack;
1023         AttributeAssertion aa_ref = ATTRIBUTEASSERTION_INIT;
1024         Filter  sf;
1025         AttributeAssertion aa_subentry = ATTRIBUTEASSERTION_INIT;
1026
1027         /*
1028          * This routine takes as input a filter (user-filter)
1029          * and rewrites it as follows:
1030          *      (&(scope=DN)[(objectClass=subentry)]
1031          *              (|[(objectClass=referral)(objectClass=alias)](user-filter))
1032          */
1033
1034         Debug(LDAP_DEBUG_TRACE,
1035                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1036                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1037
1038         xf.f_or = op->oq_search.rs_filter;
1039         xf.f_choice = LDAP_FILTER_OR;
1040         xf.f_next = NULL;
1041
1042         /* If the user's filter uses objectClass=*,
1043          * these clauses are redundant.
1044          */
1045         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
1046                 && !get_subentries_visibility(op)) {
1047                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
1048                         /* match referral objects */
1049                         struct berval bv_ref = BER_BVC( "referral" );
1050                         rf.f_choice = LDAP_FILTER_EQUALITY;
1051                         rf.f_ava = &aa_ref;
1052                         rf.f_av_desc = slap_schema.si_ad_objectClass;
1053                         rf.f_av_value = bv_ref;
1054                         rf.f_next = xf.f_or;
1055                         xf.f_or = &rf;
1056                         depth++;
1057                 }
1058         }
1059
1060         f.f_next = NULL;
1061         f.f_choice = LDAP_FILTER_AND;
1062         f.f_and = &nf;
1063         /* Dummy; we compute scope separately now */
1064         nf.f_choice = SLAPD_FILTER_COMPUTED;
1065         nf.f_result = LDAP_SUCCESS;
1066         nf.f_next = ( xf.f_or == op->oq_search.rs_filter )
1067                 ? op->oq_search.rs_filter : &xf ;
1068         /* Filter depth increased again, adding dummy clause */
1069         depth++;
1070
1071         if( get_subentries_visibility( op ) ) {
1072                 struct berval bv_subentry = BER_BVC( "subentry" );
1073                 sf.f_choice = LDAP_FILTER_EQUALITY;
1074                 sf.f_ava = &aa_subentry;
1075                 sf.f_av_desc = slap_schema.si_ad_objectClass;
1076                 sf.f_av_value = bv_subentry;
1077                 sf.f_next = nf.f_next;
1078                 nf.f_next = &sf;
1079         }
1080
1081         /* Allocate IDL stack, plus 1 more for former tmp */
1082         if ( depth+1 > bdb->bi_search_stack_depth ) {
1083                 stack = ch_malloc( (depth + 1) * BDB_IDL_UM_SIZE * sizeof( ID ) );
1084         } else {
1085                 stack = search_stack( op );
1086         }
1087
1088         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1089                 rc = search_aliases( op, rs, e, txn, ids, scopes, stack );
1090         } else {
1091                 rc = bdb_dn2idl( op, txn, &e->e_nname, BEI(e), ids, stack );
1092         }
1093
1094         if ( rc == LDAP_SUCCESS ) {
1095                 rc = bdb_filter_candidates( op, txn, &f, ids,
1096                         stack, stack+BDB_IDL_UM_SIZE );
1097         }
1098
1099         if ( depth+1 > bdb->bi_search_stack_depth ) {
1100                 ch_free( stack );
1101         }
1102
1103         if( rc ) {
1104                 Debug(LDAP_DEBUG_TRACE,
1105                         "bdb_search_candidates: failed (rc=%d)\n",
1106                         rc, NULL, NULL );
1107
1108         } else {
1109                 Debug(LDAP_DEBUG_TRACE,
1110                         "bdb_search_candidates: id=%ld first=%ld last=%ld\n",
1111                         (long) ids[0],
1112                         (long) BDB_IDL_FIRST(ids),
1113                         (long) BDB_IDL_LAST(ids) );
1114         }
1115
1116         return rc;
1117 }
1118
1119 static int
1120 parse_paged_cookie( Operation *op, SlapReply *rs )
1121 {
1122         int             rc = LDAP_SUCCESS;
1123         PagedResultsState *ps = op->o_pagedresults_state;
1124
1125         /* this function must be invoked only if the pagedResults
1126          * control has been detected, parsed and partially checked
1127          * by the frontend */
1128         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
1129
1130         /* cookie decoding/checks deferred to backend... */
1131         if ( ps->ps_cookieval.bv_len ) {
1132                 PagedResultsCookie reqcookie;
1133                 if( ps->ps_cookieval.bv_len != sizeof( reqcookie ) ) {
1134                         /* bad cookie */
1135                         rs->sr_text = "paged results cookie is invalid";
1136                         rc = LDAP_PROTOCOL_ERROR;
1137                         goto done;
1138                 }
1139
1140                 AC_MEMCPY( &reqcookie, ps->ps_cookieval.bv_val, sizeof( reqcookie ));
1141
1142                 if ( reqcookie > ps->ps_cookie ) {
1143                         /* bad cookie */
1144                         rs->sr_text = "paged results cookie is invalid";
1145                         rc = LDAP_PROTOCOL_ERROR;
1146                         goto done;
1147
1148                 } else if ( reqcookie < ps->ps_cookie ) {
1149                         rs->sr_text = "paged results cookie is invalid or old";
1150                         rc = LDAP_UNWILLING_TO_PERFORM;
1151                         goto done;
1152                 }
1153
1154         }
1155
1156 done:;
1157
1158         return rc;
1159 }
1160
1161 static void
1162 send_paged_response( 
1163         Operation       *op,
1164         SlapReply       *rs,
1165         ID              *lastid,
1166         int             tentries )
1167 {
1168         LDAPControl     ctrl, *ctrls[2];
1169         BerElementBuffer berbuf;
1170         BerElement      *ber = (BerElement *)&berbuf;
1171         PagedResultsCookie respcookie;
1172         struct berval cookie;
1173
1174         Debug(LDAP_DEBUG_ARGS,
1175                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1176                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1177
1178         BER_BVZERO( &ctrl.ldctl_value );
1179         ctrls[0] = &ctrl;
1180         ctrls[1] = NULL;
1181
1182         ber_init2( ber, NULL, LBER_USE_DER );
1183
1184         if ( lastid ) {
1185                 respcookie = ( PagedResultsCookie )(*lastid);
1186                 cookie.bv_len = sizeof( respcookie );
1187                 cookie.bv_val = (char *)&respcookie;
1188
1189         } else {
1190                 respcookie = ( PagedResultsCookie )0;
1191                 BER_BVSTR( &cookie, "" );
1192         }
1193
1194         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1195         op->o_conn->c_pagedresults_state.ps_count =
1196                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
1197                 rs->sr_nentries;
1198
1199         /* return size of 0 -- no estimate */
1200         ber_printf( ber, "{iO}", 0, &cookie ); 
1201
1202         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1203                 goto done;
1204         }
1205
1206         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1207         ctrls[0]->ldctl_iscritical = 0;
1208
1209         rs->sr_ctrls = ctrls;
1210         rs->sr_err = LDAP_SUCCESS;
1211         send_ldap_result( op, rs );
1212         rs->sr_ctrls = NULL;
1213
1214 done:
1215         (void) ber_free_buf( ber );
1216 }
1217