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