]> git.sur5r.net Git - openldap/blob - servers/slapd/back-mdb/search.c
Merge remote-tracking branch 'origin/mdb.master' into OPENLDAP_REL_ENG_2_4
[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 int
320 mdb_search( Operation *op, SlapReply *rs )
321 {
322         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
323         ID              id, cursor, nsubs, ncand, cscope;
324         ID              lastid = NOID;
325         ID              candidates[MDB_IDL_UM_SIZE];
326         ID              iscopes[MDB_IDL_DB_SIZE];
327         ID2             *scopes;
328         void    *stack;
329         Entry           *e = NULL, *base = NULL;
330         Entry           *matched = NULL;
331         AttributeName   *attrs;
332         slap_mask_t     mask;
333         time_t          stoptime;
334         int             manageDSAit;
335         int             tentries = 0;
336         IdScopes        isc;
337         MDB_cursor      *mci, *mcd;
338
339         mdb_op_info     opinfo = {{{0}}}, *moi = &opinfo;
340         MDB_txn                 *ltid = NULL;
341
342         Debug( LDAP_DEBUG_TRACE, "=> " LDAP_XSTRING(mdb_search) "\n", 0, 0, 0);
343         attrs = op->oq_search.rs_attrs;
344
345         manageDSAit = get_manageDSAit( op );
346
347         rs->sr_err = mdb_opinfo_get( op, mdb, 1, &moi );
348         switch(rs->sr_err) {
349         case 0:
350                 break;
351         default:
352                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
353                 return rs->sr_err;
354         }
355
356         ltid = moi->moi_txn;
357
358         rs->sr_err = mdb_cursor_open( ltid, mdb->mi_id2entry, &mci );
359         if ( rs->sr_err ) {
360                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
361                 return rs->sr_err;
362         }
363
364         rs->sr_err = mdb_cursor_open( ltid, mdb->mi_dn2id, &mcd );
365         if ( rs->sr_err ) {
366                 mdb_cursor_close( mci );
367                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
368                 return rs->sr_err;
369         }
370
371         scopes = scope_chunk_get( op );
372         stack = search_stack( op );
373         isc.mt = ltid;
374         isc.mc = mcd;
375         isc.scopes = scopes;
376         isc.oscope = op->ors_scope;
377         isc.sctmp = stack;
378
379         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
380                 MDB_IDL_ZERO(candidates);
381         }
382 dn2entry_retry:
383         /* get entry with reader lock */
384         rs->sr_err = mdb_dn2entry( op, ltid, mcd, &op->o_req_ndn, &e, &nsubs, 1 );
385
386         switch(rs->sr_err) {
387         case MDB_NOTFOUND:
388                 matched = e;
389                 e = NULL;
390                 break;
391         case 0:
392                 break;
393         case LDAP_BUSY:
394                 send_ldap_error( op, rs, LDAP_BUSY, "ldap server busy" );
395                 goto done;
396         default:
397                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
398                 goto done;
399         }
400
401         if ( op->ors_deref & LDAP_DEREF_FINDING ) {
402                 if ( matched && is_entry_alias( matched )) {
403                         struct berval stub;
404
405                         stub.bv_val = op->o_req_ndn.bv_val;
406                         stub.bv_len = op->o_req_ndn.bv_len - matched->e_nname.bv_len - 1;
407                         e = deref_base( op, rs, matched, &matched, ltid,
408                                 candidates, NULL );
409                         if ( e ) {
410                                 build_new_dn( &op->o_req_ndn, &e->e_nname, &stub,
411                                         op->o_tmpmemctx );
412                                 mdb_entry_return(op, e);
413                                 matched = NULL;
414                                 goto dn2entry_retry;
415                         }
416                 } else if ( e && is_entry_alias( e )) {
417                         e = deref_base( op, rs, e, &matched, ltid,
418                                 candidates, NULL );
419                 }
420         }
421
422         if ( e == NULL ) {
423                 struct berval matched_dn = BER_BVNULL;
424
425                 if ( matched != NULL ) {
426                         BerVarray erefs = NULL;
427
428                         /* return referral only if "disclose"
429                          * is granted on the object */
430                         if ( ! access_allowed( op, matched,
431                                                 slap_schema.si_ad_entry,
432                                                 NULL, ACL_DISCLOSE, NULL ) )
433                         {
434                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
435
436                         } else {
437                                 ber_dupbv( &matched_dn, &matched->e_name );
438
439                                 erefs = is_entry_referral( matched )
440                                         ? get_entry_referrals( op, matched )
441                                         : NULL;
442                                 if ( rs->sr_err == MDB_NOTFOUND )
443                                         rs->sr_err = LDAP_REFERRAL;
444                                 rs->sr_matched = matched_dn.bv_val;
445                         }
446
447                         mdb_entry_return(op, matched);
448                         matched = NULL;
449
450                         if ( erefs ) {
451                                 rs->sr_ref = referral_rewrite( erefs, &matched_dn,
452                                         &op->o_req_dn, op->oq_search.rs_scope );
453                                 ber_bvarray_free( erefs );
454                         }
455
456                 } else {
457                         rs->sr_ref = referral_rewrite( default_referral,
458                                 NULL, &op->o_req_dn, op->oq_search.rs_scope );
459                         rs->sr_err = rs->sr_ref != NULL ? LDAP_REFERRAL : LDAP_NO_SUCH_OBJECT;
460                 }
461
462                 send_ldap_result( op, rs );
463
464                 if ( rs->sr_ref ) {
465                         ber_bvarray_free( rs->sr_ref );
466                         rs->sr_ref = NULL;
467                 }
468                 if ( !BER_BVISNULL( &matched_dn ) ) {
469                         ber_memfree( matched_dn.bv_val );
470                         rs->sr_matched = NULL;
471                 }
472                 goto done;
473         }
474
475         /* NOTE: __NEW__ "search" access is required
476          * on searchBase object */
477         if ( ! access_allowed_mask( op, e, slap_schema.si_ad_entry,
478                                 NULL, ACL_SEARCH, NULL, &mask ) )
479         {
480                 if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
481                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
482                 } else {
483                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
484                 }
485
486                 mdb_entry_return( op,e);
487                 send_ldap_result( op, rs );
488                 goto done;
489         }
490
491         if ( !manageDSAit && is_entry_referral( e ) ) {
492                 /* entry is a referral */
493                 struct berval matched_dn = BER_BVNULL;
494                 BerVarray erefs = NULL;
495                 
496                 ber_dupbv( &matched_dn, &e->e_name );
497                 erefs = get_entry_referrals( op, e );
498
499                 rs->sr_err = LDAP_REFERRAL;
500
501                 mdb_entry_return( op, e );
502                 e = NULL;
503
504                 if ( erefs ) {
505                         rs->sr_ref = referral_rewrite( erefs, &matched_dn,
506                                 &op->o_req_dn, op->oq_search.rs_scope );
507                         ber_bvarray_free( erefs );
508
509                         if ( !rs->sr_ref ) {
510                                 rs->sr_text = "bad_referral object";
511                         }
512                 }
513
514                 Debug( LDAP_DEBUG_TRACE,
515                         LDAP_XSTRING(mdb_search) ": entry is referral\n",
516                         0, 0, 0 );
517
518                 rs->sr_matched = matched_dn.bv_val;
519                 send_ldap_result( op, rs );
520
521                 ber_bvarray_free( rs->sr_ref );
522                 rs->sr_ref = NULL;
523                 ber_memfree( matched_dn.bv_val );
524                 rs->sr_matched = NULL;
525                 goto done;
526         }
527
528         if ( get_assert( op ) &&
529                 ( test_filter( op, e, get_assertion( op )) != LDAP_COMPARE_TRUE ))
530         {
531                 rs->sr_err = LDAP_ASSERTION_FAILED;
532                 mdb_entry_return( op,e);
533                 send_ldap_result( op, rs );
534                 goto done;
535         }
536
537         /* compute it anyway; root does not use it */
538         stoptime = op->o_time + op->ors_tlimit;
539
540         base = e;
541
542         e = NULL;
543
544         /* select candidates */
545         if ( op->oq_search.rs_scope == LDAP_SCOPE_BASE ) {
546                 rs->sr_err = base_candidate( op->o_bd, base, candidates );
547                 scopes[0].mid = 0;
548                 ncand = 1;
549         } else {
550                 if ( op->ors_scope == LDAP_SCOPE_ONELEVEL ) {
551                         size_t nkids;
552                         MDB_val key, data;
553                         key.mv_data = &base->e_id;
554                         key.mv_size = sizeof( ID );
555                         mdb_cursor_get( mcd, &key, &data, MDB_SET );
556                         mdb_cursor_count( mcd, &nkids );
557                         nsubs = nkids - 1;
558                 } else if ( !base->e_id ) {
559                         /* we don't maintain nsubs for entryID 0.
560                          * just grab entry count from id2entry stat
561                          */
562                         MDB_stat ms;
563                         mdb_stat( ltid, mdb->mi_id2entry, &ms );
564                         nsubs = ms.ms_entries;
565                 }
566                 MDB_IDL_ZERO( candidates );
567                 scopes[0].mid = 1;
568                 scopes[1].mid = base->e_id;
569                 scopes[1].mval.mv_data = NULL;
570                 rs->sr_err = search_candidates( op, rs, base,
571                         ltid, mci, candidates, scopes, stack );
572                 ncand = MDB_IDL_N( candidates );
573                 if ( !base->e_id || ncand == NOID ) {
574                         /* grab entry count from id2entry stat
575                          */
576                         MDB_stat ms;
577                         mdb_stat( ltid, mdb->mi_id2entry, &ms );
578                         if ( !base->e_id )
579                                 nsubs = ms.ms_entries;
580                         if ( ncand == NOID )
581                                 ncand = ms.ms_entries;
582                 }
583         }
584
585         /* start cursor at beginning of candidates.
586          */
587         cursor = 0;
588
589         if ( candidates[0] == 0 ) {
590                 Debug( LDAP_DEBUG_TRACE,
591                         LDAP_XSTRING(mdb_search) ": no candidates\n",
592                         0, 0, 0 );
593
594                 goto nochange;
595         }
596
597         /* if not root and candidates exceed to-be-checked entries, abort */
598         if ( op->ors_limit      /* isroot == FALSE */ &&
599                 op->ors_limit->lms_s_unchecked != -1 &&
600                 ncand > (unsigned) op->ors_limit->lms_s_unchecked )
601         {
602                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
603                 send_ldap_result( op, rs );
604                 rs->sr_err = LDAP_SUCCESS;
605                 goto done;
606         }
607
608         if ( op->ors_limit == NULL      /* isroot == TRUE */ ||
609                 !op->ors_limit->lms_s_pr_hide )
610         {
611                 tentries = ncand;
612         }
613
614         if ( get_pagedresults( op ) > SLAP_CONTROL_IGNORED ) {
615                 PagedResultsState *ps = op->o_pagedresults_state;
616                 /* deferred cookie parsing */
617                 rs->sr_err = parse_paged_cookie( op, rs );
618                 if ( rs->sr_err != LDAP_SUCCESS ) {
619                         send_ldap_result( op, rs );
620                         goto done;
621                 }
622
623                 cursor = (ID) ps->ps_cookie;
624                 if ( cursor && ps->ps_size == 0 ) {
625                         rs->sr_err = LDAP_SUCCESS;
626                         rs->sr_text = "search abandoned by pagedResult size=0";
627                         send_ldap_result( op, rs );
628                         goto done;
629                 }
630                 id = mdb_idl_first( candidates, &cursor );
631                 if ( id == NOID ) {
632                         Debug( LDAP_DEBUG_TRACE, 
633                                 LDAP_XSTRING(mdb_search)
634                                 ": no paged results candidates\n",
635                                 0, 0, 0 );
636                         send_paged_response( op, rs, &lastid, 0 );
637
638                         rs->sr_err = LDAP_OTHER;
639                         goto done;
640                 }
641                 if ( id == (ID)ps->ps_cookie )
642                         id = mdb_idl_next( candidates, &cursor );
643                 nsubs = ncand;  /* always bypass scope'd search */
644                 goto loop_begin;
645         }
646         if ( nsubs < ncand ) {
647                 int rc;
648                 /* Do scope-based search */
649
650                 /* if any alias scopes were set, save them */
651                 if (scopes[0].mid > 1) {
652                         cursor = 1;
653                         for (cscope = 1; cscope <= scopes[0].mid; cscope++) {
654                                 /* Ignore the original base */
655                                 if (scopes[cscope].mid == base->e_id)
656                                         continue;
657                                 iscopes[cursor++] = scopes[cscope].mid;
658                         }
659                         iscopes[0] = scopes[0].mid - 1;
660                 } else {
661                         iscopes[0] = 0;
662                 }
663
664                 isc.id = base->e_id;
665                 isc.numrdns = 0;
666                 rc = mdb_dn2id_walk( op, &isc );
667                 if ( rc )
668                         id = NOID;
669                 else
670                         id = isc.id;
671                 cscope = 0;
672         } else {
673                 id = mdb_idl_first( candidates, &cursor );
674         }
675
676         while (id != NOID)
677         {
678                 int scopeok;
679                 MDB_val edata;
680
681 loop_begin:
682
683                 /* check for abandon */
684                 if ( op->o_abandon ) {
685                         rs->sr_err = SLAPD_ABANDON;
686                         send_ldap_result( op, rs );
687                         goto done;
688                 }
689
690                 /* mostly needed by internal searches,
691                  * e.g. related to syncrepl, for whom
692                  * abandon does not get set... */
693                 if ( slapd_shutdown ) {
694                         rs->sr_err = LDAP_UNAVAILABLE;
695                         send_ldap_disconnect( op, rs );
696                         goto done;
697                 }
698
699                 /* check time limit */
700                 if ( op->ors_tlimit != SLAP_NO_LIMIT
701                                 && slap_get_time() > stoptime )
702                 {
703                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
704                         rs->sr_ref = rs->sr_v2ref;
705                         send_ldap_result( op, rs );
706                         rs->sr_err = LDAP_SUCCESS;
707                         goto done;
708                 }
709
710
711                 if ( nsubs < ncand ) {
712                         unsigned i;
713                         /* Is this entry in the candidate list? */
714                         scopeok = 0;
715                         if (MDB_IDL_IS_RANGE( candidates )) {
716                                 if ( id >= MDB_IDL_RANGE_FIRST( candidates ) &&
717                                         id <= MDB_IDL_RANGE_LAST( candidates ))
718                                         scopeok = 1;
719                         } else {
720                                 i = mdb_idl_search( candidates, id );
721                                 if ( candidates[i] == id )
722                                         scopeok = 1;
723                         }
724                         if ( scopeok )
725                                 goto scopeok;
726                         goto loop_continue;
727                 }
728
729                 /* Does this candidate actually satisfy the search scope?
730                  */
731                 scopeok = 0;
732                 isc.numrdns = 0;
733                 switch( op->ors_scope ) {
734                 case LDAP_SCOPE_BASE:
735                         /* This is always true, yes? */
736                         if ( id == base->e_id ) scopeok = 1;
737                         break;
738
739 #ifdef LDAP_SCOPE_CHILDREN
740                 case LDAP_SCOPE_CHILDREN:
741                         if ( id == base->e_id ) break;
742                         /* Fall-thru */
743 #endif
744                 case LDAP_SCOPE_SUBTREE:
745                         if ( id == base->e_id ) {
746                                 scopeok = 1;
747                                 break;
748                         }
749                         /* Fall-thru */
750                 case LDAP_SCOPE_ONELEVEL:
751                         isc.id = id;
752                         isc.nscope = 0;
753                         rs->sr_err = mdb_idscopes( op, &isc );
754                         if ( rs->sr_err == MDB_SUCCESS ) {
755                                 if ( isc.nscope )
756                                         scopeok = 1;
757                         } else {
758                                 if ( rs->sr_err == MDB_NOTFOUND )
759                                         goto notfound;
760                         }
761                         break;
762                 }
763
764                 /* Not in scope, ignore it */
765                 if ( !scopeok )
766                 {
767                         Debug( LDAP_DEBUG_TRACE,
768                                 LDAP_XSTRING(mdb_search)
769                                 ": %ld scope not okay\n",
770                                 (long) id, 0, 0 );
771                         goto loop_continue;
772                 }
773
774 scopeok:
775                 if ( id == base->e_id ) {
776                         e = base;
777                 } else {
778
779                         /* get the entry */
780                         rs->sr_err = mdb_id2edata( op, mci, id, &edata );
781                         if ( rs->sr_err == MDB_NOTFOUND ) {
782 notfound:
783                                 if( nsubs < ncand )
784                                         goto loop_continue;
785
786                                 if( !MDB_IDL_IS_RANGE(candidates) ) {
787                                         /* only complain for non-range IDLs */
788                                         Debug( LDAP_DEBUG_TRACE,
789                                                 LDAP_XSTRING(mdb_search)
790                                                 ": candidate %ld not found\n",
791                                                 (long) id, 0, 0 );
792                                 } else {
793                                         /* get the next ID from the DB */
794                                         rs->sr_err = mdb_get_nextid( mci, &cursor );
795                                         if ( rs->sr_err == MDB_NOTFOUND ) {
796                                                 break;
797                                         }
798                                         if ( rs->sr_err ) {
799                                                 rs->sr_err = LDAP_OTHER;
800                                                 rs->sr_text = "internal error in get_nextid";
801                                                 send_ldap_result( op, rs );
802                                                 goto done;
803                                         }
804                                         cursor--;
805                                 }
806
807                                 goto loop_continue;
808                         } else if ( rs->sr_err ) {
809                                 rs->sr_err = LDAP_OTHER;
810                                 rs->sr_text = "internal error in mdb_id2edata";
811                                 send_ldap_result( op, rs );
812                                 goto done;
813                         }
814
815                         rs->sr_err = mdb_entry_decode( op, ltid, &edata, &e );
816                         if ( rs->sr_err ) {
817                                 rs->sr_err = LDAP_OTHER;
818                                 rs->sr_text = "internal error in mdb_entry_decode";
819                                 send_ldap_result( op, rs );
820                                 goto done;
821                         }
822                         e->e_id = id;
823                         e->e_name.bv_val = NULL;
824                         e->e_nname.bv_val = NULL;
825                 }
826
827                 if ( is_entry_subentry( e ) ) {
828                         if( op->oq_search.rs_scope != LDAP_SCOPE_BASE ) {
829                                 if(!get_subentries_visibility( op )) {
830                                         /* only subentries are visible */
831                                         goto loop_continue;
832                                 }
833
834                         } else if ( get_subentries( op ) &&
835                                 !get_subentries_visibility( op ))
836                         {
837                                 /* only subentries are visible */
838                                 goto loop_continue;
839                         }
840
841                 } else if ( get_subentries_visibility( op )) {
842                         /* only subentries are visible */
843                         goto loop_continue;
844                 }
845
846                 /* aliases were already dereferenced in candidate list */
847                 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
848                         /* but if the search base is an alias, and we didn't
849                          * deref it when finding, return it.
850                          */
851                         if ( is_entry_alias(e) &&
852                                 ((op->ors_deref & LDAP_DEREF_FINDING) || e != base ))
853                         {
854                                 goto loop_continue;
855                         }
856                 }
857
858                 if ( !manageDSAit && is_entry_glue( e )) {
859                         goto loop_continue;
860                 }
861
862                 if (e != base) {
863                         struct berval pdn, pndn;
864                         char *d, *n;
865                         int i;
866
867                         /* child of base, just append RDNs to base->e_name */
868                         if ( nsubs < ncand || isc.scopes[isc.nscope].mid == base->e_id ) {
869                                 pdn = base->e_name;
870                                 pndn = base->e_nname;
871                         } else {
872                                 mdb_id2name( op, ltid, &isc.mc, scopes[isc.nscope].mid, &pdn, &pndn );
873                         }
874                         e->e_name.bv_len = pdn.bv_len;
875                         e->e_nname.bv_len = pndn.bv_len;
876                         for (i=0; i<isc.numrdns; i++) {
877                                 e->e_name.bv_len += isc.rdns[i].bv_len + 1;
878                                 e->e_nname.bv_len += isc.nrdns[i].bv_len + 1;
879                         }
880                         e->e_name.bv_val = op->o_tmpalloc(e->e_name.bv_len + 1, op->o_tmpmemctx);
881                         e->e_nname.bv_val = op->o_tmpalloc(e->e_nname.bv_len + 1, op->o_tmpmemctx);
882                         d = e->e_name.bv_val;
883                         n = e->e_nname.bv_val;
884                         if (nsubs < ncand) {
885                                 /* RDNs are in top-down order */
886                                 for (i=isc.numrdns-1; i>=0; i--) {
887                                         memcpy(d, isc.rdns[i].bv_val, isc.rdns[i].bv_len);
888                                         d += isc.rdns[i].bv_len;
889                                         *d++ = ',';
890                                         memcpy(n, isc.nrdns[i].bv_val, isc.nrdns[i].bv_len);
891                                         n += isc.nrdns[i].bv_len;
892                                         *n++ = ',';
893                                 }
894                         } else {
895                                 /* RDNs are in bottom-up order */
896                                 for (i=0; i<isc.numrdns; i++) {
897                                         memcpy(d, isc.rdns[i].bv_val, isc.rdns[i].bv_len);
898                                         d += isc.rdns[i].bv_len;
899                                         *d++ = ',';
900                                         memcpy(n, isc.nrdns[i].bv_val, isc.nrdns[i].bv_len);
901                                         n += isc.nrdns[i].bv_len;
902                                         *n++ = ',';
903                                 }
904                         }
905
906                         if (pdn.bv_len) {
907                                 memcpy(d, pdn.bv_val, pdn.bv_len+1);
908                                 memcpy(n, pndn.bv_val, pndn.bv_len+1);
909                         } else {
910                                 *--d = '\0';
911                                 *--n = '\0';
912                                 e->e_name.bv_len--;
913                                 e->e_nname.bv_len--;
914                         }
915                         if (pndn.bv_val != base->e_nname.bv_val) {
916                                 op->o_tmpfree(pndn.bv_val, op->o_tmpmemctx);
917                                 op->o_tmpfree(pdn.bv_val, op->o_tmpmemctx);
918                         }
919                 }
920
921                 /*
922                  * if it's a referral, add it to the list of referrals. only do
923                  * this for non-base searches, and don't check the filter
924                  * explicitly here since it's only a candidate anyway.
925                  */
926                 if ( !manageDSAit && op->oq_search.rs_scope != LDAP_SCOPE_BASE
927                         && is_entry_referral( e ) )
928                 {
929                         BerVarray erefs = get_entry_referrals( op, e );
930                         rs->sr_ref = referral_rewrite( erefs, &e->e_name, NULL,
931                                 op->oq_search.rs_scope == LDAP_SCOPE_ONELEVEL
932                                         ? LDAP_SCOPE_BASE : LDAP_SCOPE_SUBTREE );
933
934                         rs->sr_entry = e;
935                         rs->sr_flags = 0;
936
937                         send_search_reference( op, rs );
938
939                         mdb_entry_return( op, e );
940                         rs->sr_entry = NULL;
941                         e = NULL;
942
943                         ber_bvarray_free( rs->sr_ref );
944                         ber_bvarray_free( erefs );
945                         rs->sr_ref = NULL;
946
947                         goto loop_continue;
948                 }
949
950                 /* if it matches the filter and scope, send it */
951                 rs->sr_err = test_filter( op, e, op->oq_search.rs_filter );
952
953                 if ( rs->sr_err == LDAP_COMPARE_TRUE ) {
954                         /* check size limit */
955                         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
956                                 if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
957                                         mdb_entry_return( op, e );
958                                         e = NULL;
959                                         send_paged_response( op, rs, &lastid, tentries );
960                                         goto done;
961                                 }
962                                 lastid = id;
963                         }
964
965                         if (e) {
966                                 /* safe default */
967                                 rs->sr_attrs = op->oq_search.rs_attrs;
968                                 rs->sr_operational_attrs = NULL;
969                                 rs->sr_ctrls = NULL;
970                                 rs->sr_entry = e;
971                                 RS_ASSERT( e->e_private != NULL );
972                                 rs->sr_flags = 0;
973                                 rs->sr_err = LDAP_SUCCESS;
974                                 rs->sr_err = send_search_entry( op, rs );
975                                 rs->sr_attrs = NULL;
976                                 rs->sr_entry = NULL;
977                                 if (e != base)
978                                         mdb_entry_return( op, e );
979                                 e = NULL;
980
981                                 switch ( rs->sr_err ) {
982                                 case LDAP_SUCCESS:      /* entry sent ok */
983                                         break;
984                                 default:                /* entry not sent */
985                                         break;
986                                 case LDAP_BUSY:
987                                         send_ldap_result( op, rs );
988                                         goto done;
989                                 case LDAP_UNAVAILABLE:
990                                 case LDAP_SIZELIMIT_EXCEEDED:
991                                         if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
992                                                 rs->sr_ref = rs->sr_v2ref;
993                                                 send_ldap_result( op, rs );
994                                                 rs->sr_err = LDAP_SUCCESS;
995
996                                         } else {
997                                                 rs->sr_err = LDAP_OTHER;
998                                         }
999                                         goto done;
1000                                 }
1001                         }
1002
1003                 } else {
1004                         Debug( LDAP_DEBUG_TRACE,
1005                                 LDAP_XSTRING(mdb_search)
1006                                 ": %ld does not match filter\n",
1007                                 (long) id, 0, 0 );
1008                 }
1009
1010 loop_continue:
1011                 if( e != NULL ) {
1012                         if ( e != base )
1013                                 mdb_entry_return( op, e );
1014                         RS_ASSERT( rs->sr_entry == NULL );
1015                         e = NULL;
1016                         rs->sr_entry = NULL;
1017                 }
1018
1019                 if ( nsubs < ncand ) {
1020                         int rc = mdb_dn2id_walk( op, &isc );
1021                         if (rc) {
1022                                 id = NOID;
1023                                 /* We got to the end of a subtree. If there are any
1024                                  * alias scopes left, search them too.
1025                                  */
1026                                 while (iscopes[0] && cscope < iscopes[0]) {
1027                                         cscope++;
1028                                         isc.id = iscopes[cscope];
1029                                         if ( base )
1030                                                 mdb_entry_return( op, base );
1031                                         rs->sr_err = mdb_id2entry(op, mci, isc.id, &base);
1032                                         if ( !rs->sr_err ) {
1033                                                 mdb_id2name( op, ltid, &isc.mc, isc.id, &base->e_name, &base->e_nname );
1034                                                 isc.numrdns = 0;
1035                                                 if (isc.oscope == LDAP_SCOPE_ONELEVEL)
1036                                                         isc.oscope = LDAP_SCOPE_BASE;
1037                                                 rc = mdb_dn2id_walk( op, &isc );
1038                                                 if ( !rc ) {
1039                                                         id = isc.id;
1040                                                         break;
1041                                                 }
1042                                         }
1043                                 }
1044                         } else
1045                                 id = isc.id;
1046                 } else {
1047                         id = mdb_idl_next( candidates, &cursor );
1048                 }
1049         }
1050
1051 nochange:
1052         rs->sr_ctrls = NULL;
1053         rs->sr_ref = rs->sr_v2ref;
1054         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS : LDAP_REFERRAL;
1055         rs->sr_rspoid = NULL;
1056         if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
1057                 send_paged_response( op, rs, NULL, 0 );
1058         } else {
1059                 send_ldap_result( op, rs );
1060         }
1061
1062         rs->sr_err = LDAP_SUCCESS;
1063
1064 done:
1065         mdb_cursor_close( mcd );
1066         mdb_cursor_close( mci );
1067         if ( moi == &opinfo ) {
1068                 mdb_txn_reset( moi->moi_txn );
1069                 LDAP_SLIST_REMOVE( &op->o_extra, &moi->moi_oe, OpExtra, oe_next );
1070         } else {
1071                 moi->moi_ref--;
1072         }
1073         if( rs->sr_v2ref ) {
1074                 ber_bvarray_free( rs->sr_v2ref );
1075                 rs->sr_v2ref = NULL;
1076         }
1077         if (base)
1078                 mdb_entry_return( op,base);
1079         scope_chunk_ret( op, scopes );
1080
1081         return rs->sr_err;
1082 }
1083
1084
1085 static int base_candidate(
1086         BackendDB       *be,
1087         Entry   *e,
1088         ID              *ids )
1089 {
1090         Debug(LDAP_DEBUG_ARGS, "base_candidates: base: \"%s\" (0x%08lx)\n",
1091                 e->e_nname.bv_val, (long) e->e_id, 0);
1092
1093         ids[0] = 1;
1094         ids[1] = e->e_id;
1095         return 0;
1096 }
1097
1098 /* Look for "objectClass Present" in this filter.
1099  * Also count depth of filter tree while we're at it.
1100  */
1101 static int oc_filter(
1102         Filter *f,
1103         int cur,
1104         int *max )
1105 {
1106         int rc = 0;
1107
1108         assert( f != NULL );
1109
1110         if( cur > *max ) *max = cur;
1111
1112         switch( f->f_choice ) {
1113         case LDAP_FILTER_PRESENT:
1114                 if (f->f_desc == slap_schema.si_ad_objectClass) {
1115                         rc = 1;
1116                 }
1117                 break;
1118
1119         case LDAP_FILTER_AND:
1120         case LDAP_FILTER_OR:
1121                 cur++;
1122                 for ( f=f->f_and; f; f=f->f_next ) {
1123                         (void) oc_filter(f, cur, max);
1124                 }
1125                 break;
1126
1127         default:
1128                 break;
1129         }
1130         return rc;
1131 }
1132
1133 static void search_stack_free( void *key, void *data )
1134 {
1135         ber_memfree_x(data, NULL);
1136 }
1137
1138 static void *search_stack( Operation *op )
1139 {
1140         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
1141         void *ret = NULL;
1142
1143         if ( op->o_threadctx ) {
1144                 ldap_pvt_thread_pool_getkey( op->o_threadctx, (void *)search_stack,
1145                         &ret, NULL );
1146         } else {
1147                 ret = mdb->mi_search_stack;
1148         }
1149
1150         if ( !ret ) {
1151                 ret = ch_malloc( mdb->mi_search_stack_depth * MDB_IDL_UM_SIZE
1152                         * sizeof( ID ) );
1153                 if ( op->o_threadctx ) {
1154                         ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)search_stack,
1155                                 ret, search_stack_free, NULL, NULL );
1156                 } else {
1157                         mdb->mi_search_stack = ret;
1158                 }
1159         }
1160         return ret;
1161 }
1162
1163 static int search_candidates(
1164         Operation *op,
1165         SlapReply *rs,
1166         Entry *e,
1167         MDB_txn *txn,
1168         MDB_cursor *mci,
1169         ID      *ids,
1170         ID2L    scopes,
1171         ID *stack )
1172 {
1173         struct mdb_info *mdb = (struct mdb_info *) op->o_bd->be_private;
1174         int rc, depth = 1;
1175         Filter          *f, rf, xf, nf, sf;
1176         AttributeAssertion aa_ref = ATTRIBUTEASSERTION_INIT;
1177         AttributeAssertion aa_subentry = ATTRIBUTEASSERTION_INIT;
1178
1179         /*
1180          * This routine takes as input a filter (user-filter)
1181          * and rewrites it as follows:
1182          *      (&(scope=DN)[(objectClass=subentry)]
1183          *              (|[(objectClass=referral)](user-filter))
1184          */
1185
1186         Debug(LDAP_DEBUG_TRACE,
1187                 "search_candidates: base=\"%s\" (0x%08lx) scope=%d\n",
1188                 e->e_nname.bv_val, (long) e->e_id, op->oq_search.rs_scope );
1189
1190         f = op->oq_search.rs_filter;
1191
1192         /* If the user's filter uses objectClass=*,
1193          * these clauses are redundant.
1194          */
1195         if (!oc_filter(op->oq_search.rs_filter, 1, &depth)
1196                 && !get_subentries_visibility(op)) {
1197                 if( !get_manageDSAit(op) && !get_domainScope(op) ) {
1198                         /* match referral objects */
1199                         struct berval bv_ref = BER_BVC( "referral" );
1200                         rf.f_choice = LDAP_FILTER_EQUALITY;
1201                         rf.f_ava = &aa_ref;
1202                         rf.f_av_desc = slap_schema.si_ad_objectClass;
1203                         rf.f_av_value = bv_ref;
1204                         rf.f_next = f;
1205                         xf.f_or = &rf;
1206                         xf.f_choice = LDAP_FILTER_OR;
1207                         xf.f_next = NULL;
1208                         f = &xf;
1209                         depth++;
1210                 }
1211         }
1212
1213         if( get_subentries_visibility( op ) ) {
1214                 struct berval bv_subentry = BER_BVC( "subentry" );
1215                 sf.f_choice = LDAP_FILTER_EQUALITY;
1216                 sf.f_ava = &aa_subentry;
1217                 sf.f_av_desc = slap_schema.si_ad_objectClass;
1218                 sf.f_av_value = bv_subentry;
1219                 sf.f_next = f;
1220                 nf.f_choice = LDAP_FILTER_AND;
1221                 nf.f_and = &sf;
1222                 nf.f_next = NULL;
1223                 f = &nf;
1224                 depth++;
1225         }
1226
1227         /* Allocate IDL stack, plus 1 more for former tmp */
1228         if ( depth+1 > mdb->mi_search_stack_depth ) {
1229                 stack = ch_malloc( (depth + 1) * MDB_IDL_UM_SIZE * sizeof( ID ) );
1230         }
1231
1232         if( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1233                 rc = search_aliases( op, rs, e->e_id, txn, mci, scopes, stack );
1234         } else {
1235                 rc = LDAP_SUCCESS;
1236         }
1237
1238         if ( rc == LDAP_SUCCESS ) {
1239                 rc = mdb_filter_candidates( op, txn, f, ids,
1240                         stack, stack+MDB_IDL_UM_SIZE );
1241         }
1242
1243         if ( depth+1 > mdb->mi_search_stack_depth ) {
1244                 ch_free( stack );
1245         }
1246
1247         if( rc ) {
1248                 Debug(LDAP_DEBUG_TRACE,
1249                         "mdb_search_candidates: failed (rc=%d)\n",
1250                         rc, NULL, NULL );
1251
1252         } else {
1253                 Debug(LDAP_DEBUG_TRACE,
1254                         "mdb_search_candidates: id=%ld first=%ld last=%ld\n",
1255                         (long) ids[0],
1256                         (long) MDB_IDL_FIRST(ids),
1257                         (long) MDB_IDL_LAST(ids) );
1258         }
1259
1260         return rc;
1261 }
1262
1263 static int
1264 parse_paged_cookie( Operation *op, SlapReply *rs )
1265 {
1266         int             rc = LDAP_SUCCESS;
1267         PagedResultsState *ps = op->o_pagedresults_state;
1268
1269         /* this function must be invoked only if the pagedResults
1270          * control has been detected, parsed and partially checked
1271          * by the frontend */
1272         assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
1273
1274         /* cookie decoding/checks deferred to backend... */
1275         if ( ps->ps_cookieval.bv_len ) {
1276                 PagedResultsCookie reqcookie;
1277                 if( ps->ps_cookieval.bv_len != sizeof( reqcookie ) ) {
1278                         /* bad cookie */
1279                         rs->sr_text = "paged results cookie is invalid";
1280                         rc = LDAP_PROTOCOL_ERROR;
1281                         goto done;
1282                 }
1283
1284                 AC_MEMCPY( &reqcookie, ps->ps_cookieval.bv_val, sizeof( reqcookie ));
1285
1286                 if ( reqcookie > ps->ps_cookie ) {
1287                         /* bad cookie */
1288                         rs->sr_text = "paged results cookie is invalid";
1289                         rc = LDAP_PROTOCOL_ERROR;
1290                         goto done;
1291
1292                 } else if ( reqcookie < ps->ps_cookie ) {
1293                         rs->sr_text = "paged results cookie is invalid or old";
1294                         rc = LDAP_UNWILLING_TO_PERFORM;
1295                         goto done;
1296                 }
1297
1298         } else {
1299                 /* we're going to use ps_cookie */
1300                 op->o_conn->c_pagedresults_state.ps_cookie = 0;
1301         }
1302
1303 done:;
1304
1305         return rc;
1306 }
1307
1308 static void
1309 send_paged_response( 
1310         Operation       *op,
1311         SlapReply       *rs,
1312         ID              *lastid,
1313         int             tentries )
1314 {
1315         LDAPControl     *ctrls[2];
1316         BerElementBuffer berbuf;
1317         BerElement      *ber = (BerElement *)&berbuf;
1318         PagedResultsCookie respcookie;
1319         struct berval cookie;
1320
1321         Debug(LDAP_DEBUG_ARGS,
1322                 "send_paged_response: lastid=0x%08lx nentries=%d\n", 
1323                 lastid ? *lastid : 0, rs->sr_nentries, NULL );
1324
1325         ctrls[1] = NULL;
1326
1327         ber_init2( ber, NULL, LBER_USE_DER );
1328
1329         if ( lastid ) {
1330                 respcookie = ( PagedResultsCookie )(*lastid);
1331                 cookie.bv_len = sizeof( respcookie );
1332                 cookie.bv_val = (char *)&respcookie;
1333
1334         } else {
1335                 respcookie = ( PagedResultsCookie )0;
1336                 BER_BVSTR( &cookie, "" );
1337         }
1338
1339         op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
1340         op->o_conn->c_pagedresults_state.ps_count =
1341                 ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
1342                 rs->sr_nentries;
1343
1344         /* return size of 0 -- no estimate */
1345         ber_printf( ber, "{iO}", 0, &cookie ); 
1346
1347         ctrls[0] = op->o_tmpalloc( sizeof(LDAPControl), op->o_tmpmemctx );
1348         if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
1349                 goto done;
1350         }
1351
1352         ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1353         ctrls[0]->ldctl_iscritical = 0;
1354
1355         slap_add_ctrls( op, rs, ctrls );
1356         rs->sr_err = LDAP_SUCCESS;
1357         send_ldap_result( op, rs );
1358
1359 done:
1360         (void) ber_free_buf( ber );
1361 }