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