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