]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/search.c
implement search timeout when the remote server does not respond in the specified...
[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, 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, ei_root = {0};
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_root.bei_e = &e_root;
354                 ei_root.bei_parent = &ei_root;
355                 e_root.e_private = &ei_root;
356                 e_root.e_id = 0;
357                 BER_BVSTR( &e_root.e_nname, "" );
358                 BER_BVSTR( &e_root.e_name, "" );
359                 ei = &ei_root;
360                 rs->sr_err = LDAP_SUCCESS;
361         } else {
362                 if ( op->ors_deref & LDAP_DEREF_FINDING ) {
363                         BDB_IDL_ZERO(candidates);
364                 }
365 dn2entry_retry:
366                 /* get entry with reader lock */
367                 rs->sr_err = bdb_dn2entry( op, ltid, &op->o_req_ndn, &ei,
368                         1, locker, &lock );
369         }
370
371         switch(rs->sr_err) {
372         case DB_NOTFOUND:
373                 matched = ei->bei_e;
374                 break;
375         case 0:
376                 e = ei->bei_e;
377                 break;
378         case LDAP_BUSY:
379                 send_ldap_error( op, rs, LDAP_BUSY, "ldap server busy" );
380                 if ( !opinfo )
381                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
382                 return LDAP_BUSY;
383         case DB_LOCK_DEADLOCK:
384         case DB_LOCK_NOTGRANTED:
385                 goto dn2entry_retry;
386         default:
387                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
388                 if ( !opinfo )
389                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
390                 return rs->sr_err;
391         }
392
393         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
394                 if ( matched && is_entry_alias( matched )) {
395                         struct berval stub;
396
397                         stub.bv_val = op->o_req_ndn.bv_val;
398                         stub.bv_len = op->o_req_ndn.bv_len - matched->e_nname.bv_len - 1;
399                         e = deref_base( op, rs, matched, &matched, locker, &lock,
400                                 candidates, NULL );
401                         if ( e ) {
402                                 build_new_dn( &op->o_req_ndn, &e->e_nname, &stub,
403                                         op->o_tmpmemctx );
404                                 bdb_cache_return_entry_r (bdb, e, &lock);
405                                 matched = NULL;
406                                 goto dn2entry_retry;
407                         }
408                 } else if ( e && is_entry_alias( e )) {
409                         e = deref_base( op, rs, e, &matched, locker, &lock,
410                                 candidates, NULL );
411                 }
412         }
413
414         if ( e == NULL ) {
415                 struct berval matched_dn = BER_BVNULL;
416
417                 if ( matched != NULL ) {
418                         BerVarray erefs = NULL;
419
420                         /* return referral only if "disclose"
421                          * is granted on the object */
422                         if ( ! access_allowed( op, matched,
423                                                 slap_schema.si_ad_entry,
424                                                 NULL, ACL_DISCLOSE, NULL ) )
425                         {
426                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
427
428                         } else {
429                                 ber_dupbv( &matched_dn, &matched->e_name );
430
431                                 erefs = is_entry_referral( matched )
432                                         ? get_entry_referrals( op, matched )
433                                         : NULL;
434                                 if ( rs->sr_err == DB_NOTFOUND )
435                                         rs->sr_err = LDAP_REFERRAL;
436                                 rs->sr_matched = matched_dn.bv_val;
437                         }
438
439 #ifdef SLAP_ZONE_ALLOC
440                         slap_zn_runlock(bdb->bi_cache.c_zctx, matched);
441 #endif
442                         bdb_cache_return_entry_r (bdb, matched, &lock);
443                         matched = NULL;
444
445                         if ( erefs ) {
446                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
447                                         &op->o_req_dn, op->oq_search.rs_scope );
448                                 ber_bvarray_free( erefs );
449                         }
450
451                 } else {
452 #ifdef SLAP_ZONE_ALLOC
453                         slap_zn_runlock(bdb->bi_cache.c_zctx, matched);
454 #endif
455                         rs->sr_ref = referral_rewrite( default_referral,
456                                 NULL, &op->o_req_dn, op->oq_search.rs_scope );
457                         rs->sr_err = rs->sr_ref != NULL ? LDAP_REFERRAL : LDAP_NO_SUCH_OBJECT;
458                 }
459
460                 send_ldap_result( op, rs );
461
462                 if ( !opinfo )
463                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
464                 if ( rs->sr_ref ) {
465                         ber_bvarray_free( rs->sr_ref );
466                         rs->sr_ref = NULL;
467                 }
468                 if ( !BER_BVISNULL( &matched_dn ) ) {
469                         ber_memfree( matched_dn.bv_val );
470                         rs->sr_matched = NULL;
471                 }
472                 return rs->sr_err;
473         }
474
475         /* NOTE: __NEW__ "search" access is required
476          * on searchBase object */
477         if ( ! access_allowed_mask( op, e, slap_schema.si_ad_entry,
478                                 NULL, ACL_SEARCH, NULL, &mask ) )
479         {
480                 if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
481                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
482                 } else {
483                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
484                 }
485
486 #ifdef SLAP_ZONE_ALLOC
487                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
488 #endif
489                 if ( e != &e_root ) {
490                         bdb_cache_return_entry_r(bdb, e, &lock);
491                 }
492                 send_ldap_result( op, rs );
493                 return rs->sr_err;
494         }
495
496         if ( !manageDSAit && e != &e_root && is_entry_referral( e ) ) {
497                 /* entry is a referral, don't allow add */
498                 struct berval matched_dn = BER_BVNULL;
499                 BerVarray erefs = NULL;
500                 
501                 ber_dupbv( &matched_dn, &e->e_name );
502                 erefs = get_entry_referrals( op, e );
503
504                 rs->sr_err = LDAP_REFERRAL;
505
506 #ifdef SLAP_ZONE_ALLOC
507                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
508 #endif
509                 bdb_cache_return_entry_r( bdb, e, &lock );
510                 e = NULL;
511
512                 if ( erefs ) {
513                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
514                                 &op->o_req_dn, op->oq_search.rs_scope );
515                         ber_bvarray_free( erefs );
516
517                         if ( !rs->sr_ref ) {
518                                 rs->sr_text = "bad_referral object";
519                         }
520                 }
521
522                 Debug( LDAP_DEBUG_TRACE,
523                         LDAP_XSTRING(bdb_search) ": entry is referral\n",
524                         0, 0, 0 );
525
526                 rs->sr_matched = matched_dn.bv_val;
527                 send_ldap_result( op, rs );
528
529                 if ( !opinfo ) {
530                         LOCK_ID_FREE (bdb->bi_dbenv, locker );
531                 }
532                 ber_bvarray_free( rs->sr_ref );
533                 rs->sr_ref = NULL;
534                 ber_memfree( matched_dn.bv_val );
535                 rs->sr_matched = NULL;
536                 return 1;
537         }
538
539         if ( get_assert( op ) &&
540                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
541         {
542                 rs->sr_err = LDAP_ASSERTION_FAILED;
543 #ifdef SLAP_ZONE_ALLOC
544                 slap_zn_runlock(bdb->bi_cache.c_zctx, e);
545 #endif
546                 if ( e != &e_root ) {
547                         bdb_cache_return_entry_r(bdb, e, &lock);
548                 }
549                 send_ldap_result( op, rs );
550                 return 1;
551         }
552
553         /* compute it anyway; root does not use it */
554         stoptime = op->o_time + op->ors_tlimit;
555
556         /* need normalized dn below */
557         ber_dupbv( &realbase, &e->e_nname );
558
559         /* Copy info to base, must free entry before accessing the database
560          * in search_candidates, to avoid deadlocks.
561          */
562         base.e_private = e->e_private;
563         base.e_nname = realbase;
564         base.e_id = e->e_id;
565
566 #ifdef SLAP_ZONE_ALLOC
567         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
568 #endif
569         if ( e != &e_root ) {
570                 bdb_cache_return_entry_r(bdb, e, &lock);
571         }
572         e = NULL;
573
574         /* select candidates */
575         if ( op->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
576                 rs->sr_err = base_candidate( op->o_bd, &base, candidates );
577
578         } else {
579                 BDB_IDL_ZERO( candidates );
580                 BDB_IDL_ZERO( scopes );
581                 rs->sr_err = search_candidates( op, rs, &base,
582                         locker, candidates, scopes );
583         }
584
585         /* start cursor at beginning of candidates.
586          */
587         cursor = 0;
588
589         if ( candidates[0] == 0 ) {
590                 Debug( LDAP_DEBUG_TRACE,
591                         LDAP_XSTRING(bdb_search) ": no candidates\n",
592                         0, 0, 0 );
593
594                 goto nochange;
595         }
596
597         /* if not root and candidates exceed to-be-checked entries, abort */
598         if ( op->ors_limit      /* isroot == FALSE */ &&
599                 op->ors_limit->lms_s_unchecked != -1 &&
600                 BDB_IDL_N(candidates) > (unsigned) op->ors_limit->lms_s_unchecked )
601         {
602                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
603                 send_ldap_result( op, rs );
604                 rs->sr_err = LDAP_SUCCESS;
605                 goto done;
606         }
607
608         if ( op->ors_limit == NULL      /* isroot == TRUE */ ||
609                 !op->ors_limit->lms_s_pr_hide )
610         {
611                 tentries = BDB_IDL_N(candidates);
612         }
613
614         if ( get_pagedresults( op ) > SLAP_CONTROL_IGNORED ) {
615                 PagedResultsState *ps = op->o_pagedresults_state;
616                 /* deferred cookie parsing */
617                 rs->sr_err = parse_paged_cookie( op, rs );
618                 if ( rs->sr_err != LDAP_SUCCESS ) {
619                         send_ldap_result( op, rs );
620                         goto done;
621                 }
622
623                 if ( (ID)( ps->ps_cookie ) == 0 ) {
624                         id = bdb_idl_first( candidates, &cursor );
625
626                 } else {
627                         if ( ps->ps_size == 0 ) {
628                                 rs->sr_err = LDAP_SUCCESS;
629                                 rs->sr_text = "search abandoned by pagedResult size=0";
630                                 send_ldap_result( op, rs );
631                                 goto done;
632                         }
633                         for ( id = bdb_idl_first( candidates, &cursor );
634                                 id != NOID &&
635                                         id <= (ID)( ps->ps_cookie );
636                                 id = bdb_idl_next( candidates, &cursor ) )
637                         {
638                                 /* empty */;
639                         }
640                 }
641
642                 if ( cursor == NOID ) {
643                         Debug( LDAP_DEBUG_TRACE, 
644                                 LDAP_XSTRING(bdb_search)
645                                 ": no paged results candidates\n",
646                                 0, 0, 0 );
647                         send_paged_response( op, rs, &lastid, 0 );
648
649                         rs->sr_err = LDAP_OTHER;
650                         goto done;
651                 }
652                 goto loop_begin;
653         }
654
655         for ( id = bdb_idl_first( candidates, &cursor );
656                   id != NOID ; id = bdb_idl_next( candidates, &cursor ) )
657         {
658                 int scopeok;
659
660 loop_begin:
661
662                 /* check for abandon */
663                 if ( op->o_abandon ) {
664                         rs->sr_err = SLAPD_ABANDON;
665                         goto done;
666                 }
667
668                 /* check time limit */
669                 if ( op->ors_tlimit != SLAP_NO_LIMIT
670                                 && slap_get_time() > stoptime )
671                 {
672                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
673                         rs->sr_ref = rs->sr_v2ref;
674                         send_ldap_result( op, rs );
675                         rs->sr_err = LDAP_SUCCESS;
676                         goto done;
677                 }
678
679 fetch_entry_retry:
680                         /* get the entry with reader lock */
681                         ei = NULL;
682                         rs->sr_err = bdb_cache_find_id( op, ltid,
683                                 id, &ei, 0, locker, &lock );
684
685                         if (rs->sr_err == LDAP_BUSY) {
686                                 rs->sr_text = "ldap server busy";
687                                 send_ldap_result( op, rs );
688                                 goto done;
689
690                         } else if ( rs->sr_err == DB_LOCK_DEADLOCK
691                                 || rs->sr_err == DB_LOCK_NOTGRANTED )
692                         {
693                                 goto fetch_entry_retry;
694                         }
695
696                         if ( ei && rs->sr_err == LDAP_SUCCESS ) {
697                                 e = ei->bei_e;
698                         } else {
699                                 e = NULL;
700                         }
701
702                         if ( e == NULL ) {
703                                 if( !BDB_IDL_IS_RANGE(candidates) ) {
704                                         /* only complain for non-range IDLs */
705                                         Debug( LDAP_DEBUG_TRACE,
706                                                 LDAP_XSTRING(bdb_search)
707                                                 ": candidate %ld not found\n",
708                                                 (long) id, 0, 0 );
709                                 }
710
711                                 goto loop_continue;
712                         }
713
714                 rs->sr_entry = e;
715
716                 if ( is_entry_subentry( e ) ) {
717                         if( op->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
718                                 if(!get_subentries_visibility( op )) {
719                                         /* only subentries are visible */
720                                         goto loop_continue;
721                                 }
722
723                         } else if ( get_subentries( op ) &&
724                                 !get_subentries_visibility( op ))
725                         {
726                                 /* only subentries are visible */
727                                 goto loop_continue;
728                         }
729
730                 } else if ( get_subentries_visibility( op )) {
731                         /* only subentries are visible */
732                         goto loop_continue;
733                 }
734
735                 /* Does this candidate actually satisfy the search scope?
736                  *
737                  * Note that we don't lock access to the bei_parent pointer.
738                  * Since only leaf nodes can be deleted, the parent of any
739                  * node will always be a valid node. Also since we have
740                  * a Read lock on the data, it cannot be renamed out of the
741                  * scope while we are looking at it, and unless we're using
742                  * BDB_HIER, its parents cannot be moved either.
743                  */
744                 scopeok = 0;
745                 switch( op->ors_scope ) {
746                 case LDAP_SCOPE_BASE:
747                         /* This is always true, yes? */
748                         if ( id == base.e_id ) scopeok = 1;
749                         break;
750
751                 case LDAP_SCOPE_ONELEVEL:
752                         if ( ei->bei_parent->bei_id == base.e_id ) scopeok = 1;
753                         break;
754
755 #ifdef LDAP_SCOPE_CHILDREN
756                 case LDAP_SCOPE_CHILDREN:
757                         if ( id == base.e_id ) break;
758                         /* Fall-thru */
759 #endif
760                 case LDAP_SCOPE_SUBTREE: {
761                         EntryInfo *tmp;
762                         for ( tmp = BEI(e); tmp; tmp = tmp->bei_parent ) {
763                                 if ( tmp->bei_id == base.e_id ) {
764                                         scopeok = 1;
765                                         break;
766                                 }
767                         }
768                         } break;
769                 }
770
771                 /* aliases were already dereferenced in candidate list */
772                 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
773                         /* but if the search base is an alias, and we didn't
774                          * deref it when finding, return it.
775                          */
776                         if ( is_entry_alias(e) &&
777                                 ((op->ors_deref & LDAP_DEREF_FINDING) ||
778                                         !bvmatch(&e->e_nname, &op->o_req_ndn)))
779                         {
780                                 goto loop_continue;
781                         }
782
783                         /* scopes is only non-empty for onelevel or subtree */
784                         if ( !scopeok && BDB_IDL_N(scopes) ) {
785                                 unsigned x;
786                                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) {
787                                         x = bdb_idl_search( scopes, e->e_id );
788                                         if ( scopes[x] == e->e_id ) scopeok = 1;
789                                 } else {
790                                         /* subtree, walk up the tree */
791                                         EntryInfo *tmp = BEI(e);
792                                         for (;tmp->bei_parent; tmp=tmp->bei_parent) {
793                                                 x = bdb_idl_search( scopes, tmp->bei_id );
794                                                 if ( scopes[x] == tmp->bei_id ) {
795                                                         scopeok = 1;
796                                                         break;
797                                                 }
798                                         }
799                                 }
800                         }
801                 }
802
803                 /* Not in scope, ignore it */
804                 if ( !scopeok )
805                 {
806                         Debug( LDAP_DEBUG_TRACE,
807                                 LDAP_XSTRING(bdb_search)
808                                 ": %ld scope not okay\n",
809                                 (long) id, 0, 0 );
810                         goto loop_continue;
811                 }
812
813                 /*
814                  * if it's a referral, add it to the list of referrals. only do
815                  * this for non-base searches, and don't check the filter
816                  * explicitly here since it's only a candidate anyway.
817                  */
818                 if ( !manageDSAit && op->oq_search.rs_scope != LDAP_SCOPE_BASE
819                         && is_entry_referral( e ) )
820                 {
821                         BerVarray erefs = get_entry_referrals( op, e );
822                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
823                                 op->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
824                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
825
826                         send_search_reference( op, rs );
827
828                         ber_bvarray_free( rs->sr_ref );
829                         ber_bvarray_free( erefs );
830                         rs->sr_ref = NULL;
831
832                         goto loop_continue;
833                 }
834
835                 if ( !manageDSAit && is_entry_glue( e )) {
836                         goto loop_continue;
837                 }
838
839                 /* if it matches the filter and scope, send it */
840                 rs->sr_err = test_filter( op, rs->sr_entry, op->oq_search.rs_filter );
841
842                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
843                         /* check size limit */
844                         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
845                                 if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
846 #ifdef SLAP_ZONE_ALLOC
847                                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
848 #endif
849                                         bdb_cache_return_entry_r( bdb, e, &lock );
850                                         e = NULL;
851                                         send_paged_response( op, rs, &lastid, tentries );
852                                         goto done;
853                                 }
854                                 lastid = id;
855                         }
856
857                         if (e) {
858                                 /* safe default */
859                                 rs->sr_attrs = op->oq_search.rs_attrs;
860                                 rs->sr_operational_attrs = NULL;
861                                 rs->sr_ctrls = NULL;
862                                 rs->sr_flags = 0;
863                                 rs->sr_err = LDAP_SUCCESS;
864                                 rs->sr_err = send_search_entry( op, rs );
865
866                                 switch ( rs->sr_err ) {
867                                 case LDAP_SUCCESS:      /* entry sent ok */
868                                         break;
869                                 default:                /* entry not sent */
870                                         break;
871                                 case LDAP_UNAVAILABLE:
872                                 case LDAP_SIZELIMIT_EXCEEDED:
873 #ifdef SLAP_ZONE_ALLOC
874                                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
875 #endif
876                                         bdb_cache_return_entry_r(bdb, e, &lock);
877                                         e = NULL;
878                                         rs->sr_entry = NULL;
879                                         if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
880                                                 rs->sr_ref = rs->sr_v2ref;
881                                                 send_ldap_result( op, rs );
882                                                 rs->sr_err = LDAP_SUCCESS;
883
884                                         } else {
885                                                 rs->sr_err = LDAP_OTHER;
886                                         }
887                                         goto done;
888                                 }
889                         }
890
891                 } else {
892                         Debug( LDAP_DEBUG_TRACE,
893                                 LDAP_XSTRING(bdb_search)
894                                 ": %ld does not match filter\n",
895                                 (long) id, 0, 0 );
896                 }
897
898 loop_continue:
899                 if( e != NULL ) {
900                         /* free reader lock */
901 #ifdef SLAP_ZONE_ALLOC
902                         slap_zn_runlock(bdb->bi_cache.c_zctx, e);
903 #endif
904                         bdb_cache_return_entry_r( bdb, e , &lock );
905                         e = NULL;
906                         rs->sr_entry = NULL;
907                 }
908         }
909
910 nochange:
911         rs->sr_ctrls = NULL;
912         rs->sr_ref = rs->sr_v2ref;
913         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
914         rs->sr_rspoid = NULL;
915         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
916                 send_paged_response( op, rs, NULL, 0 );
917         } else {
918                 send_ldap_result( op, rs );
919         }
920
921         rs->sr_err = LDAP_SUCCESS;
922
923 done:
924         if ( !opinfo )
925                 LOCK_ID_FREE( bdb->bi_dbenv, locker );
926
927         if( rs->sr_v2ref ) {
928                 ber_bvarray_free( rs->sr_v2ref );
929                 rs->sr_v2ref = NULL;
930         }
931         if( realbase.bv_val ) ch_free( realbase.bv_val );
932
933         return rs->sr_err;
934 }
935
936
937 static int base_candidate(
938         BackendDB       *be,
939         Entry   *e,
940         ID              *ids )
941 {
942         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
943                 e->e_nname.bv_val, (long) e->e_id, 0);
944
945         ids[0] = 1;
946         ids[1] = e->e_id;
947         return 0;
948 }
949
950 /* Look for "objectClass Present" in this filter.
951  * Also count depth of filter tree while we're at it.
952  */
953 static int oc_filter(
954         Filter *f,
955         int cur,
956         int *max )
957 {
958         int rc = 0;
959
960         assert( f != NULL );
961
962         if( cur > *max ) *max = cur;
963
964         switch( f->f_choice ) {
965         case LDAP_FILTER_PRESENT:
966                 if (f->f_desc == slap_schema.si_ad_objectClass) {
967                         rc = 1;
968                 }
969                 break;
970
971         case LDAP_FILTER_AND:
972         case LDAP_FILTER_OR:
973                 cur++;
974                 for ( f=f->f_and; f; f=f->f_next ) {
975                         (void) oc_filter(f, cur, max);
976                 }
977                 break;
978
979         default:
980                 break;
981         }
982         return rc;
983 }
984
985 static void search_stack_free( void *key, void *data )
986 {
987         ber_memfree_x(data, NULL);
988 }
989
990 static void *search_stack( Operation *op )
991 {
992         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
993         void *ret = NULL;
994
995         if ( op->o_threadctx ) {
996                 ldap_pvt_thread_pool_getkey( op->o_threadctx, search_stack,
997                         &ret, NULL );
998         } else {
999                 ret = bdb->bi_search_stack;
1000         }
1001
1002         if ( !ret ) {
1003                 ret = ch_malloc( bdb->bi_search_stack_depth * BDB_IDL_UM_SIZE
1004                         * sizeof( ID ) );
1005                 if ( op->o_threadctx ) {
1006                         ldap_pvt_thread_pool_setkey( op->o_threadctx, search_stack,
1007                                 ret, search_stack_free );
1008                 } else {
1009                         bdb->bi_search_stack = ret;
1010                 }
1011         }
1012         return ret;
1013 }
1014
1015 static int search_candidates(
1016         Operation *op,
1017         SlapReply *rs,
1018         Entry *e,
1019         u_int32_t locker,
1020         ID      *ids,
1021         ID      *scopes )
1022 {
1023         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
1024         int rc, depth = 1;
1025         Filter          f, rf, xf, nf;
1026         ID              *stack;
1027 #ifdef LDAP_COMP_MATCH
1028         AttributeAssertion aa_ref = { NULL, BER_BVNULL, NULL };
1029 #else
1030         AttributeAssertion aa_ref = { NULL, BER_BVNULL };
1031 #endif
1032         Filter  sf;
1033 #ifdef LDAP_COMP_MATCH
1034         AttributeAssertion aa_subentry = { NULL, BER_BVNULL, NULL };
1035 #else
1036         AttributeAssertion aa_subentry = { NULL, BER_BVNULL };
1037 #endif
1038
1039         /*
1040          * This routine takes as input a filter (user-filter)
1041          * and rewrites it as follows:
1042          *      (&(scope=DN)[(objectClass=subentry)]
1043          *              (|[(objectClass=referral)(objectClass=alias)](user-filter))
1044          */
1045
1046         Debug(LDAP_DEBUG_TRACE,
1047                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1048                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1049
1050         xf.f_or = op->oq_search.rs_filter;
1051         xf.f_choice = LDAP_FILTER_OR;
1052         xf.f_next = NULL;
1053
1054         /* If the user's filter uses objectClass=*,
1055          * these clauses are redundant.
1056          */
1057         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
1058                 && !get_subentries_visibility(op)) {
1059                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
1060                         /* match referral objects */
1061                         struct berval bv_ref = BER_BVC( "referral" );
1062                         rf.f_choice = LDAP_FILTER_EQUALITY;
1063                         rf.f_ava = &aa_ref;
1064                         rf.f_av_desc = slap_schema.si_ad_objectClass;
1065                         rf.f_av_value = bv_ref;
1066                         rf.f_next = xf.f_or;
1067                         xf.f_or = &rf;
1068                         depth++;
1069                 }
1070         }
1071
1072         f.f_next = NULL;
1073         f.f_choice = LDAP_FILTER_AND;
1074         f.f_and = &nf;
1075         /* Dummy; we compute scope separately now */
1076         nf.f_choice = SLAPD_FILTER_COMPUTED;
1077         nf.f_result = LDAP_SUCCESS;
1078         nf.f_next = ( xf.f_or == op->oq_search.rs_filter )
1079                 ? op->oq_search.rs_filter : &xf ;
1080         /* Filter depth increased again, adding dummy clause */
1081         depth++;
1082
1083         if( get_subentries_visibility( op ) ) {
1084                 struct berval bv_subentry = BER_BVC( "subentry" );
1085                 sf.f_choice = LDAP_FILTER_EQUALITY;
1086                 sf.f_ava = &aa_subentry;
1087                 sf.f_av_desc = slap_schema.si_ad_objectClass;
1088                 sf.f_av_value = bv_subentry;
1089                 sf.f_next = nf.f_next;
1090                 nf.f_next = &sf;
1091         }
1092
1093         /* Allocate IDL stack, plus 1 more for former tmp */
1094         if ( depth+1 > bdb->bi_search_stack_depth ) {
1095                 stack = ch_malloc( (depth + 1) * BDB_IDL_UM_SIZE * sizeof( ID ) );
1096         } else {
1097                 stack = search_stack( op );
1098         }
1099
1100         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1101                 rc = search_aliases( op, rs, e, locker, ids, scopes, stack );
1102         } else {
1103                 rc = bdb_dn2idl( op, locker, e, ids, stack );
1104         }
1105
1106         if ( rc == LDAP_SUCCESS ) {
1107                 rc = bdb_filter_candidates( op, locker, &f, ids,
1108                         stack, stack+BDB_IDL_UM_SIZE );
1109         }
1110
1111         if ( depth+1 > bdb->bi_search_stack_depth ) {
1112                 ch_free( stack );
1113         }
1114
1115         if( rc ) {
1116                 Debug(LDAP_DEBUG_TRACE,
1117                         "bdb_search_candidates: failed (rc=%d)\n",
1118                         rc, NULL, NULL );
1119
1120         } else {
1121                 Debug(LDAP_DEBUG_TRACE,
1122                         "bdb_search_candidates: id=%ld first=%ld last=%ld\n",
1123                         (long) ids[0],
1124                         (long) BDB_IDL_FIRST(ids),
1125                         (long) BDB_IDL_LAST(ids) );
1126         }
1127
1128         return rc;
1129 }
1130
1131 static int
1132 parse_paged_cookie( Operation *op, SlapReply *rs )
1133 {
1134         LDAPControl     **c;
1135         int             rc = LDAP_SUCCESS;
1136         ber_tag_t       tag;
1137         ber_int_t       size;
1138         BerElement      *ber;
1139         struct berval   cookie = BER_BVNULL;
1140         PagedResultsState *ps = op->o_pagedresults_state;
1141
1142         /* this function must be invoked only if the pagedResults
1143          * control has been detected, parsed and partially checked
1144          * by the frontend */
1145         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
1146
1147         /* look for the appropriate ctrl structure */
1148         for ( c = op->o_ctrls; c[0] != NULL; c++ ) {
1149                 if ( strcmp( c[0]->ldctl_oid, LDAP_CONTROL_PAGEDRESULTS ) == 0 )
1150                 {
1151                         break;
1152                 }
1153         }
1154
1155         if ( c[0] == NULL ) {
1156                 rs->sr_text = "missing pagedResults control";
1157                 return LDAP_PROTOCOL_ERROR;
1158         }
1159
1160         /* Tested by frontend */
1161         assert( c[0]->ldctl_value.bv_len > 0 );
1162
1163         /* Parse the control value
1164          *      realSearchControlValue ::= SEQUENCE {
1165          *              size    INTEGER (0..maxInt),
1166          *                              -- requested page size from client
1167          *                              -- result set size estimate from server
1168          *              cookie  OCTET STRING
1169          * }
1170          */
1171         ber = ber_init( &c[0]->ldctl_value );
1172         if ( ber == NULL ) {
1173                 rs->sr_text = "internal error";
1174                 return LDAP_OTHER;
1175         }
1176
1177         tag = ber_scanf( ber, "{im}", &size, &cookie );
1178
1179         /* Tested by frontend */
1180         assert( tag != LBER_ERROR );
1181         assert( size >= 0 );
1182
1183         /* cookie decoding/checks deferred to backend... */
1184         if ( cookie.bv_len ) {
1185                 PagedResultsCookie reqcookie;
1186                 if( cookie.bv_len != sizeof( reqcookie ) ) {
1187                         /* bad cookie */
1188                         rs->sr_text = "paged results cookie is invalid";
1189                         rc = LDAP_PROTOCOL_ERROR;
1190                         goto done;
1191                 }
1192
1193                 AC_MEMCPY( &reqcookie, cookie.bv_val, sizeof( reqcookie ));
1194
1195                 if ( reqcookie > ps->ps_cookie ) {
1196                         /* bad cookie */
1197                         rs->sr_text = "paged results cookie is invalid";
1198                         rc = LDAP_PROTOCOL_ERROR;
1199                         goto done;
1200
1201                 } else if ( reqcookie < ps->ps_cookie ) {
1202                         rs->sr_text = "paged results cookie is invalid or old";
1203                         rc = LDAP_UNWILLING_TO_PERFORM;
1204                         goto done;
1205                 }
1206
1207         } else {
1208                 /* Initial request.  Initialize state. */
1209 #if 0
1210                 if ( op->o_conn->c_pagedresults_state.ps_cookie != 0 ) {
1211                         /* There's another pagedResults control on the
1212                          * same connection; reject new pagedResults controls 
1213                          * (allowed by RFC2696) */
1214                         rs->sr_text = "paged results cookie unavailable; try later";
1215                         rc = LDAP_UNWILLING_TO_PERFORM;
1216                         goto done;
1217                 }
1218 #endif
1219                 ps->ps_cookie = 0;
1220                 ps->ps_count = 0;
1221         }
1222
1223 done:;
1224         (void)ber_free( ber, 1 );
1225
1226         return rc;
1227 }
1228
1229 static void
1230 send_paged_response( 
1231         Operation       *op,
1232         SlapReply       *rs,
1233         ID              *lastid,
1234         int             tentries )
1235 {
1236         LDAPControl     ctrl, *ctrls[2];
1237         BerElementBuffer berbuf;
1238         BerElement      *ber = (BerElement *)&berbuf;
1239         PagedResultsCookie respcookie;
1240         struct berval cookie;
1241
1242         Debug(LDAP_DEBUG_ARGS,
1243                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1244                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1245
1246         BER_BVZERO( &ctrl.ldctl_value );
1247         ctrls[0] = &ctrl;
1248         ctrls[1] = NULL;
1249
1250         ber_init2( ber, NULL, LBER_USE_DER );
1251
1252         if ( lastid ) {
1253                 respcookie = ( PagedResultsCookie )(*lastid);
1254                 cookie.bv_len = sizeof( respcookie );
1255                 cookie.bv_val = (char *)&respcookie;
1256
1257         } else {
1258                 respcookie = ( PagedResultsCookie )0;
1259                 BER_BVSTR( &cookie, "" );
1260         }
1261
1262         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1263         op->o_conn->c_pagedresults_state.ps_count =
1264                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
1265                 rs->sr_nentries;
1266
1267         /* return size of 0 -- no estimate */
1268         ber_printf( ber, "{iO}", 0, &cookie ); 
1269
1270         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1271                 goto done;
1272         }
1273
1274         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1275         ctrls[0]->ldctl_iscritical = 0;
1276
1277         rs->sr_ctrls = ctrls;
1278         rs->sr_err = LDAP_SUCCESS;
1279         send_ldap_result( op, rs );
1280         rs->sr_ctrls = NULL;
1281
1282 done:
1283         (void) ber_free_buf( ber );
1284 }
1285