]> git.sur5r.net Git - openldap/blob - servers/slapd/back-mdb/search.c
2009f006a256caf48fc1d67a0fef5deba010b932
[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;
288         Entry           *matched = NULL;
289         AttributeName   *attrs;
290         struct berval   realbase = BER_BVNULL;
291         slap_mask_t     mask;
292         time_t          stoptime;
293         int             manageDSAit;
294         int             tentries = 0;
295
296         mdb_op_info     opinfo = {0}, *moi = &opinfo;
297         MDB_txn                 *ltid = NULL;
298         MDB_cursor      *idcursor = NULL;
299
300         Debug( LDAP_DEBUG_TRACE, "=> " LDAP_XSTRING(mdb_search) "\n", 0, 0, 0);
301         attrs = op->oq_search.rs_attrs;
302
303         manageDSAit = get_manageDSAit( op );
304
305         rs->sr_err = mdb_opinfo_get( op, mdb, 1, &moi );
306         switch(rs->sr_err) {
307         case 0:
308                 break;
309         default:
310                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
311                 return rs->sr_err;
312         }
313
314         ltid = moi->moi_txn;
315
316         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
317                 MDB_IDL_ZERO(candidates);
318         }
319 dn2entry_retry:
320         /* get entry with reader lock */
321         rs->sr_err = mdb_dn2entry( op, ltid, &op->o_req_ndn, &e, 1 );
322
323         switch(rs->sr_err) {
324         case MDB_NOTFOUND:
325                 matched = e;
326                 e = NULL;
327                 break;
328         case 0:
329                 break;
330         case LDAP_BUSY:
331                 send_ldap_error( op, rs, LDAP_BUSY, "ldap server busy" );
332                 goto done;
333         default:
334                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
335                 goto done;
336         }
337
338         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
339                 if ( matched && is_entry_alias( matched )) {
340                         struct berval stub;
341
342                         stub.bv_val = op->o_req_ndn.bv_val;
343                         stub.bv_len = op->o_req_ndn.bv_len - matched->e_nname.bv_len - 1;
344                         e = deref_base( op, rs, matched, &matched, ltid,
345                                 candidates, NULL );
346                         if ( e ) {
347                                 build_new_dn( &op->o_req_ndn, &e->e_nname, &stub,
348                                         op->o_tmpmemctx );
349                                 mdb_entry_return (e);
350                                 matched = NULL;
351                                 goto dn2entry_retry;
352                         }
353                 } else if ( e && is_entry_alias( e )) {
354                         e = deref_base( op, rs, e, &matched, ltid,
355                                 candidates, NULL );
356                 }
357         }
358
359         if ( e == NULL ) {
360                 struct berval matched_dn = BER_BVNULL;
361
362                 if ( matched != NULL ) {
363                         BerVarray erefs = NULL;
364
365                         /* return referral only if "disclose"
366                          * is granted on the object */
367                         if ( ! access_allowed( op, matched,
368                                                 slap_schema.si_ad_entry,
369                                                 NULL, ACL_DISCLOSE, NULL ) )
370                         {
371                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
372
373                         } else {
374                                 ber_dupbv( &matched_dn, &matched->e_name );
375
376                                 erefs = is_entry_referral( matched )
377                                         ? get_entry_referrals( op, matched )
378                                         : NULL;
379                                 if ( rs->sr_err == MDB_NOTFOUND )
380                                         rs->sr_err = LDAP_REFERRAL;
381                                 rs->sr_matched = matched_dn.bv_val;
382                         }
383
384                         mdb_entry_return (matched);
385                         matched = NULL;
386
387                         if ( erefs ) {
388                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
389                                         &op->o_req_dn, op->oq_search.rs_scope );
390                                 ber_bvarray_free( erefs );
391                         }
392
393                 } else {
394                         rs->sr_ref = referral_rewrite( default_referral,
395                                 NULL, &op->o_req_dn, op->oq_search.rs_scope );
396                         rs->sr_err = rs->sr_ref != NULL ? LDAP_REFERRAL : LDAP_NO_SUCH_OBJECT;
397                 }
398
399                 send_ldap_result( op, rs );
400
401                 if ( rs->sr_ref ) {
402                         ber_bvarray_free( rs->sr_ref );
403                         rs->sr_ref = NULL;
404                 }
405                 if ( !BER_BVISNULL( &matched_dn ) ) {
406                         ber_memfree( matched_dn.bv_val );
407                         rs->sr_matched = NULL;
408                 }
409                 goto done;
410         }
411
412         /* NOTE: __NEW__ "search" access is required
413          * on searchBase object */
414         if ( ! access_allowed_mask( op, e, slap_schema.si_ad_entry,
415                                 NULL, ACL_SEARCH, NULL, &mask ) )
416         {
417                 if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
418                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
419                 } else {
420                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
421                 }
422
423                 mdb_entry_return(e);
424                 send_ldap_result( op, rs );
425                 goto done;
426         }
427
428         if ( !manageDSAit && is_entry_referral( e ) ) {
429                 /* entry is a referral */
430                 struct berval matched_dn = BER_BVNULL;
431                 BerVarray erefs = NULL;
432                 
433                 ber_dupbv( &matched_dn, &e->e_name );
434                 erefs = get_entry_referrals( op, e );
435
436                 rs->sr_err = LDAP_REFERRAL;
437
438                 mdb_entry_return( e );
439                 e = NULL;
440
441                 if ( erefs ) {
442                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
443                                 &op->o_req_dn, op->oq_search.rs_scope );
444                         ber_bvarray_free( erefs );
445
446                         if ( !rs->sr_ref ) {
447                                 rs->sr_text = "bad_referral object";
448                         }
449                 }
450
451                 Debug( LDAP_DEBUG_TRACE,
452                         LDAP_XSTRING(mdb_search) ": entry is referral\n",
453                         0, 0, 0 );
454
455                 rs->sr_matched = matched_dn.bv_val;
456                 send_ldap_result( op, rs );
457
458                 ber_bvarray_free( rs->sr_ref );
459                 rs->sr_ref = NULL;
460                 ber_memfree( matched_dn.bv_val );
461                 rs->sr_matched = NULL;
462                 goto done;
463         }
464
465         if ( get_assert( op ) &&
466                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
467         {
468                 rs->sr_err = LDAP_ASSERTION_FAILED;
469                 mdb_entry_return(e);
470                 send_ldap_result( op, rs );
471                 goto done;
472         }
473
474         /* compute it anyway; root does not use it */
475         stoptime = op->o_time + op->ors_tlimit;
476
477         /* need normalized dn below */
478         ber_dupbv( &realbase, &e->e_nname );
479
480         /* Copy info to base, must free entry before accessing the database
481          * in search_candidates, to avoid deadlocks.
482          */
483         base.e_private = e->e_private;
484         base.e_nname = realbase;
485         base.e_id = e->e_id;
486
487         mdb_entry_return(e);
488         e = NULL;
489
490         /* select candidates */
491         if ( op->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
492                 rs->sr_err = base_candidate( op->o_bd, &base, candidates );
493
494         } else {
495                 MDB_IDL_ZERO( candidates );
496                 MDB_IDL_ZERO( scopes );
497                 mdb_idl_insert( scopes, base.e_id );
498                 rs->sr_err = search_candidates( op, rs, &base,
499                         ltid, candidates, scopes );
500         }
501
502         /* start cursor at beginning of candidates.
503          */
504         cursor = 0;
505
506         if ( candidates[0] == 0 ) {
507                 Debug( LDAP_DEBUG_TRACE,
508                         LDAP_XSTRING(mdb_search) ": no candidates\n",
509                         0, 0, 0 );
510
511                 goto nochange;
512         }
513
514         /* if not root and candidates exceed to-be-checked entries, abort */
515         if ( op->ors_limit      /* isroot == FALSE */ &&
516                 op->ors_limit->lms_s_unchecked != -1 &&
517                 MDB_IDL_N(candidates) > (unsigned) op->ors_limit->lms_s_unchecked )
518         {
519                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
520                 send_ldap_result( op, rs );
521                 rs->sr_err = LDAP_SUCCESS;
522                 goto done;
523         }
524
525         if ( op->ors_limit == NULL      /* isroot == TRUE */ ||
526                 !op->ors_limit->lms_s_pr_hide )
527         {
528                 tentries = MDB_IDL_N(candidates);
529         }
530
531         if ( get_pagedresults( op ) > SLAP_CONTROL_IGNORED ) {
532                 PagedResultsState *ps = op->o_pagedresults_state;
533                 /* deferred cookie parsing */
534                 rs->sr_err = parse_paged_cookie( op, rs );
535                 if ( rs->sr_err != LDAP_SUCCESS ) {
536                         send_ldap_result( op, rs );
537                         goto done;
538                 }
539
540                 cursor = (ID) ps->ps_cookie;
541                 if ( cursor && ps->ps_size == 0 ) {
542                         rs->sr_err = LDAP_SUCCESS;
543                         rs->sr_text = "search abandoned by pagedResult size=0";
544                         send_ldap_result( op, rs );
545                         goto done;
546                 }
547                 id = mdb_idl_first( candidates, &cursor );
548                 if ( id == NOID ) {
549                         Debug( LDAP_DEBUG_TRACE, 
550                                 LDAP_XSTRING(mdb_search)
551                                 ": no paged results candidates\n",
552                                 0, 0, 0 );
553                         send_paged_response( op, rs, &lastid, 0 );
554
555                         rs->sr_err = LDAP_OTHER;
556                         goto done;
557                 }
558                 if ( id == (ID)ps->ps_cookie )
559                         id = mdb_idl_next( candidates, &cursor );
560                 goto loop_begin;
561         }
562
563         for ( id = mdb_idl_first( candidates, &cursor );
564                   id != NOID ; id = mdb_idl_next( candidates, &cursor ) )
565         {
566                 int scopeok;
567
568 loop_begin:
569
570                 /* check for abandon */
571                 if ( op->o_abandon ) {
572                         rs->sr_err = SLAPD_ABANDON;
573                         send_ldap_result( op, rs );
574                         goto done;
575                 }
576
577                 /* mostly needed by internal searches,
578                  * e.g. related to syncrepl, for whom
579                  * abandon does not get set... */
580                 if ( slapd_shutdown ) {
581                         rs->sr_err = LDAP_UNAVAILABLE;
582                         send_ldap_disconnect( op, rs );
583                         goto done;
584                 }
585
586                 /* check time limit */
587                 if ( op->ors_tlimit != SLAP_NO_LIMIT
588                                 && slap_get_time() > stoptime )
589                 {
590                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
591                         rs->sr_ref = rs->sr_v2ref;
592                         send_ldap_result( op, rs );
593                         rs->sr_err = LDAP_SUCCESS;
594                         goto done;
595                 }
596
597                 /* get the entry */
598                 rs->sr_err = mdb_id2entry( op, ltid, id, &e );
599
600                 if (rs->sr_err == LDAP_BUSY) {
601                         rs->sr_text = "ldap server busy";
602                         send_ldap_result( op, rs );
603                         goto done;
604
605                 } else if ( rs->sr_err == LDAP_OTHER ) {
606                         rs->sr_text = "internal error";
607                         send_ldap_result( op, rs );
608                         goto done;
609                 }
610
611                 if ( e == NULL ) {
612                         if( !MDB_IDL_IS_RANGE(candidates) ) {
613                                 /* only complain for non-range IDLs */
614                                 Debug( LDAP_DEBUG_TRACE,
615                                         LDAP_XSTRING(mdb_search)
616                                         ": candidate %ld not found\n",
617                                         (long) id, 0, 0 );
618                         } else {
619                                 /* get the next ID from the DB */
620                                 rs->sr_err = mdb_get_nextid( mdb, ltid, &cursor );
621                                 if ( rs->sr_err == MDB_NOTFOUND ) {
622                                         break;
623                                 }
624                                 if ( rs->sr_err ) {
625                                         rs->sr_err = LDAP_OTHER;
626                                         rs->sr_text = "internal error in get_nextid";
627                                         send_ldap_result( op, rs );
628                                         goto done;
629                                 }
630                                 cursor--;
631                         }
632
633                         goto loop_continue;
634                 }
635
636                 if ( is_entry_subentry( e ) ) {
637                         if( op->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
638                                 if(!get_subentries_visibility( op )) {
639                                         /* only subentries are visible */
640                                         goto loop_continue;
641                                 }
642
643                         } else if ( get_subentries( op ) &&
644                                 !get_subentries_visibility( op ))
645                         {
646                                 /* only subentries are visible */
647                                 goto loop_continue;
648                         }
649
650                 } else if ( get_subentries_visibility( op )) {
651                         /* only subentries are visible */
652                         goto loop_continue;
653                 }
654
655                 /* Does this candidate actually satisfy the search scope?
656                  */
657                 scopeok = 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                         if ( mdb_idscopes( op, ltid, &idcursor, id, scopes ) == MDB_SUCCESS ) scopeok = 1;
677                         break;
678                 }
679
680                 /* aliases were already dereferenced in candidate list */
681                 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
682                         /* but if the search base is an alias, and we didn't
683                          * deref it when finding, return it.
684                          */
685                         if ( is_entry_alias(e) &&
686                                 ((op->ors_deref & LDAP_DEREF_FINDING) ||
687                                         !bvmatch(&e->e_nname, &op->o_req_ndn)))
688                         {
689                                 goto loop_continue;
690                         }
691                 }
692
693                 /* Not in scope, ignore it */
694                 if ( !scopeok )
695                 {
696                         Debug( LDAP_DEBUG_TRACE,
697                                 LDAP_XSTRING(mdb_search)
698                                 ": %ld scope not okay\n",
699                                 (long) id, 0, 0 );
700                         goto loop_continue;
701                 }
702
703                 if ( !manageDSAit && is_entry_glue( e )) {
704                         goto loop_continue;
705                 }
706
707                 mdb_id2name( op, ltid, &idcursor, e->e_id,
708                         &e->e_name, &e->e_nname );
709
710                 /*
711                  * if it's a referral, add it to the list of referrals. only do
712                  * this for non-base searches, and don't check the filter
713                  * explicitly here since it's only a candidate anyway.
714                  */
715                 if ( !manageDSAit && op->oq_search.rs_scope != LDAP_SCOPE_BASE
716                         && is_entry_referral( e ) )
717                 {
718                         BerVarray erefs = get_entry_referrals( op, e );
719                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
720                                 op->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
721                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
722
723                         rs->sr_entry = e;
724                         rs->sr_flags = 0;
725
726                         send_search_reference( op, rs );
727
728                         mdb_entry_return( e );
729                         rs->sr_entry = NULL;
730                         e = NULL;
731
732                         ber_bvarray_free( rs->sr_ref );
733                         ber_bvarray_free( erefs );
734                         rs->sr_ref = NULL;
735
736                         goto loop_continue;
737                 }
738
739                 /* if it matches the filter and scope, send it */
740                 rs->sr_err = test_filter( op, e, op->oq_search.rs_filter );
741
742                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
743                         /* check size limit */
744                         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
745                                 if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
746                                         mdb_entry_return( e );
747                                         e = NULL;
748                                         send_paged_response( op, rs, &lastid, tentries );
749                                         goto done;
750                                 }
751                                 lastid = id;
752                         }
753
754                         if (e) {
755                                 /* safe default */
756                                 rs->sr_attrs = op->oq_search.rs_attrs;
757                                 rs->sr_operational_attrs = NULL;
758                                 rs->sr_ctrls = NULL;
759                                 rs->sr_entry = e;
760                                 RS_ASSERT( e->e_private != NULL );
761                                 rs->sr_flags = 0;
762                                 rs->sr_err = LDAP_SUCCESS;
763                                 rs->sr_err = send_search_entry( op, rs );
764                                 rs->sr_attrs = NULL;
765                                 rs->sr_entry = NULL;
766                                 mdb_entry_return( e );
767                                 e = NULL;
768
769                                 switch ( rs->sr_err ) {
770                                 case LDAP_SUCCESS:      /* entry sent ok */
771                                         break;
772                                 default:                /* entry not sent */
773                                         break;
774                                 case LDAP_UNAVAILABLE:
775                                 case LDAP_SIZELIMIT_EXCEEDED:
776                                         if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
777                                                 rs->sr_ref = rs->sr_v2ref;
778                                                 send_ldap_result( op, rs );
779                                                 rs->sr_err = LDAP_SUCCESS;
780
781                                         } else {
782                                                 rs->sr_err = LDAP_OTHER;
783                                         }
784                                         goto done;
785                                 }
786                         }
787
788                 } else {
789                         Debug( LDAP_DEBUG_TRACE,
790                                 LDAP_XSTRING(mdb_search)
791                                 ": %ld does not match filter\n",
792                                 (long) id, 0, 0 );
793                 }
794
795 loop_continue:
796                 if( e != NULL ) {
797                         /* free reader lock */
798                         mdb_entry_return( e );
799                         RS_ASSERT( rs->sr_entry == NULL );
800                         e = NULL;
801                         rs->sr_entry = NULL;
802                 }
803         }
804
805 nochange:
806         rs->sr_ctrls = NULL;
807         rs->sr_ref = rs->sr_v2ref;
808         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
809         rs->sr_rspoid = NULL;
810         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
811                 send_paged_response( op, rs, NULL, 0 );
812         } else {
813                 send_ldap_result( op, rs );
814         }
815
816         rs->sr_err = LDAP_SUCCESS;
817
818 done:
819         if ( moi == &opinfo ) {
820                 mdb_txn_reset( moi->moi_txn );
821                 LDAP_SLIST_REMOVE( &op->o_extra, &moi->moi_oe, OpExtra, oe_next );
822         }
823         if( idcursor )
824                 mdb_cursor_close( idcursor );
825         if( rs->sr_v2ref ) {
826                 ber_bvarray_free( rs->sr_v2ref );
827                 rs->sr_v2ref = NULL;
828         }
829         if( realbase.bv_val ) ch_free( realbase.bv_val );
830
831         return rs->sr_err;
832 }
833
834
835 static int base_candidate(
836         BackendDB       *be,
837         Entry   *e,
838         ID              *ids )
839 {
840         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
841                 e->e_nname.bv_val, (long) e->e_id, 0);
842
843         ids[0] = 1;
844         ids[1] = e->e_id;
845         return 0;
846 }
847
848 /* Look for "objectClass Present" in this filter.
849  * Also count depth of filter tree while we're at it.
850  */
851 static int oc_filter(
852         Filter *f,
853         int cur,
854         int *max )
855 {
856         int rc = 0;
857
858         assert( f != NULL );
859
860         if( cur > *max ) *max = cur;
861
862         switch( f->f_choice ) {
863         case LDAP_FILTER_PRESENT:
864                 if (f->f_desc == slap_schema.si_ad_objectClass) {
865                         rc = 1;
866                 }
867                 break;
868
869         case LDAP_FILTER_AND:
870         case LDAP_FILTER_OR:
871                 cur++;
872                 for ( f=f->f_and; f; f=f->f_next ) {
873                         (void) oc_filter(f, cur, max);
874                 }
875                 break;
876
877         default:
878                 break;
879         }
880         return rc;
881 }
882
883 static void search_stack_free( void *key, void *data )
884 {
885         ber_memfree_x(data, NULL);
886 }
887
888 static void *search_stack( Operation *op )
889 {
890         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
891         void *ret = NULL;
892
893         if ( op->o_threadctx ) {
894                 ldap_pvt_thread_pool_getkey( op->o_threadctx, (void *)search_stack,
895                         &ret, NULL );
896         } else {
897                 ret = mdb->mi_search_stack;
898         }
899
900         if ( !ret ) {
901                 ret = ch_malloc( mdb->mi_search_stack_depth * MDB_IDL_UM_SIZE
902                         * sizeof( ID ) );
903                 if ( op->o_threadctx ) {
904                         ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)search_stack,
905                                 ret, search_stack_free, NULL, NULL );
906                 } else {
907                         mdb->mi_search_stack = ret;
908                 }
909         }
910         return ret;
911 }
912
913 static int search_candidates(
914         Operation *op,
915         SlapReply *rs,
916         Entry *e,
917         MDB_txn *txn,
918         ID      *ids,
919         ID      *scopes )
920 {
921         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
922         int rc, depth = 1;
923         Filter          *f, rf, xf, nf, sf;
924         ID              *stack;
925         AttributeAssertion aa_ref = ATTRIBUTEASSERTION_INIT;
926         AttributeAssertion aa_subentry = ATTRIBUTEASSERTION_INIT;
927
928         /*
929          * This routine takes as input a filter (user-filter)
930          * and rewrites it as follows:
931          *      (&(scope=DN)[(objectClass=subentry)]
932          *              (|[(objectClass=referral)](user-filter))
933          */
934
935         Debug(LDAP_DEBUG_TRACE,
936                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
937                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
938
939         f = op->oq_search.rs_filter;
940
941         /* If the user's filter uses objectClass=*,
942          * these clauses are redundant.
943          */
944         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
945                 && !get_subentries_visibility(op)) {
946                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
947                         /* match referral objects */
948                         struct berval bv_ref = BER_BVC( "referral" );
949                         rf.f_choice = LDAP_FILTER_EQUALITY;
950                         rf.f_ava = &aa_ref;
951                         rf.f_av_desc = slap_schema.si_ad_objectClass;
952                         rf.f_av_value = bv_ref;
953                         rf.f_next = f;
954                         xf.f_or = &rf;
955                         xf.f_choice = LDAP_FILTER_OR;
956                         xf.f_next = NULL;
957                         f = &xf;
958                         depth++;
959                 }
960         }
961
962         if( get_subentries_visibility( op ) ) {
963                 struct berval bv_subentry = BER_BVC( "subentry" );
964                 sf.f_choice = LDAP_FILTER_EQUALITY;
965                 sf.f_ava = &aa_subentry;
966                 sf.f_av_desc = slap_schema.si_ad_objectClass;
967                 sf.f_av_value = bv_subentry;
968                 sf.f_next = f;
969                 nf.f_choice = LDAP_FILTER_AND;
970                 nf.f_and = &sf;
971                 nf.f_next = NULL;
972                 f = &nf;
973                 depth++;
974         }
975
976         /* Allocate IDL stack, plus 1 more for former tmp */
977         if ( depth+1 > mdb->mi_search_stack_depth ) {
978                 stack = ch_malloc( (depth + 1) * MDB_IDL_UM_SIZE * sizeof( ID ) );
979         } else {
980                 stack = search_stack( op );
981         }
982
983         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
984                 rc = search_aliases( op, rs, e, txn, scopes, stack );
985         } else {
986                 rc = LDAP_SUCCESS;
987         }
988
989         if ( rc == LDAP_SUCCESS ) {
990                 rc = mdb_filter_candidates( op, txn, f, ids,
991                         stack, stack+MDB_IDL_UM_SIZE );
992         }
993
994         if ( depth+1 > mdb->mi_search_stack_depth ) {
995                 ch_free( stack );
996         }
997
998         if( rc ) {
999                 Debug(LDAP_DEBUG_TRACE,
1000                         "mdb_search_candidates: failed (rc=%d)\n",
1001                         rc, NULL, NULL );
1002
1003         } else {
1004                 Debug(LDAP_DEBUG_TRACE,
1005                         "mdb_search_candidates: id=%ld first=%ld last=%ld\n",
1006                         (long) ids[0],
1007                         (long) MDB_IDL_FIRST(ids),
1008                         (long) MDB_IDL_LAST(ids) );
1009         }
1010
1011         return rc;
1012 }
1013
1014 static int
1015 parse_paged_cookie( Operation *op, SlapReply *rs )
1016 {
1017         int             rc = LDAP_SUCCESS;
1018         PagedResultsState *ps = op->o_pagedresults_state;
1019
1020         /* this function must be invoked only if the pagedResults
1021          * control has been detected, parsed and partially checked
1022          * by the frontend */
1023         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
1024
1025         /* cookie decoding/checks deferred to backend... */
1026         if ( ps->ps_cookieval.bv_len ) {
1027                 PagedResultsCookie reqcookie;
1028                 if( ps->ps_cookieval.bv_len != sizeof( reqcookie ) ) {
1029                         /* bad cookie */
1030                         rs->sr_text = "paged results cookie is invalid";
1031                         rc = LDAP_PROTOCOL_ERROR;
1032                         goto done;
1033                 }
1034
1035                 AC_MEMCPY( &reqcookie, ps->ps_cookieval.bv_val, sizeof( reqcookie ));
1036
1037                 if ( reqcookie > ps->ps_cookie ) {
1038                         /* bad cookie */
1039                         rs->sr_text = "paged results cookie is invalid";
1040                         rc = LDAP_PROTOCOL_ERROR;
1041                         goto done;
1042
1043                 } else if ( reqcookie < ps->ps_cookie ) {
1044                         rs->sr_text = "paged results cookie is invalid or old";
1045                         rc = LDAP_UNWILLING_TO_PERFORM;
1046                         goto done;
1047                 }
1048
1049         } else {
1050                 /* we're going to use ps_cookie */
1051                 op->o_conn->c_pagedresults_state.ps_cookie = 0;
1052         }
1053
1054 done:;
1055
1056         return rc;
1057 }
1058
1059 static void
1060 send_paged_response( 
1061         Operation       *op,
1062         SlapReply       *rs,
1063         ID              *lastid,
1064         int             tentries )
1065 {
1066         LDAPControl     *ctrls[2];
1067         BerElementBuffer berbuf;
1068         BerElement      *ber = (BerElement *)&berbuf;
1069         PagedResultsCookie respcookie;
1070         struct berval cookie;
1071
1072         Debug(LDAP_DEBUG_ARGS,
1073                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1074                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1075
1076         ctrls[1] = NULL;
1077
1078         ber_init2( ber, NULL, LBER_USE_DER );
1079
1080         if ( lastid ) {
1081                 respcookie = ( PagedResultsCookie )(*lastid);
1082                 cookie.bv_len = sizeof( respcookie );
1083                 cookie.bv_val = (char *)&respcookie;
1084
1085         } else {
1086                 respcookie = ( PagedResultsCookie )0;
1087                 BER_BVSTR( &cookie, "" );
1088         }
1089
1090         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1091         op->o_conn->c_pagedresults_state.ps_count =
1092                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
1093                 rs->sr_nentries;
1094
1095         /* return size of 0 -- no estimate */
1096         ber_printf( ber, "{iO}", 0, &cookie ); 
1097
1098         ctrls[0] = op->o_tmpalloc( sizeof(LDAPControl), op->o_tmpmemctx );
1099         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1100                 goto done;
1101         }
1102
1103         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1104         ctrls[0]->ldctl_iscritical = 0;
1105
1106         slap_add_ctrls( op, rs, ctrls );
1107         rs->sr_err = LDAP_SUCCESS;
1108         send_ldap_result( op, rs );
1109
1110 done:
1111         (void) ber_free_buf( ber );
1112 }