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