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