]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/cache-search.c
-reenabling LDAP_CACHING
[openldap] / servers / slapd / back-meta / cache-search.c
1 /*
2  * Copyright (c) 2003 by International Business Machines, Inc.
3  *
4  * International Business Machines, Inc. (hereinafter called IBM) grants
5  * permission under its copyrights to use, copy, modify, and distribute this
6  * Software with or without fee, provided that the above copyright notice and
7  * all paragraphs of this notice appear in all copies, and that the name of IBM
8  * not be used in connection with the marketing of any product incorporating
9  * the Software or modifications thereof, without specific, written prior
10  * permission.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
13  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
14  * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
15  * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
17  * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
18  *
19  * 
20  * This software is based on the backends back-ldap and back-meta, implemented
21  * by Howard Chu <hyc@highlandsun.com>, Mark Valence
22  * <kurash@sassafras.com>, Pierangelo Masarati <ando@sys-net.it> and other
23  * contributors. 
24  *
25  * The original copyright statements follow. 
26  * Copyright 1998-2002 The OpenLDAP Foundation, All Rights Reserved.
27  * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
28  *
29  * Copyright 2001, Pierangelo Masarati, All rights reserved. <ando@sys-net.it>
30  *
31  * This work has been developed to fulfill the requirements
32  * of SysNet s.n.c. <http:www.sys-net.it> and it has been donated
33  * to the OpenLDAP Foundation in the hope that it may be useful
34  * to the Open Source community, but WITHOUT ANY WARRANTY.
35  *
36  * Permission is granted to anyone to use this software for any purpose
37  * on any computer system, and to alter it and redistribute it, subject
38  * to the following restrictions:
39  *
40  * 1. The author and SysNet s.n.c. are not responsible for the consequences
41  *    of use of this software, no matter how awful, even if they arise from 
42  *    flaws in it.
43  *
44  * 2. The origin of this software must not be misrepresented, either by
45  *    explicit claim or by omission.  Since few users ever read sources,
46  *    credits should appear in the documentation.
47  *
48  * 3. Altered versions must be plainly marked as such, and must not be
49  *    misrepresented as being the original software.  Since few users
50  *    ever read sources, credits should appear in the documentation.
51  *    SysNet s.n.c. cannot be responsible for the consequences of the
52  *    alterations.
53  *
54  * 4. This notice may not be removed or altered.
55  *
56  *
57  * This software is based on the backend back-ldap, implemented
58  * by Howard Chu <hyc@highlandsun.com>, and modified by Mark Valence
59  * <kurash@sassafras.com>, Pierangelo Masarati <ando@sys-net.it> and other
60  * contributors. The contribution of the original software to the present
61  * implementation is acknowledged in this copyright statement.
62  *
63  * A special acknowledgement goes to Howard for the overall architecture
64  * (and for borrowing large pieces of code), and to Mark, who implemented
65  * from scratch the attribute/objectclass mapping.
66  *
67  * The original copyright statement follows.
68  *
69  * Copyright 1999, Howard Chu, All rights reserved. <hyc@highlandsun.com>
70  *
71  * Permission is granted to anyone to use this software for any purpose
72  * on any computer system, and to alter it and redistribute it, subject
73  * to the following restrictions:
74  *
75  * 1. The author is not responsible for the consequences of use of this
76  *    software, no matter how awful, even if they arise from flaws in it.
77  *
78  * 2. The origin of this software must not be misrepresented, either by
79  *    explicit claim or by omission.  Since few users ever read sources,
80  *    credits should appear in the documentation.
81  *
82  * 3. Altered versions must be plainly marked as such, and must not be
83  *    misrepresented as being the original software.  Since few users
84  *    ever read sources, credits should appear in the
85  *    documentation.
86  *
87  * 4. This notice may not be removed or altered.
88  *                
89  */
90 #include "portable.h"
91
92 #include <stdio.h>
93
94 #include <ac/socket.h>
95 #include <ac/string.h>
96 #include <ac/time.h>
97
98 #include "ldap_pvt.h"
99 #include "lutil.h"
100 #include "slap.h"
101 #include "../back-ldap/back-ldap.h"
102 #include "back-meta.h"
103 #undef ldap_debug       /* silence a warning in ldap-int.h */
104 #include "ldap_log.h"
105 #include "../../../libraries/libldap/ldap-int.h"
106
107 #ifdef LDAP_CACHING 
108 static Entry* 
109 meta_create_entry(
110         Backend         *be,
111         struct metaconn *lc,
112         int             target,
113         LDAPMessage     *e,
114         struct exception* result
115 ); 
116
117 static int
118 is_one_level_rdn(
119         const char      *rdn,
120         int             from
121 );
122
123 static struct metaconn*  
124 metaConnect(
125         Operation               *op, 
126         SlapReply               *rs,
127         int                     op_type, 
128         struct berval           *nbase, 
129         struct exception        *result 
130 );
131
132 static void
133 add_filter_attrs(
134         AttributeName** newattrs, 
135         AttributeName* attrs, 
136         AttributeName* filter_attrs
137 );
138
139 static int 
140 handleLdapResult(
141         struct metaconn* lc, 
142         Operation* op, 
143         SlapReply *rs,
144         int* msgid, Backend* be, 
145         AttributeName* attrs, 
146         int attrsonly, 
147         int candidates, 
148         int cacheable, 
149         Entry*** entry_array, 
150         int curr_limit, 
151         int slimit,
152         struct exception* result
153 );
154
155 static Entry* 
156 get_result_entry(
157         Backend* be,
158         struct metaconn* lc, 
159         struct metasingleconn* lsc, 
160         int* msgid,
161         int i, 
162         struct timeval* tv, 
163         struct exception* result
164 ); 
165
166 static void
167 rewriteSession(
168         struct rewrite_info* info, 
169         const char* rewriteContext, 
170         const char* string, 
171         const void* cookie,  
172         char** base, 
173         struct exception* result
174 );
175
176 static int 
177 get_attr_set(
178         AttributeName* attrs, 
179         query_manager* qm, 
180         int num
181 );
182
183 static int 
184 attrscmp(
185         AttributeName* attrs_in, 
186         AttributeName* attrs
187 );
188
189 static char* 
190 cache_entries(
191         Operation       *op,
192         SlapReply       *rs,
193         Entry** entry_array, 
194         cache_manager* cm, 
195         struct exception* result
196 ); 
197
198 static int 
199 is_temp_answerable(
200         int attr_set, 
201         struct berval* tempstr, 
202         query_manager* qm, 
203         int template_id
204 );
205
206 static void
207 consistency_check(
208         Operation       *op,
209         SlapReply       *rs,
210         Backend         *glue_be
211 ); 
212
213 static int
214 cache_back_sentry(
215         Operation* op, 
216         SlapReply *rs
217 );
218
219 int
220 meta_back_cache_search(
221         Operation       *op,
222         SlapReply       *rs )
223         /*
224         Backend         *be,
225         Connection      *conn,
226         Operation       *op,
227         struct berval   *base,
228         struct berval   *nbase,
229         int             scope,
230         int             deref,
231         int             slimit,
232         int             tlimit,
233         Filter          *filt,
234         struct berval   *filterstr,
235         AttributeName   *attributes,
236         int             attrsonly
237 ) */
238 {
239         struct metainfo         *li = ( struct metainfo * )op->o_bd->be_private;
240         struct metaconn         *lc;
241         struct metasingleconn   *lsc;
242         cache_manager*          cm = li->cm; 
243         query_manager*          qm = cm->qm; 
244
245         time_t                  curr_time; 
246
247         int count, rc = 0, *msgid = NULL; 
248         char *mbase = NULL;
249         char *cbase = NULL; 
250         char *uuid; 
251             
252         int i = -1, last = 0, candidates = 0, op_type;
253
254         struct berval   mfilter;
255         struct berval   cachebase = { 0L, NULL };  
256         struct berval   ncachebase = { 0L, NULL };  
257         struct berval   cache_suffix; 
258         struct berval   tempstr = { 0L, NULL }; 
259
260         AttributeName   *filter_attrs = NULL; 
261         AttributeName   *new_attrs = NULL; 
262         AttributeName   *attrs = NULL; 
263
264         Entry           *e;
265         Entry           **entry_array = NULL;
266
267         Query           query; 
268
269         int             attr_set = -1; 
270         int             template_id = -1; 
271         int             answerable = 0; 
272         int             cacheable = 0; 
273         int             num_entries = 0;
274         int             curr_limit;
275         int             fattr_cnt=0; 
276
277    
278         struct exception result[1]; 
279
280         Filter* filter = str2filter(op->ors_filterstr.bv_val); 
281         slap_callback cb = {cache_back_sentry, NULL}; 
282
283         cb.sc_private = op->o_bd; 
284
285         if (op->ors_attrs) {
286                 for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ )
287                         ;
288                 attrs = (AttributeName*)malloc( ( count + 1 ) *
289                                                 sizeof(AttributeName));
290                 for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ ) {
291                         ber_dupbv(&attrs[ count ].an_name,
292                                                 &op->ors_attrs[ count ].an_name);
293                         attrs[count].an_desc = op->ors_attrs[count].an_desc; 
294                 }
295                 attrs[ count ].an_name.bv_val = NULL;
296                 attrs[ count ].an_name.bv_len = 0;
297         }
298
299         result->type = SUCCESS; 
300         result->rc = 0; 
301         ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
302         cm->threads++; 
303 #ifdef NEW_LOGGING
304         LDAP_LOG( BACK_META, DETAIL1, "Threads++ = %d\n", cm->threads, 0, 0 );
305 #else /* !NEW_LOGGING */
306         Debug( LDAP_DEBUG_ANY, "Threads++ = %d\n", cm->threads, 0, 0 );
307 #endif /* !NEW_LOGGING */
308         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
309     
310         filter2template(filter, &tempstr, &filter_attrs, &fattr_cnt, result);  
311         if (result->type != SUCCESS) 
312                 goto Catch; 
313
314 #ifdef NEW_LOGGING
315         LDAP_LOG( BACK_META, DETAIL1, "query template of incoming query = %s\n",
316                                         tempstr.bv_val, 0, 0 );
317 #else /* !NEW_LOGGING */
318         Debug( LDAP_DEBUG_ANY, "query template of incoming query = %s\n",
319                                         tempstr.bv_val, 0, 0 );
320 #endif /* !NEW_LOGGING */
321         curr_limit = cm->num_entries_limit ;
322
323         /* find attr set */     
324         attr_set = get_attr_set(attrs, qm, cm->numattrsets); 
325     
326         query.filter = filter; 
327         query.attrs = attrs; 
328         query.base = op->o_req_dn; 
329         query.scope = op->ors_scope; 
330
331         /* check for query containment */
332         if (attr_set > -1) {
333                 for (i=0; i<cm->numtemplates; i++) {
334                         /* find if template i can potentially answer tempstr */
335                         if (!is_temp_answerable(attr_set, &tempstr, qm, i)) 
336                                 continue; 
337                         if (attr_set == qm->templates[i].attr_set_index) {
338                                 cacheable = 1; 
339                                 template_id = i; 
340                         }
341 #ifdef NEW_LOGGING
342                         LDAP_LOG( BACK_META, DETAIL2,
343                                         "Entering QC, querystr = %s\n",
344                                         op->ors_filterstr.bv_val, 0, 0 );
345 #else /* !NEW_LOGGING */
346                         Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
347                                         op->ors_filterstr.bv_val, 0, 0 );
348 #endif /* !NEW_LOGGING */
349                         answerable = (*(qm->qcfunc))(qm, &query, i);
350
351                         if (answerable)
352                                 break;
353                 }
354         }
355
356         if (answerable) {
357                 Operation       op_tmp;
358
359 #ifdef NEW_LOGGING
360                 LDAP_LOG( BACK_META, DETAIL1, "QUERY ANSWERABLE\n", 0, 0, 0 );
361 #else /* !NEW_LOGGING */
362                 Debug( LDAP_DEBUG_ANY, "QUERY ANSWERABLE\n", 0, 0, 0 );
363 #endif /* !NEW_LOGGING */
364                 rewriteSession(li->rwinfo, "cacheBase", op->o_req_dn.bv_val,
365                                         op->o_conn, &cbase, result); 
366                 if (result->type != SUCCESS) { 
367                         ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock); 
368                         goto Catch; 
369                 }
370                 if ( cbase == NULL ) {
371                         cachebase = op->o_req_dn;
372                 } else {
373                         cachebase.bv_val = cbase;
374                         cachebase.bv_len = strlen(cbase);
375                 }
376                 dnNormalize(0, NULL, NULL, &cachebase, &ncachebase,
377                                 op->o_tmpmemctx); 
378
379                 /* FIXME: safe default? */
380                 op_tmp = *op;
381
382                 op_tmp.o_bd = li->glue_be;
383                 op_tmp.o_req_dn = cachebase;
384                 op_tmp.o_req_ndn = ncachebase;
385
386                 op_tmp.o_caching_on = 1; 
387                 op_tmp.o_callback = &cb; 
388
389                 li->glue_be->be_search(op, rs);
390                 ber_memfree( ncachebase.bv_val );
391                 if ( cachebase.bv_val != op->o_req_dn.bv_val ) {
392                         /* free only if rewritten */
393                         free( cachebase.bv_val );
394                 }
395
396                 ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock); 
397         } else {
398 #ifdef NEW_LOGGING
399                 LDAP_LOG( BACK_META, DETAIL1, "QUERY NOT ANSWERABLE\n",
400                                         0, 0, 0 );
401 #else /* !NEW_LOGGING */
402                 Debug( LDAP_DEBUG_ANY, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
403 #endif /* !NEW_LOGGING */
404
405                 if ( op->ors_scope == LDAP_SCOPE_BASE ) {
406                         op_type = META_OP_REQUIRE_SINGLE;
407                 } else {
408                         op_type = META_OP_ALLOW_MULTIPLE;
409                 }
410
411                 lc = metaConnect(op, rs, op_type,
412                                 &op->o_req_ndn, result);
413
414                 if (result->type != SUCCESS) 
415                         goto Catch; 
416
417                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
418                 if (cm->num_cached_queries >= cm->max_queries) {
419                         cacheable = 0; 
420                 }
421                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
422                 
423                 if (cacheable) {
424 #ifdef NEW_LOGGING
425                         LDAP_LOG( BACK_META, DETAIL1,
426                                         "QUERY TEMPLATE CACHEABLE\n",
427                                         0, 0, 0);
428 #else /* !NEW_LOGGING */
429                         Debug( LDAP_DEBUG_ANY, "QUERY TEMPLATE CACHEABLE\n",
430                                         0, 0, 0);
431 #endif /* !NEW_LOGGING */
432                         add_filter_attrs(&new_attrs, attrs, filter_attrs);
433                 } else {
434                         new_attrs = attrs; 
435                 }
436
437                 free(filter_attrs); 
438         
439                 /*
440                  * Array of message id of each target
441                  */
442                 msgid = ch_calloc( sizeof( int ), li->ntargets );
443                 if ( msgid == NULL ) {
444                         result->type = CONN_ERR; 
445                         goto Catch; 
446                 }
447
448                 /*
449                 if (slimit > 0 &&  (slimit <= cm->num_entries_limit))  
450                         slimit = cm->num_entries_limit; 
451                 */
452
453                 /*
454                  * Inits searches
455                  */
456
457                 for ( i = 0, lsc = lc->conns; !META_LAST(lsc); ++i, ++lsc ) {
458                         char    *realbase = ( char * )op->o_req_dn.bv_val;
459                         int     realscope = op->ors_scope;
460                         ber_len_t suffixlen;
461                         char    *mapped_filter, **mapped_attrs;
462
463                         /* FIXME: Check for more than one targets */
464                         if ( meta_back_is_candidate(
465                                         &li->targets[i]->suffix,
466                                         &op->o_req_ndn ))
467                                 lsc->candidate = META_CANDIDATE; 
468
469                         if ( lsc->candidate != META_CANDIDATE ) 
470                                 continue;
471
472                         if ( op->ors_deref != -1 ) {
473                                 ldap_set_option( lsc->ld, LDAP_OPT_DEREF,
474                                                 ( void * )&op->ors_deref);
475                         }
476                         if ( op->ors_tlimit != -1 ) {
477                                 ldap_set_option( lsc->ld, LDAP_OPT_TIMELIMIT,
478                                                 ( void * )&op->ors_tlimit);
479                         }
480                         if ( op->ors_slimit != -1 ) {
481                                 ldap_set_option( lsc->ld, LDAP_OPT_SIZELIMIT,
482                                                 ( void * )&op->ors_slimit);
483                         }
484
485                         /*
486                          * modifies the base according to the scope, if required
487                          */
488                         suffixlen = li->targets[ i ]->suffix.bv_len;
489                         if ( suffixlen > op->o_req_ndn.bv_len ) {
490                                 switch ( op->ors_scope ) {
491                                 case LDAP_SCOPE_SUBTREE:
492                                         /*
493                                          * make the target suffix the new base
494                                          * FIXME: this is very forgiving,
495                                          * because illegal bases may be turned
496                                          * into the suffix of the target.
497                                          */
498                                         if ( dnIsSuffix(
499                                                 &li->targets[ i ]->suffix,
500                                                 &op->o_req_ndn ) ) {
501                                                 realbase =
502                                                 li->targets[i]->suffix.bv_val;
503                                         } else {
504                                                 /*
505                                                  * this target is no longer
506                                                  * candidate
507                                                  */
508                                                 lsc->candidate =
509                                                         META_NOT_CANDIDATE;
510                                                 continue;
511                                         }
512                                         break;
513
514                                 case LDAP_SCOPE_ONELEVEL:
515                                         if ( is_one_level_rdn(
516                                                 li->targets[ i ]->suffix.bv_val,
517                                                 suffixlen - op->o_req_ndn.bv_len - 1 )
518                                                 && dnIsSuffix(
519                                                 &li->targets[ i ]->suffix,
520                                                 &op->o_req_ndn ) ) {
521                                                 /*
522                                                  * if there is exactly one
523                                                  * level, make the target suffix
524                                                  * the new base, and make scope
525                                                  * "base"
526                                                  */
527                                                 realbase =
528                                                 li->targets[i]->suffix.bv_val;
529                                                 realscope = LDAP_SCOPE_BASE;
530                                                 break;
531                                         } /* else continue with the next case */
532
533                                 case LDAP_SCOPE_BASE:
534                                         /*
535                                          * this target is no longer candidate
536                                          */
537                                         lsc->candidate = META_NOT_CANDIDATE;
538                                         continue;
539                                 }
540                         }
541
542                         /*
543                          * Rewrite the search base, if required
544                          */
545
546                         rewriteSession(li->targets[i]->rwmap.rwm_rw,
547                                         "searchBase",
548                                         realbase, op->o_conn, &mbase, result); 
549
550                         if (result->type != SUCCESS)
551                                 goto Catch; 
552
553                         if ( mbase == NULL ) {
554                                 mbase = realbase;
555                         }
556
557                         /*
558                          * Rewrite the search filter, if required
559                          */
560                         rewriteSession( li->targets[i]->rwmap.rwm_rw,
561                                         "searchFilter",
562                                         op->ors_filterstr.bv_val, op->o_conn,
563                                         &mfilter.bv_val, result);
564                         if (result->type != SUCCESS) 
565                                 goto Catch; 
566
567                         if ( mfilter.bv_val != NULL && mfilter.bv_val[ 0 ]
568                                                                 != '\0') {
569                                 mfilter.bv_len = strlen( mfilter.bv_val );
570                         } else {
571                                 if ( mfilter.bv_val != NULL ) {
572                                         free( mfilter.bv_val );
573                                 }
574                                 mfilter = op->ors_filterstr;
575                         }
576
577 #if 0
578                         /*
579                          * Maps attributes in filter
580                          */
581                         mapped_filter = ldap_back_map_filter(
582                                         &li->targets[i]->rwmap.rwm_at,
583                                         &li->targets[i]->rwmap.rwm_oc,
584                                         &mfilter, 0 );
585                         if ( mapped_filter == NULL ) {
586                                 mapped_filter = ( char * )mfilter.bv_val;
587                         } else {
588                                 if ( mfilter.bv_val != op->ors_filterstr.bv_val ) {
589                                         free( mfilter.bv_val );
590                                 }
591                         }
592                         mfilter.bv_val = NULL;
593                         mfilter.bv_len = 0;
594 #else
595                         mapped_filter = (char *) mfilter.bv_val;
596 #endif
597
598                         /*
599                          * Maps required attributes
600                          */
601                         if ( ldap_back_map_attrs(
602                                         &li->targets[ i ]->rwmap.rwm_at,
603                                         new_attrs, 0, &mapped_attrs ) ) {
604                                 goto Catch;
605                         }
606
607                         /*
608                          * Starts the search
609                          */
610                         msgid[ i ] = ldap_search( lsc->ld, mbase, realscope,
611                                                 mapped_filter, mapped_attrs,
612                                                 op->ors_attrsonly ); 
613                         if ( msgid[ i ] == -1 ) {
614                                 lsc->candidate = META_NOT_CANDIDATE;
615                                 continue;
616                         }
617
618                         if ( mapped_attrs ) {
619                                 free( mapped_attrs );
620                                 mapped_attrs = NULL;
621                         }
622
623                         if ( mapped_filter != op->ors_filterstr.bv_val ) {
624                                 free( mapped_filter );
625                                 mapped_filter = NULL;
626                         }
627
628                         if ( mbase != realbase ) {
629                                 free( mbase );
630                                 mbase = NULL;
631                         }
632
633                         ++candidates;
634                 }
635
636                 num_entries = handleLdapResult(lc, op, rs, msgid,
637                                 op->o_bd, attrs,
638                                 op->ors_attrsonly, candidates, 
639                                 cacheable, &entry_array,
640                                 curr_limit, op->ors_slimit, result); 
641
642                 if (result->type != SUCCESS) 
643                         goto Catch; 
644                 if (cacheable && (num_entries <= curr_limit)) {
645                         Operation       op_tmp = *op;
646
647 #ifdef NEW_LOGGING
648                         LDAP_LOG( BACK_META, DETAIL1,
649                                         "QUERY CACHEABLE\n", 0, 0, 0 );
650 #else /* !NEW_LOGGING */
651                         Debug( LDAP_DEBUG_ANY, "QUERY CACHEABLE\n", 0, 0, 0 );
652 #endif /* !NEW_LOGGING */
653                         op_tmp.o_bd = li->glue_be;
654                         uuid = cache_entries(&op_tmp, rs, entry_array,
655                                         cm, result); 
656 #ifdef NEW_LOGGING
657                         LDAP_LOG( BACK_META, DETAIL1,
658                                         "Added query %s UUID %s ENTRIES %d\n",
659                                         op->ors_filterstr.bv_val,
660                                         uuid, num_entries );
661 #else /* !NEW_LOGGING */
662                         Debug( LDAP_DEBUG_ANY,
663                                         "Added query %s UUID %s ENTRIES %d\n",
664                                         op->ors_filterstr.bv_val,
665                                         uuid, num_entries );
666 #endif /* !NEW_LOGGING */
667             
668                         if (result->type != SUCCESS) 
669                                 goto Catch; 
670                         (*(qm->addfunc))(qm, &query, template_id, uuid, result); 
671                         if (result->type != SUCCESS) 
672                                 goto Catch; 
673                         filter = 0; 
674                         attrs = 0; 
675                 }
676         }
677
678 Catch:;
679         switch (result->type) {
680                 case SUCCESS: 
681                         rc = 0; 
682                         break;
683
684                 case FILTER_ERR: 
685 #ifdef NEW_LOGGING
686                         LDAP_LOG( BACK_META, DETAIL1,
687                                         "Invalid template error\n", 0, 0, 0 );
688 #else /* !NEW_LOGGING */
689                         Debug( LDAP_DEBUG_ANY, "Invalid template error\n",
690                                         0, 0, 0 );
691 #endif /* !NEW_LOGGING */
692                         break; 
693
694                 case CONN_ERR: 
695                         rc = -1; 
696 #ifdef NEW_LOGGING
697                         LDAP_LOG( BACK_META, DETAIL1,
698                                 "Could not connect to a remote server\n",
699                                 0, 0, 0 );
700 #else /* !NEW_LOGGING */
701                         Debug( LDAP_DEBUG_ANY,
702                                 "Could not connect to a remote server\n",
703                                 0, 0, 0 );
704 #endif /* !NEW_LOGGING */
705                         send_ldap_error(op, rs, LDAP_OTHER,
706                                         "Connection error" );
707                         break;
708                         
709                 case RESULT_ERR: 
710                         rc = -1; 
711 #ifdef NEW_LOGGING
712                         LDAP_LOG( BACK_META, DETAIL1,
713                                 "Error in handling ldap_result\n", 0, 0, 0 );
714 #else /* !NEW_LOGGING */
715                         Debug( LDAP_DEBUG_ANY,
716                                 "Error in handling ldap_result\n", 0, 0, 0 );
717 #endif /* !NEW_LOGGING */
718                         break; 
719
720                 case REWRITING_ERR: 
721                         rc = -1; 
722                         if (result->rc == REWRITE_REGEXEC_UNWILLING) {
723                                 send_ldap_error( op, rs,
724                                                 LDAP_UNWILLING_TO_PERFORM,
725                                                 "Unwilling to perform" );
726                         } else {
727                                 send_ldap_error( op, rs, LDAP_OTHER,
728                                                 "Rewrite error" );
729                         }
730                         break;
731
732                 case MERGE_ERR: 
733                         rc = -1; 
734 #ifdef NEW_LOGGING
735                         LDAP_LOG( BACK_META, DETAIL1,
736                                 "Error in merging entry \n", 0, 0, 0 );
737 #else /* !NEW_LOGGING */
738                         Debug( LDAP_DEBUG_ANY,
739                                 "Error in merging entry \n", 0, 0, 0 );
740 #endif /* !NEW_LOGGING */
741                         break;
742
743                 case REMOVE_ERR: 
744                         rc = -1; 
745 #ifdef NEW_LOGGING
746                         LDAP_LOG( BACK_META, DETAIL1,
747                                         "Error in removing query \n",
748                                         0, 0, 0 );
749 #else /* !NEW_LOGGING */
750                         Debug( LDAP_DEBUG_ANY, "Error in removing query \n",
751                                         0, 0, 0 );
752 #endif /* !NEW_LOGGING */
753                         break;
754
755                 default:
756                         /* assert(0); */
757                         break;
758         }
759
760         ldap_pvt_thread_mutex_lock(&cm->consistency_mutex); 
761         curr_time = slap_get_time(); 
762         if (curr_time - cm->consistency_time > cm->consistency_cycle_time) {
763                 cm->consistency_time = curr_time; 
764                 consistency_check(op, rs, li->glue_be); 
765         }       
766         ldap_pvt_thread_mutex_unlock(&cm->consistency_mutex); 
767
768         if ( msgid ) {
769                 ch_free( msgid );
770         }
771         if (entry_array)  {
772                 for (i=0; (e = entry_array[i]); i++) {
773                         entry_free(e); 
774                 }
775                 free(entry_array);
776         }
777         if (filter) 
778                 filter_free(filter);
779
780         if (new_attrs) {
781                 if (new_attrs != attrs) 
782                         free(new_attrs); 
783         }
784
785         if (attrs)
786                 free(attrs); 
787
788         if (tempstr.bv_val ) {
789                 free(tempstr.bv_val);
790         }
791         ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
792         cm->threads--; 
793 #ifdef NEW_LOGGING
794         LDAP_LOG( BACK_META, DETAIL1, "Threads-- = %d\n", cm->threads, 0, 0 ); 
795 #else /* !NEW_LOGGING */
796         Debug( LDAP_DEBUG_ANY, "Threads-- = %d\n", cm->threads, 0, 0 ); 
797 #endif /* !NEW_LOGGING */
798         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
799         return rc;
800 }
801
802
803 static Entry* 
804 meta_create_entry (
805         Backend                 *be,
806         struct metaconn         *lc,
807         int                     target,
808         LDAPMessage             *e,
809         struct exception*       result
810 )
811 {
812         struct metainfo         *li = ( struct metainfo * )be->be_private;
813         struct berval           a, mapped;
814         Entry*                  ent;
815         BerElement              ber = *e->lm_ber;
816         Attribute               *attr, **attrp;
817         struct berval           dummy = { 0, NULL };
818         struct berval           *bv, bdn;
819         const char              *text;
820         char*                   ename = NULL; 
821         if ( ber_scanf( &ber, "{m{", &bdn ) == LBER_ERROR ) {
822                 result->type = CREATE_ENTRY_ERR;        
823                 return NULL; 
824         }
825         ent = (Entry*)malloc(sizeof(Entry)); 
826
827         /*
828          * Rewrite the dn of the result, if needed
829          */
830         rewriteSession( li->targets[ target ]->rwmap.rwm_rw, "searchResult",
831                         bdn.bv_val, lc->conn, &ent->e_name.bv_val, result );  
832
833         if (result->type != SUCCESS) {
834                 return NULL; 
835         }
836         if ( ent->e_name.bv_val == NULL ) {
837                 ber_dupbv(&(ent->e_name), &bdn);
838         } else {
839 #ifdef NEW_LOGGING
840                 LDAP_LOG( BACK_META, DETAIL1,
841                         "[rw] searchResult[%d]: \"%s\" -> \"%s\"\n",
842                         target, bdn.bv_val, ent->e_name.bv_val );
843 #else /* !NEW_LOGGING */
844                 Debug( LDAP_DEBUG_ARGS, "rw> searchResult[%d]: \"%s\""
845                         " -> \"%s\"\n",
846                         target, bdn.bv_val, ent->e_name.bv_val );
847 #endif /* !NEW_LOGGING */
848                 ent->e_name.bv_len = strlen( ent->e_name.bv_val );
849         }
850                 
851         /*
852          * Note: this may fail if the target host(s) schema differs
853          * from the one known to the meta, and a DN with unknown
854          * attributes is returned.
855          * 
856          * FIXME: should we log anything, or delegate to dnNormalize?
857          */
858         dnNormalize( 0, NULL, NULL, &ent->e_name, &ent->e_nname, NULL ); 
859
860         /*
861         if ( dnNormalize( 0, NULL, NULL, &ent->e_name, &ent->e_nname )
862                 != LDAP_SUCCESS )
863         {
864                 return LDAP_INVALID_DN_SYNTAX;
865         }
866         */
867
868         /*
869          * cache dn
870          */
871         if ( li->cache.ttl != META_DNCACHE_DISABLED ) {
872                 meta_dncache_update_entry( &li->cache, &ent->e_nname, target );
873         }
874
875         ent->e_id = 0;
876         ent->e_attrs = 0;
877         ent->e_private = 0;
878         ent->e_bv.bv_val = 0; 
879
880         attrp = &ent->e_attrs;
881
882         while ( ber_scanf( &ber, "{m", &a ) != LBER_ERROR ) {
883                 ldap_back_map( &li->targets[ target ]->rwmap.rwm_at, 
884                                 &a, &mapped, 1 );
885                 if ( mapped.bv_val == NULL ) {
886                         continue;
887                 }
888                 attr = ( Attribute * )ch_malloc( sizeof( Attribute ) );
889                 if ( attr == NULL ) {
890                         continue;
891                 }
892                 attr->a_flags = 0;
893                 attr->a_next = 0;
894                 attr->a_desc = NULL;
895                 if ( slap_bv2ad( &mapped, &attr->a_desc, &text ) != LDAP_SUCCESS) {
896                         if ( slap_bv2undef_ad( &mapped, &attr->a_desc, &text ) 
897                                         != LDAP_SUCCESS) {
898 #ifdef NEW_LOGGING
899                                 LDAP_LOG( BACK_META, DETAIL1,
900                                         "slap_bv2undef_ad(%s): %s\n",
901                                         mapped.bv_val, text, 0 );
902 #else /* !NEW_LOGGING */
903                                 Debug( LDAP_DEBUG_ANY,
904                                         "slap_bv2undef_ad(%s): "
905                                         "%s\n%s", mapped.bv_val, text, "" );
906 #endif /* !NEW_LOGGING */
907                                 ch_free( attr );
908                                 continue;
909                         }
910                 }
911
912                 /* no subschemaSubentry */
913                 if ( attr->a_desc == slap_schema.si_ad_subschemaSubentry ) {
914                         ch_free(attr);
915                         continue;
916                 }
917
918                 if ( ber_scanf( &ber, "[W]", &attr->a_vals ) == LBER_ERROR 
919                                 || attr->a_vals == NULL ) {
920                         attr->a_vals = &dummy;
921                 } else if ( attr->a_desc == slap_schema.si_ad_objectClass ||
922                                 attr->a_desc ==
923                                 slap_schema.si_ad_structuralObjectClass) {
924                         int i, last;
925                         for ( last = 0; attr->a_vals[ last ].bv_val; ++last )
926                                 ;
927                         for ( i = 0, bv = attr->a_vals; bv->bv_val; bv++,i++ ) {
928                                 ldap_back_map( &li->targets[ target]->rwmap.rwm_oc,
929                                                 bv, &mapped, 1 );
930                                 if ( mapped.bv_val == NULL ) {
931                                         free( bv->bv_val );
932                                         bv->bv_val = NULL;
933                                         if ( --last < 0 ) {
934                                                 break;
935                                         }
936                                         *bv = attr->a_vals[ last ];
937                                         attr->a_vals[ last ].bv_val = NULL;
938                                         i--;
939                                 } else if ( mapped.bv_val != bv->bv_val ) {
940                                         free( bv->bv_val );
941                                         ber_dupbv( bv, &mapped );
942                                 }
943                         }
944                 /*
945                  * It is necessary to try to rewrite attributes with
946                  * dn syntax because they might be used in ACLs as
947                  * members of groups; since ACLs are applied to the
948                  * rewritten stuff, no dn-based subecj clause could
949                  * be used at the ldap backend side (see
950                  * http://www.OpenLDAP.org/faq/data/cache/452.html)
951                  * The problem can be overcome by moving the dn-based
952                  * ACLs to the target directory server, and letting
953                  * everything pass thru the ldap backend.
954                  */
955                 } else if ( strcmp( attr->a_desc->ad_type->sat_syntax->ssyn_oid,
956                                 SLAPD_DN_SYNTAX ) == 0 ) {
957                         int i;
958                         for ( i = 0, bv = attr->a_vals; bv->bv_val; bv++,i++ ) {
959                                 char *newval;
960                                 rewriteSession(li->targets[ target ]->rwmap.rwm_rw,
961                                                 "searchResult", bv->bv_val,
962                                                 lc->conn, &newval, result); 
963                                 if (result->type != SUCCESS) {
964                                         /* FIXME : Handle error */
965                                         result->type = SUCCESS; 
966                                 } else {
967                                         /* left as is */
968                                         if ( newval == NULL ) {
969                                                 break;
970                                         }
971 #ifdef NEW_LOGGING
972                                         LDAP_LOG( BACK_META, DETAIL1,
973                                                 "[rw] searchResult on "
974                                                 "attr=%s: \"%s\" -> \"%s\"\n",
975                                                 attr->a_desc->ad_type->
976                                                 sat_cname.bv_val,
977                                                 bv->bv_val, newval );
978 #else /* !NEW_LOGGING */
979                                         Debug( LDAP_DEBUG_ARGS,
980                                                 "rw> searchResult on attr=%s:"
981                                                 " \"%s\" -> \"%s\"\n",
982                                                 attr->a_desc->ad_type->
983                                                 sat_cname.bv_val,
984                                                 bv->bv_val, newval );
985 #endif /* !NEW_LOGGING */
986                                         free( bv->bv_val );
987                                         bv->bv_val = newval;
988                                         bv->bv_len = strlen( newval );
989                                 }
990                         }
991                 }
992                 *attrp = attr;
993                 attrp = &attr->a_next;
994         }
995         return ent; 
996 }
997
998 static int
999 is_one_level_rdn(
1000         const char      *rdn,
1001         int             from
1002 )
1003 {
1004         for ( ; from--; ) {
1005                 if ( DN_SEPARATOR( rdn[ from ] ) ) {
1006                         return 0;
1007                 }
1008         }
1009         return 1;
1010 }
1011
1012 static struct metaconn*  
1013 metaConnect(
1014         Operation*              op, 
1015         SlapReply               *rs,
1016         int                     op_type, 
1017         struct berval           *nbase, 
1018         struct exception        *result)
1019 {
1020         struct metaconn         *lc; 
1021
1022         result->type = SUCCESS; 
1023         lc = meta_back_getconn( op, rs, op_type, nbase, NULL );
1024         if (!lc) {
1025                 result->type = CONN_ERR; 
1026                 return 0; 
1027         }
1028         return lc; 
1029 }
1030
1031 static void
1032 add_filter_attrs(
1033         AttributeName** new_attrs, 
1034         AttributeName* attrs, 
1035         AttributeName* filter_attrs )
1036 {
1037         struct berval all_user = { sizeof(LDAP_ALL_USER_ATTRIBUTES) -1,
1038                                    LDAP_ALL_USER_ATTRIBUTES };
1039
1040         struct berval all_op = { sizeof(LDAP_ALL_OPERATIONAL_ATTRIBUTES) -1,
1041                                         LDAP_ALL_OPERATIONAL_ATTRIBUTES}; 
1042
1043         int alluser = 0; 
1044         int allop = 0; 
1045         int i; 
1046         int count; 
1047
1048         /* duplicate attrs */
1049         for (count=0; attrs[count].an_name.bv_val; count++) 
1050                 ;
1051         *new_attrs =  (AttributeName*)(malloc((count+1)*sizeof(AttributeName))); 
1052         for (i=0; i<count; i++) {
1053                 /*
1054                 ber_dupbv(&((*new_attrs)[i].an_name), &(attrs[i].an_name)); 
1055                 */
1056                 (*new_attrs)[i].an_name = attrs[i].an_name; 
1057                 (*new_attrs)[i].an_desc = attrs[i].an_desc;  
1058         }
1059         (*new_attrs)[count].an_name.bv_val = NULL; 
1060         (*new_attrs)[count].an_name.bv_len = 0; 
1061
1062
1063         if ((*new_attrs)[0].an_name.bv_val == NULL) {
1064                 *new_attrs = (AttributeName*)(malloc(2*sizeof(AttributeName))); 
1065                 (*new_attrs)[0].an_name.bv_val = "*"; 
1066                 (*new_attrs)[0].an_name.bv_len = 1; 
1067                 (*new_attrs)[1].an_name.bv_val = NULL; 
1068                 (*new_attrs)[1].an_name.bv_len = 0; 
1069                 alluser = 1; 
1070                 count = 1; 
1071         } else {
1072                 alluser = an_find(*new_attrs, &all_user); 
1073                 allop = an_find(*new_attrs, &all_op); 
1074         }
1075
1076         for ( i=0; filter_attrs[i].an_name.bv_val; i++ ) {
1077                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1078                         continue; 
1079                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type)
1080                                                 && allop )
1081                         continue; 
1082                 else if (alluser) 
1083                         continue; 
1084                 *new_attrs = (AttributeName*)(realloc(*new_attrs,
1085                                         (count+2)*sizeof(AttributeName))); 
1086                 (*new_attrs)[count].an_name.bv_val =
1087                                 filter_attrs[i].an_name.bv_val; 
1088                 (*new_attrs)[count].an_name.bv_len =
1089                                 filter_attrs[i].an_name.bv_len; 
1090                 (*new_attrs)[count].an_desc = filter_attrs[i].an_desc; 
1091                 (*new_attrs)[count+1].an_name.bv_val = NULL; 
1092                 (*new_attrs)[count+1].an_name.bv_len = 0; 
1093                 count++; 
1094         }
1095 }
1096
1097 static int 
1098 handleLdapResult(
1099         struct metaconn* lc,
1100         Operation* op, 
1101         SlapReply *rs,
1102         int* msgid, Backend* be, 
1103         AttributeName* attrs, 
1104         int attrsonly, 
1105         int candidates, 
1106         int cacheable, 
1107         Entry*** entry_array, 
1108         int curr_limit, 
1109         int slimit,
1110         struct exception* result)
1111 {
1112         Entry  *entry;
1113         char *match = NULL, *err = NULL, *cache_ename = NULL;
1114         int sres; 
1115         int mres = LDAP_SUCCESS; 
1116         int num_entries = 0, count, i, rc;     
1117         struct timeval tv = {0, 0}; 
1118         struct metasingleconn* lsc; 
1119         struct metainfo         *li = ( struct metainfo * )be->be_private;
1120         result->rc = 0; 
1121         result->type = SUCCESS; 
1122
1123         for ( count = 0, rc = 0; candidates > 0; ) {
1124                 int ab, gotit = 0;
1125
1126                 /* check for abandon */
1127                 ab = op->o_abandon;
1128
1129                 for ( i = 0, lsc = lc->conns; !META_LAST(lsc); lsc++, i++ ) {
1130                         if ( lsc->candidate != META_CANDIDATE ) {
1131                                 continue;
1132                         }
1133
1134                         if ( ab ) {
1135                                 ldap_abandon( lsc->ld, msgid[ i ] );
1136                                 result->type = ABANDON_ERR;
1137                                 break; 
1138                         }
1139
1140                         if ( slimit > 0 && num_entries == slimit ) {
1141                                 result->type = SLIMIT_ERR; 
1142                                 break; 
1143                         }
1144
1145                         if ((entry = get_result_entry(be, lc, lsc,
1146                                                 msgid, i, &tv, result))) {
1147                                 rs->sr_entry = entry;
1148                                 send_search_entry( op, rs );
1149                                 rs->sr_entry = NULL;
1150                                 if ((cacheable) &&
1151                                                 (num_entries < curr_limit))  {
1152                                         rewriteSession( li->rwinfo,
1153                                                         "cacheResult",
1154                                                         entry->e_name.bv_val,
1155                                                         lc->conn,
1156                                                         &cache_ename, result );  
1157                                         free(entry->e_name.bv_val); 
1158                                         if (result->type != SUCCESS) {
1159                                                 return 0; 
1160                                         }
1161                                         ber_str2bv(cache_ename,
1162                                                 strlen(cache_ename),
1163                                                 0, &entry->e_name); 
1164                                         ber_dupbv(&entry->e_nname,
1165                                                 &entry->e_name); 
1166                                         *entry_array = (Entry**)realloc(
1167                                                         *entry_array,
1168                                                         (( num_entries+2 ) *
1169                                                          sizeof( Entry* )));
1170                                         (*entry_array)[num_entries] = entry;    
1171                                         (*entry_array)[num_entries+1] = NULL;
1172                                 }
1173                                 num_entries++; 
1174                                 gotit = 1; 
1175                         } else if (result->type == REWRITING_ERR) {
1176                                 return 0; 
1177                         } else if (result->type == TIMEOUT_ERR) {
1178                                 result->type = SUCCESS; 
1179                                 continue;  
1180                         } else if (result->type == CREATE_ENTRY_ERR) {
1181                                 break; 
1182                         } else if (result->rc == -1) {
1183                                 break; 
1184                         } else {
1185                                 rs->sr_err = result->rc;
1186                                 sres = ldap_back_map_result(rs);
1187                                 if (mres == LDAP_SUCCESS &&
1188                                                 sres != LDAP_SUCCESS) {
1189                                         mres = sres; 
1190                                         ldap_get_option(lsc->ld,
1191                                                 LDAP_OPT_ERROR_STRING, &err);
1192                                         ldap_get_option(lsc->ld,
1193                                                 LDAP_OPT_MATCHED_DN, &match);
1194                                 }
1195                                 lsc->candidate = META_NOT_CANDIDATE; 
1196                                 candidates--; 
1197                                 result->type = SUCCESS; 
1198                         }
1199                 }
1200                 switch (result->type) {
1201                 case RESULT_ERR: 
1202 #ifdef NEW_LOGGING
1203                         LDAP_LOG( BACK_META, DETAIL1,
1204                                         "ldap_result error, rc = -1\n",
1205                                         0, 0, 0 );
1206 #else /* !NEW_LOGGING */
1207                         Debug( LDAP_DEBUG_ANY, "ldap_result error, rc = -1\n",
1208                                         0, 0, 0 );
1209 #endif /* !NEW_LOGGING */
1210                         rs->sr_err = LDAP_OTHER;
1211                         send_ldap_result( op, rs );
1212                         return 0; 
1213
1214                 case CREATE_ENTRY_ERR: 
1215 #ifdef NEW_LOGGING
1216                         LDAP_LOG( BACK_META, DETAIL1,
1217                                         "Error in parsing result \n",
1218                                         0, 0, 0 );
1219 #else /* !NEW_LOGGING */
1220                         Debug( LDAP_DEBUG_ANY, "Error in parsing result \n",
1221                                         0, 0, 0 );
1222 #endif /* !NEW_LOGGING */
1223                         rs->sr_err = LDAP_OTHER;
1224                         send_ldap_result( op, rs );
1225                         result->type = RESULT_ERR; 
1226                         return 0; 
1227
1228                 case SLIMIT_ERR: 
1229 #ifdef NEW_LOGGING
1230                         LDAP_LOG( BACK_META, DETAIL1, "Size limit exceeded \n",
1231                                         0, 0, 0 );
1232 #else /* !NEW_LOGGING */
1233                         Debug( LDAP_DEBUG_ANY, "Size limit exceeded \n",
1234                                         0, 0, 0 );
1235 #endif /* !NEW_LOGGING */
1236                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
1237                         send_ldap_result( op, rs );
1238                         result->type = RESULT_ERR; 
1239                         return 0;
1240
1241                 case ABANDON_ERR: 
1242 #ifdef NEW_LOGGING
1243                         LDAP_LOG( BACK_META, DETAIL1,
1244                                         "search operation abandoned \n",
1245                                         0, 0, 0 );
1246 #else /* !NEW_LOGGING */
1247                         Debug( LDAP_DEBUG_ANY, "search operation abandoned \n",
1248                                         0, 0, 0 );
1249 #endif /* !NEW_LOGGING */
1250                         result->type = RESULT_ERR; 
1251                         return 0; 
1252
1253                 default:
1254                         /* assert( 0 ); */
1255                         break;
1256                 }
1257                 if ( gotit == 0 ) {
1258                         tv.tv_sec = 0;
1259                         tv.tv_usec = 100000;
1260                         ldap_pvt_thread_yield();
1261                 } else {
1262                         tv.tv_sec = 0;
1263                         tv.tv_usec = 0;
1264                 }
1265         }
1266
1267         rs->sr_err = mres;
1268         rs->sr_text = err;
1269         rs->sr_matched = match;
1270
1271         send_ldap_result( op, rs );
1272
1273         rs->sr_text = NULL;
1274         rs->sr_matched = NULL;
1275
1276         if (err) 
1277                 free(err); 
1278
1279         if (match) 
1280                 free(match); 
1281     
1282         result->type = (mres == LDAP_SUCCESS) ? SUCCESS : RESULT_ERR; 
1283         return num_entries; 
1284 }
1285
1286 static Entry* 
1287 get_result_entry(
1288         Backend* be, 
1289         struct metaconn* lc, 
1290         struct metasingleconn* lsc, 
1291         int* msgid,
1292         int i, 
1293         struct timeval* tv, 
1294         struct exception* result)
1295 {
1296         Entry* entry; 
1297         LDAPMessage     *res, *e; 
1298         int rc; 
1299         int sres = LDAP_SUCCESS; 
1300
1301         rc = ldap_result( lsc->ld, msgid[ i ],
1302                         0, tv, &res );
1303
1304         if ( rc == 0 ) {
1305                 result->type = TIMEOUT_ERR; 
1306                 return NULL; 
1307         } else if ( rc == -1 ) {
1308                 result->rc = -1; 
1309                 result->type = RESULT_ERR; 
1310                 return NULL; 
1311         } else if ( rc == LDAP_RES_SEARCH_ENTRY ) {
1312                 e = ldap_first_entry( lsc->ld, res );
1313                 entry = meta_create_entry(be, lc, i, e, result);  
1314                 if (!entry) {
1315                         return NULL; 
1316                 }    
1317                 ldap_msgfree( res );
1318                 result->type = SUCCESS; 
1319                 return entry; 
1320         } else {
1321                 sres = ldap_result2error( lsc->ld,
1322                                 res, 1 );
1323                 result->rc = sres; 
1324                 result->type = RESULT_ERR; 
1325                 return NULL; 
1326         }
1327 }       
1328
1329 static void
1330 rewriteSession(
1331         struct rewrite_info* info, 
1332         const char* rewriteContext, 
1333         const char* string, 
1334         const void* cookie,  
1335         char** base, 
1336         struct exception* result)
1337 {
1338         int rc = rewrite_session(info, rewriteContext, string, cookie, base); 
1339         if (rc != REWRITE_REGEXEC_OK) {
1340                 result->rc = rc; 
1341                 result->type = REWRITING_ERR; 
1342
1343                 if (strcmp(rewriteContext, "searchBase") == 0) 
1344 #ifdef NEW_LOGGING
1345                         LDAP_LOG( BACK_META, DETAIL1,
1346                                 "Problem in rewriting search base\n", 0, 0, 0 );
1347 #else /* !NEW_LOGGING */
1348                         Debug( LDAP_DEBUG_ANY,
1349                                 "Problem in rewriting search base\n", 0, 0, 0 );
1350 #endif /* !NEW_LOGGING */
1351                 if (strcmp(rewriteContext, "searchFilter") == 0) 
1352 #ifdef NEW_LOGGING
1353                         LDAP_LOG( BACK_META, DETAIL1,
1354                                 "Problem in rewriting search filter\n",
1355                                 0, 0, 0 );
1356 #else /* !NEW_LOGGING */
1357                         Debug( LDAP_DEBUG_ANY,
1358                                 "Problem in rewriting search filter\n",
1359                                 0, 0, 0 );
1360 #endif /* !NEW_LOGGING */
1361                 if (strcmp(rewriteContext, "searchResult") == 0) 
1362 #ifdef NEW_LOGGING
1363                         LDAP_LOG( BACK_META, DETAIL1,
1364                                 "Problem in rewriting DN, or DN syntax "
1365                                 "attributes of search result\n", 0, 0, 0 );
1366 #else /* !NEW_LOGGING */
1367                         Debug( LDAP_DEBUG_ANY,
1368                                 "Problem in rewriting DN, or DN syntax "
1369                                 "attributes of search result\n", 0, 0, 0 );
1370 #endif /* !NEW_LOGGING */
1371                 if (strcmp(rewriteContext, "cacheBase") == 0) 
1372 #ifdef NEW_LOGGING
1373                         LDAP_LOG( BACK_META, DETAIL1,
1374                                 "Problem in rewriting search base with "
1375                                 "cache base\n", 0, 0, 0 );
1376 #else /* !NEW_LOGGING */
1377                         Debug( LDAP_DEBUG_ANY,
1378                                 "Problem in rewriting search base with "
1379                                 "cache base\n", 0, 0, 0 );
1380 #endif /* !NEW_LOGGING */
1381                 if (strcmp(rewriteContext, "cacheResult") == 0) 
1382 #ifdef NEW_LOGGING
1383                         LDAP_LOG( BACK_META, DETAIL1,
1384                                 "Problem in rewriting DN for cached entries\n",
1385                                 0, 0, 0 );
1386 #else /* !NEW_LOGGING */
1387                         Debug( LDAP_DEBUG_ANY,
1388                                 "Problem in rewriting DN for cached entries\n",
1389                                 0, 0, 0 );
1390 #endif /* !NEW_LOGGING */
1391                 if (strcmp(rewriteContext, "cacheReturn") == 0) 
1392 #ifdef NEW_LOGGING
1393                         LDAP_LOG( BACK_META, DETAIL1,
1394                                 "Problem in rewriting DN for answerable "
1395                                 "entries\n", 0, 0, 0 );
1396 #else /* !NEW_LOGGING */
1397                         Debug( LDAP_DEBUG_ANY,
1398                                 "Problem in rewriting DN for answerable "
1399                                 "entries\n", 0, 0, 0 );
1400 #endif /* !NEW_LOGGING */
1401         } else {
1402                 result->type = SUCCESS;
1403         }
1404 }
1405
1406 static int 
1407 get_attr_set(
1408         AttributeName* attrs, 
1409         query_manager* qm, 
1410         int num )
1411 {
1412         int i; 
1413         for (i=0; i<num; i++) {
1414                 if (attrscmp(attrs, qm->attr_sets[i].attrs)) 
1415                         return i;
1416         }
1417         return -1; 
1418 }
1419
1420 static int 
1421 attrscmp(
1422         AttributeName* attrs_in, 
1423         AttributeName* attrs)
1424 {
1425         int i, count1, count2; 
1426         if ((attrs_in==NULL) || (attrs==NULL)) 
1427                 return 1; 
1428         for ( count1=0;
1429               attrs_in && attrs_in[count1].an_name.bv_val != NULL;
1430               count1++ )
1431                 ;
1432         for ( count2=0;
1433               attrs && attrs[count2].an_name.bv_val != NULL;
1434               count2++) 
1435                 ;
1436         if ( count1 != count2 )
1437                 return 0; 
1438
1439         for ( i=0; i<count1; i++ ) {
1440                 if ( !an_find(attrs, &attrs_in[i].an_name ))
1441                         return 0; 
1442         }
1443         return 1; 
1444 }
1445
1446 static char* 
1447 cache_entries(
1448         Operation       *op,
1449         SlapReply       *rs,
1450         Entry** entry_array, 
1451         cache_manager* cm, 
1452         struct exception* result)
1453 {
1454         int             i; 
1455         int             return_val; 
1456         int             cache_size; 
1457         Entry           *e; 
1458         struct berval   query_uuid; 
1459         struct berval   crp_uuid; 
1460         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ], *crpid; 
1461         char            crpuuid[40]; 
1462         query_manager   *qm = cm->qm;
1463     
1464         result->type = SUCCESS; 
1465         query_uuid.bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf)); 
1466         query_uuid.bv_val = ch_strdup(uuidbuf);
1467
1468 #ifdef NEW_LOGGING
1469         LDAP_LOG( BACK_META, DETAIL1, "UUID for query being added = %s\n",
1470                         uuidbuf, 0, 0 );
1471 #else /* !NEW_LOGGING */
1472         Debug( LDAP_DEBUG_ANY, "UUID for query being added = %s\n",
1473                         uuidbuf, 0, 0 );
1474 #endif /* !NEW_LOGGING */
1475         
1476         for ( i=0; ( entry_array && (e=entry_array[i]) ); i++ ) {
1477 #ifdef NEW_LOGGING
1478                 LDAP_LOG( BACK_META, DETAIL2, "LOCKING REMOVE MUTEX\n",
1479                                 0, 0, 0 );
1480 #else /* !NEW_LOGGING */
1481                 Debug( LDAP_DEBUG_NONE, "LOCKING REMOVE MUTEX\n", 0, 0, 0 );
1482 #endif /* !NEW_LOGGING */
1483                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex); 
1484 #ifdef NEW_LOGGING
1485                 LDAP_LOG( BACK_META, DETAIL2, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1486 #else /* !NEW_LOGGING */
1487                 Debug( LDAP_DEBUG_NONE, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1488 #endif /* !NEW_LOGGING */
1489                 if ( cm->cache_size > (cm->thresh_hi) ) {
1490                         while(cm->cache_size > (cm->thresh_lo)) {
1491                                 crpid = cache_replacement(qm);
1492                                 if (crpid == NULL) {
1493                                         result->type = REMOVE_ERR; 
1494                                 } else {
1495                                         strcpy(crpuuid, crpid); 
1496                                         crp_uuid.bv_val = crpuuid; 
1497                                         crp_uuid.bv_len = strlen(crpuuid); 
1498 #ifdef NEW_LOGGING
1499                                         LDAP_LOG( BACK_META, DETAIL1,
1500                                                 "Removing query UUID %s\n",
1501                                                 crpuuid, 0, 0 );
1502 #else /* !NEW_LOGGING */
1503                                         Debug( LDAP_DEBUG_ANY,
1504                                                 "Removing query UUID %s\n",
1505                                                 crpuuid, 0, 0 );
1506 #endif /* !NEW_LOGGING */
1507                                         return_val = remove_query_data(op, rs,
1508                                                         &crp_uuid, result); 
1509 #ifdef NEW_LOGGING
1510                                         LDAP_LOG( BACK_META, DETAIL1,
1511                                                 "QUERY REMOVED, SIZE=%d\n",
1512                                                 return_val, 0, 0);
1513 #else /* !NEW_LOGGING */
1514                                         Debug( LDAP_DEBUG_ANY,
1515                                                 "QUERY REMOVED, SIZE=%d\n",
1516                                                 return_val, 0, 0);
1517 #endif /* !NEW_LOGGING */
1518                                         ldap_pvt_thread_mutex_lock(
1519                                                         &cm->cache_mutex ); 
1520                                         cm->total_entries -= result->rc; 
1521                                         cm->num_cached_queries--; 
1522 #ifdef NEW_LOGGING
1523                                         LDAP_LOG( BACK_META, DETAIL1,
1524                                                 "STORED QUERIES = %lu\n",
1525                                                 cm->num_cached_queries, 0, 0 );
1526 #else /* !NEW_LOGGING */
1527                                         Debug( LDAP_DEBUG_ANY,
1528                                                 "STORED QUERIES = %lu\n",
1529                                                 cm->num_cached_queries, 0, 0 );
1530 #endif /* !NEW_LOGGING */
1531                                         ldap_pvt_thread_mutex_unlock(
1532                                                         &cm->cache_mutex );
1533                                         cm->cache_size = (return_val >
1534                                                 cm->cache_size) ?
1535                                                 0 : (cm->cache_size-return_val);
1536 #ifdef NEW_LOGGING
1537                                         LDAP_LOG( BACK_META, DETAIL1,
1538                                                 "QUERY REMOVED, CACHE SIZE="
1539                                                 "%lu bytes %d entries\n",
1540                                                 cm->cache_size,
1541                                                 cm->total_entries, 0 );
1542 #else /* !NEW_LOGGING */
1543                                         Debug( LDAP_DEBUG_ANY,
1544                                                 "QUERY REMOVED, CACHE SIZE="
1545                                                 "%lu bytes %d entries\n",
1546                                                 cm->cache_size,
1547                                                 cm->total_entries, 0 );
1548 #endif /* !NEW_LOGGING */
1549                                 }
1550                         }
1551                 }
1552
1553                 rs->sr_entry = e;
1554                 return_val = merge_entry(op, rs, &query_uuid, result);
1555                 rs->sr_entry = NULL;
1556                 cm->cache_size += return_val;
1557 #ifdef NEW_LOGGING
1558                 LDAP_LOG( BACK_META, DETAIL1,
1559                         "ENTRY ADDED/MERGED, CACHE SIZE=%lu bytes\n",
1560                         cm->cache_size, 0, 0 );
1561 #else /* !NEW_LOGGING */
1562                 Debug( LDAP_DEBUG_ANY,
1563                         "ENTRY ADDED/MERGED, CACHE SIZE=%lu bytes\n",
1564                         cm->cache_size, 0, 0 );
1565 #endif /* !NEW_LOGGING */
1566 #ifdef NEW_LOGGING
1567                 LDAP_LOG( BACK_META, DETAIL2, "UNLOCKING REMOVE MUTEX\n",
1568                                 0, 0, 0 );
1569 #else /* !NEW_LOGGING */
1570                 Debug( LDAP_DEBUG_NONE, "UNLOCKING REMOVE MUTEX\n", 0, 0, 0 );
1571 #endif /* !NEW_LOGGING */
1572                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex); 
1573 #ifdef NEW_LOGGING
1574                 LDAP_LOG( BACK_META, DETAIL2, "UNLOCKED REMOVE MUTEX\n",
1575                                 0, 0, 0 );
1576 #else /* !NEW_LOGGING */
1577                 Debug( LDAP_DEBUG_NONE, "UNLOCKED REMOVE MUTEX\n", 0, 0, 0 );
1578 #endif /* !NEW_LOGGING */
1579                 if (result->type != SUCCESS) 
1580                         return 0; 
1581                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
1582                 cm->total_entries += result->rc; 
1583 #ifdef NEW_LOGGING
1584                 LDAP_LOG( BACK_META, DETAIL1,
1585                         "ENTRY ADDED/MERGED, SIZE=%d, CACHED ENTRIES=%d\n",
1586                         return_val, cm->total_entries, 0 );
1587 #else /* !NEW_LOGGING */
1588                 Debug( LDAP_DEBUG_ANY,
1589                         "ENTRY ADDED/MERGED, SIZE=%d, CACHED ENTRIES=%d\n",
1590                         return_val, cm->total_entries, 0 );
1591 #endif /* !NEW_LOGGING */
1592                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
1593         }
1594         ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
1595         cm->num_cached_queries++; 
1596 #ifdef NEW_LOGGING
1597         LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1598                         cm->num_cached_queries, 0, 0 );
1599 #else /* !NEW_LOGGING */
1600         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1601                         cm->num_cached_queries, 0, 0 );
1602 #endif /* !NEW_LOGGING */
1603         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
1604
1605         return query_uuid.bv_val; 
1606 }
1607
1608 static int 
1609 is_temp_answerable(
1610         int attr_set, 
1611         struct berval* tempstr, 
1612         query_manager* qm, 
1613         int template_id )
1614 {
1615         int i; 
1616         int* id_array; 
1617         char* str;
1618         int result = 0; 
1619         i = qm->templates[template_id].attr_set_index; 
1620         str = qm->templates[template_id].querystr; 
1621
1622         if (attr_set == i) {
1623                 result = 1; 
1624         } else { 
1625                 id_array = qm->attr_sets[attr_set].ID_array;    
1626
1627                 while (*id_array != -1) {
1628                         if (*id_array == i) 
1629                                 result = 1; 
1630                         id_array++; 
1631                 }
1632         }
1633         if (!result) 
1634                 return 0; 
1635         if (strcasecmp(str, tempstr->bv_val) == 0)  
1636                 return 1; 
1637         return 0; 
1638 }
1639
1640 static void 
1641 consistency_check(Operation *op, SlapReply *rs, Backend* glue_be)
1642 {
1643         struct metainfo *li = ( struct metainfo * )op->o_bd->be_private;
1644         cache_manager*  cm = li->cm; 
1645         query_manager* qm = cm->qm; 
1646         CachedQuery* query, *query_prev; 
1647         time_t curr_time; 
1648         struct berval uuid;  
1649         struct exception result; 
1650         int i, return_val; 
1651         QueryTemplate* templ;
1652         Backend         *be = op->o_bd;
1653
1654         op->o_bd = glue_be;
1655       
1656         for (i=0; qm->templates[i].querystr; i++) {
1657                 templ = qm->templates + i; 
1658                 query = templ->query_last; 
1659                 curr_time = slap_get_time(); 
1660                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex); 
1661                 while (query && (query->expiry_time < curr_time)) {
1662                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex); 
1663                         remove_query(qm, query); 
1664                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex); 
1665 #ifdef NEW_LOGGING
1666                         LDAP_LOG( BACK_META, DETAIL1, "Lock CR index = %d\n",
1667                                         i, 0, 0 );
1668 #else /* !NEW_LOGGING */
1669                         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n",
1670                                         i, 0, 0 );
1671 #endif /* !NEW_LOGGING */
1672                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);  
1673                         remove_from_template(query, templ); 
1674 #ifdef NEW_LOGGING
1675                         LDAP_LOG( BACK_META, DETAIL1,
1676                                         "TEMPLATE %d QUERIES-- %d\n",
1677                                         i, templ->no_of_queries, 0 );
1678 #else /* !NEW_LOGGING */
1679                         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
1680                                         i, templ->no_of_queries, 0 );
1681 #endif /* !NEW_LOGGING */
1682 #ifdef NEW_LOGGING
1683                         LDAP_LOG( BACK_META, DETAIL1, "Unlock CR index = %d\n",
1684                                         i, 0, 0 );
1685 #else /* !NEW_LOGGING */
1686                         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n",
1687                                         i, 0, 0 );
1688 #endif /* !NEW_LOGGING */
1689                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);  
1690                         uuid.bv_val = query->q_uuid; 
1691                         uuid.bv_len = strlen(query->q_uuid); 
1692                         return_val = remove_query_data(op, rs, &uuid, &result); 
1693 #ifdef NEW_LOGGING
1694                         LDAP_LOG( BACK_META, DETAIL1,
1695                                         "STALE QUERY REMOVED, SIZE=%d\n",
1696                                         return_val, 0, 0 );
1697 #else /* !NEW_LOGGING */
1698                         Debug( LDAP_DEBUG_ANY, "STALE QUERY REMOVED, SIZE=%d\n",
1699                                                 return_val, 0, 0 );
1700 #endif /* !NEW_LOGGING */
1701                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
1702                         cm->total_entries -= result.rc; 
1703                         cm->num_cached_queries--; 
1704 #ifdef NEW_LOGGING
1705                         LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1706                                         cm->num_cached_queries, 0, 0 );
1707 #else /* !NEW_LOGGING */
1708                         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1709                                         cm->num_cached_queries, 0, 0 );
1710 #endif /* !NEW_LOGGING */
1711                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
1712                         cm->cache_size = (return_val > cm->cache_size) ?
1713                                                 0: (cm->cache_size-return_val);
1714 #ifdef NEW_LOGGING
1715                         LDAP_LOG( BACK_META, DETAIL1,
1716                                 "STALE QUERY REMOVED, CACHE SIZE=%lu bytes %d "
1717                                 "entries\n", cm->cache_size,
1718                                 cm->total_entries, 0 );
1719 #else /* !NEW_LOGGING */
1720                         Debug( LDAP_DEBUG_ANY,
1721                                 "STALE QUERY REMOVED, CACHE SIZE=%lu bytes %d "
1722                                 "entries\n", cm->cache_size,
1723                                 cm->total_entries, 0 );
1724 #endif /* !NEW_LOGGING */
1725                         query_prev = query; 
1726                         query = query->prev; 
1727                         free_query(query_prev); 
1728                 }
1729                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex); 
1730         }
1731
1732         op->o_bd = be;
1733 }
1734
1735 static int
1736 cache_back_sentry(
1737         Operation* op, 
1738         SlapReply *rs )
1739
1740         slap_callback           *cb = op->o_callback; 
1741         struct metainfo         *li = ( struct metainfo * )op->o_bd->be_private;
1742  
1743         char                    *ename = NULL;
1744         struct exception        result;
1745         struct berval           dn;
1746         struct berval           ndn;
1747
1748         dn = rs->sr_entry->e_name; 
1749         ndn = rs->sr_entry->e_nname; 
1750
1751         rewriteSession( li->rwinfo, "cacheReturn",
1752                         rs->sr_entry->e_name.bv_val, op->o_conn,
1753                         &ename, &result );  
1754         ber_str2bv(ename, strlen(ename), 0, &rs->sr_entry->e_name); 
1755         /* FIXME: should we normalize this? */
1756         ber_dupbv(&rs->sr_entry->e_nname, &rs->sr_entry->e_name); 
1757
1758         op->o_callback = NULL; 
1759
1760         send_search_entry( op, rs );
1761  
1762         rs->sr_entry->e_name = dn; 
1763         rs->sr_entry->e_nname = ndn; 
1764
1765         op->o_callback = cb; 
1766
1767         return 0;  
1768 }
1769 #endif