]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
Overlay build environment
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003 The OpenLDAP Foundation.
5  * Portions Copyright 2003 IBM Corporation.
6  * Portions Copyright 2003 Symas Corporation.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by Apurva Kumar for inclusion
19  * in OpenLDAP Software.
20  *
21  * This work was rewritten by Howard Chu for OpenLDAP.
22  */
23
24 #include "portable.h"
25
26 #ifdef SLAPD_OVER_PROXYCACHE
27
28 #include <stdio.h>
29
30 #include <ac/string.h>
31 #include <ac/time.h>
32
33 #include "slap.h"
34 #include "ldap_pvt.h"
35 #include "lutil.h"
36
37 /* query cache structs */
38 /* query */
39
40 typedef struct Query_s {
41         Filter*         filter;         /* Search Filter */
42         AttributeName*  attrs;          /* Projected attributes */
43         struct berval   base;           /* Search Base */
44         int             scope;          /* Search scope */
45 } Query;
46
47 /* struct representing a cached query */
48 typedef struct cached_query_s {
49         Query                           query;          /* LDAP query */ 
50         struct berval                   q_uuid;         /* query identifier */ 
51         int                             template_id;    /* template of the query */ 
52         time_t                          expiry_time;    /* time till the query is considered valid */ 
53         struct cached_query_s           *next;          /* next query in the template */
54         struct cached_query_s           *prev;          /* previous query in the template */
55         struct cached_query_s           *lru_up;        /* previous query in the LRU list */ 
56         struct cached_query_s           *lru_down;      /* next query in the LRU list */ 
57 } CachedQuery; 
58
59 /* struct representing a query template
60  * e.g. template string = &(cn=)(mail=) 
61  */
62 typedef struct query_template_s {
63         struct berval   querystr;       /* Filter string corresponding to the QT */
64         int             attr_set_index; /* determines the projected attributes */ 
65
66         CachedQuery*    query;          /* most recent query cached for the template */ 
67         CachedQuery*    query_last;     /* oldest query cached for the template */              
68
69         int             no_of_queries;  /* Total number of queries in the template */
70         long            ttl;            /* TTL for the queries of this template */ 
71         ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */ 
72 } QueryTemplate;
73
74 /* 
75  * Represents a set of projected attributes and any
76  * supersets among all specified sets of attributes. 
77  */
78
79 struct attr_set {
80         AttributeName*  attrs;          /* specifies the set */
81         int             count;          /* number of attributes */ 
82         int*            ID_array;       /* array of indices of supersets of 'attrs' */ 
83 };
84
85 struct query_manager_s; 
86
87 /* prototypes for functions for 1) query containment 
88  * 2) query addition, 3) cache replacement 
89  */
90 typedef int     (QCfunc)(struct query_manager_s*, Query*, int );
91 typedef void    (AddQueryfunc)(struct query_manager_s*, Query*, int, struct berval*);
92 typedef void    (CRfunc)(struct query_manager_s*, struct berval * );
93
94 /* LDAP query cache */ 
95 typedef struct query_manager_s {
96         struct attr_set*        attr_sets;              /* possible sets of projected attributes */
97         QueryTemplate*          templates;              /* cacheable templates */
98
99         CachedQuery*            lru_top;                /* top and bottom of LRU list */
100         CachedQuery*            lru_bottom;
101
102         ldap_pvt_thread_mutex_t         lru_mutex;      /* mutex for accessing LRU list */
103
104         /* Query cache methods */
105         QCfunc                  *qcfunc;                        /* Query containment*/  
106         CRfunc                  *crfunc;                        /* cache replacement */
107         AddQueryfunc    *addfunc;                       /* add query */ 
108 } query_manager; 
109
110 /* LDAP query cache manager */ 
111 typedef struct cache_manager_s {
112         BackendInfo *bi;        /* underlying database info */
113         void *be_private;       /* for the underlying database */
114         unsigned long   num_cached_queries;             /* total number of cached queries */
115         unsigned long   max_queries;                    /* upper bound on # of cached queries */ 
116         int     numattrsets;                    /* number of attribute sets */
117         int     numtemplates;                   /* number of cacheable templates */
118         int     cur_entries;                    /* current number of entries cached */ 
119         int     max_entries;                    /* max number of entries cached */ 
120         int     num_entries_limit;              /* max # of entries in a cacheable query */ 
121
122         int     cc_period;              /* interval between successive consistency checks (sec) */ 
123         int     cc_thread_started; 
124         ldap_pvt_thread_t   cc_thread; 
125
126         ldap_pvt_thread_mutex_t         cache_mutex;            
127         ldap_pvt_thread_mutex_t         remove_mutex;
128
129         query_manager*   qm;    /* query cache managed by the cache manager */ 
130 } cache_manager; 
131
132 static AttributeDescription *ad_queryid;
133 static char *queryid_schema = "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
134                         "DESC 'list of queries the entry belongs to' "
135                         "EQUALITY octetStringMatch "
136                         "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
137                         "NO-USER-MODIFICATION USAGE directoryOperation )";
138
139 static int
140 merge_entry(
141         Operation               *op,
142         Entry                   *e,
143         struct berval*          query_uuid )
144 {
145         int             rc;
146         Modifications* modlist = NULL;
147         const char*     text = NULL;
148         Attribute               *attr;
149         char                    textbuf[SLAP_TEXT_BUFLEN];
150         size_t                  textlen = sizeof(textbuf);
151
152         SlapReply sreply = {REP_RESULT};
153
154         slap_callback cb = { slap_null_cb, NULL };
155
156         attr = e->e_attrs;
157         e->e_attrs = NULL;
158
159         /* add queryid attribute */     
160         attr_merge_one( e, ad_queryid, query_uuid, NULL );
161
162         /* append the attribute list from the fetched entry */
163         e->e_attrs->a_next = attr;
164
165         op->o_tag = LDAP_REQ_ADD;
166         op->o_protocol = LDAP_VERSION3;
167         op->o_callback = &cb;
168         op->o_time = slap_get_time();
169         op->o_do_not_cache = 1;
170
171         op->ora_e = e;
172         rc = op->o_bd->be_add( op, &sreply );
173
174         if ( rc != LDAP_SUCCESS ) {
175                 if ( rc == LDAP_ALREADY_EXISTS ) {
176                         slap_entry2mods( e, &modlist, &text, textbuf, textlen );
177                         modlist->sml_op = LDAP_MOD_ADD;
178                         op->o_tag = LDAP_REQ_MODIFY;
179                         op->orm_modlist = modlist;
180                         op->o_req_dn = e->e_name;
181                         op->o_req_ndn = e->e_nname;
182                         rc = op->o_bd->be_modify( op, &sreply );
183                         slap_mods_free( modlist );
184                 } else if ( rc == LDAP_REFERRAL ||
185                                         rc == LDAP_NO_SUCH_OBJECT ) {
186                         syncrepl_add_glue( op, e );
187                 } else {
188                         rc = 0;
189                 }
190         }
191
192         return rc;
193 }
194
195 /* compare base and scope of incoming and cached queries */
196 static int base_scope_compare(
197         struct berval* ndn_stored, 
198         struct berval* ndn_incoming, 
199         int scope_stored, 
200         int scope_incoming      )
201 {
202         struct berval pdn_incoming = { 0, NULL };
203
204         if (scope_stored < scope_incoming)
205                 return 0;
206
207         if ( !dnIsSuffix(ndn_incoming, ndn_stored))
208                 return 0;
209         
210         switch(scope_stored) {
211         case LDAP_SCOPE_BASE:
212                 return (ndn_incoming->bv_len == ndn_stored->bv_len);
213
214         case LDAP_SCOPE_ONELEVEL:
215                 switch(scope_incoming){
216                 case LDAP_SCOPE_BASE:
217                         dnParent(ndn_incoming, &pdn_incoming); 
218                         return (pdn_incoming.bv_len == ndn_stored->bv_len);
219
220                 case LDAP_SCOPE_ONELEVEL:
221                         return (ndn_incoming->bv_len == ndn_stored->bv_len);
222
223                 default:
224                         return 0;
225                 }
226         case LDAP_SCOPE_SUBTREE:
227                 return 1;
228                 break;
229         default:
230                 return 0;
231                 break;  
232     }
233 }
234
235 /* add query on top of LRU list */
236 static void 
237 add_query_on_top (query_manager* qm, CachedQuery* qc) 
238 {
239         CachedQuery* top = qm->lru_top; 
240         Query* q = (Query*)qc; 
241     
242         qm->lru_top = qc; 
243
244         if (top) 
245                 top->lru_up = qc; 
246         else
247                 qm->lru_bottom = qc; 
248        
249         qc->lru_down = top; 
250         qc->lru_up = NULL; 
251 #ifdef NEW_LOGGING
252         LDAP_LOG( BACK_META, DETAIL1, "Base of added query = %s\n",
253                         q->base.bv_val, 0, 0 );
254 #else
255         Debug( LDAP_DEBUG_ANY, "Base of added query = %s\n",
256                         q->base.bv_val, 0, 0 );
257 #endif
258 }
259
260 /* remove_query from LRU list */
261
262 static void 
263 remove_query (query_manager* qm, CachedQuery* qc) 
264 {
265         CachedQuery* up; 
266         CachedQuery* down; 
267
268         if (!qc) 
269                 return; 
270
271         up = qc->lru_up; 
272         down = qc->lru_down; 
273
274         if (!up) 
275                 qm->lru_top = down; 
276
277         if (!down) 
278                 qm->lru_bottom = up; 
279
280         if (down) 
281                 down->lru_up = up; 
282
283         if (up) 
284                 up->lru_down = down; 
285
286         qc->lru_up = qc->lru_down = NULL; 
287 }
288
289 static void
290 invert_string( struct berval *bv )
291 {
292         int i; 
293         char c;
294
295         for (i=0; i<bv->bv_len/2; i++) {
296                 c = bv->bv_val[i];
297                 bv->bv_val[i] = bv->bv_val[bv->bv_len-i-1];
298                 bv->bv_val[bv->bv_len-i-1] = c;
299         }
300 }       
301
302 /* find and remove string2 from string1 
303  * from start if position = 1, 
304  * from end if position = 3,
305  * from anywhere if position = 2
306  */
307
308 static int 
309 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
310 {
311         char* temp; 
312         int len; 
313         int ret=0;
314
315         char* arg1, *arg2;  
316         char* string1=ber1->bv_val;
317         char* string2=ber2->bv_val;
318
319         if (string2 == NULL) 
320                 return 1; 
321         if (string1 == NULL) 
322                 return 0; 
323
324         if (position == 3) {
325                 invert_string(ber1); 
326                 invert_string(ber2); 
327         }
328
329         arg1 = string1; 
330         arg2 = string2; 
331
332         temp = strstr(arg1, arg2); 
333
334         len = ber2->bv_len;
335
336         if ( temp && (position == 2 || temp == arg1) ) {
337                 string1 = temp+len;
338                 strcpy( arg1, string1 );
339                 ber1->bv_len -= len;
340                 ret = 1;
341         }
342         if ( position == 3 ) {
343                 invert_string(ber1); 
344                 invert_string(ber2); 
345         }
346         return ret;
347 }
348
349
350 static struct berval*  
351 merge_init_final(struct berval* init, struct berval* any, struct berval* final)
352 {
353         struct berval* merged, *temp; 
354         int i, any_count, count; 
355
356         for (any_count=0; any && any[any_count].bv_val; any_count++)
357                 ;
358
359         count = any_count; 
360
361         if (init->bv_val) 
362                 count++; 
363         if (final->bv_val)
364                 count++; 
365
366         merged = (struct berval*)(ch_malloc((count+1)*sizeof(struct berval))); 
367         temp = merged; 
368
369         if (init->bv_val) {
370                 *temp++ = *init;
371         }
372
373         for (i=0; i<any_count; i++) {
374                 *temp++ = *any++;
375         } 
376
377         if (final->bv_val){ 
378                 *temp++ = *final;
379         }        
380         temp->bv_val = NULL; 
381         temp->bv_len = 0; 
382         return merged; 
383 }
384
385 static int
386 strings_containment(struct berval* stored, struct berval* incoming)
387 {
388         struct berval* element;
389         int k=0;
390         int j, rc = 0; 
391         
392         for ( element=stored; element->bv_val != NULL; element++ ) {
393                 for (j = k; incoming[j].bv_val != NULL; j++) {
394                         if (find_and_remove(&(incoming[j]), element, 2)) {
395                                 k = j; 
396                                 rc = 1; 
397                                 break; 
398                         }
399                         rc = 0; 
400                 }
401                 if ( rc ) {
402                         continue; 
403                 } else {
404                         return 0;
405                 }
406         }   
407         return 1;
408 }
409
410 static int
411 substr_containment_substr(Filter* stored, Filter* incoming) 
412 {
413         int i; 
414         int rc = 0;
415         int any_count = 0; 
416
417         struct berval init_incoming;
418         struct berval final_incoming;
419         struct berval *any_incoming = NULL; 
420         struct berval *remaining_incoming = NULL; 
421
422         if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val)) 
423            || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val))) 
424                 return 0; 
425  
426         
427         ber_dupbv(&init_incoming, &(incoming->f_sub_initial)); 
428         ber_dupbv(&final_incoming, &(incoming->f_sub_final)); 
429
430         if (incoming->f_sub_any) { 
431                 for ( any_count=0; incoming->f_sub_any[any_count].bv_val != NULL;
432                                 any_count++ )
433                         ;
434             
435                 any_incoming = (struct berval*)ch_malloc((any_count+1) *
436                                                 sizeof(struct berval)); 
437             
438                 for (i=0; i<any_count; i++) {
439                         ber_dupbv(&(any_incoming[i]), &(incoming->f_sub_any[i])); 
440                 }
441                 any_incoming[any_count].bv_val = NULL; 
442                 any_incoming[any_count].bv_len = 0; 
443         }
444   
445         if (find_and_remove(&init_incoming, 
446                         &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming, 
447                         &(stored->f_sub_final), 3)) 
448         {
449                 if (stored->f_sub_any == NULL) {
450                         rc = 1; 
451                         goto final; 
452                 }
453                 remaining_incoming = merge_init_final(&init_incoming,
454                                                 any_incoming, &final_incoming); 
455                 rc = strings_containment(stored->f_sub_any, remaining_incoming);
456         }       
457 final:
458         free(init_incoming.bv_val);
459         free(final_incoming.bv_val); 
460         if (any_incoming) ber_bvarray_free( any_incoming );
461         free(remaining_incoming);
462                 
463         return rc; 
464 }
465
466 static int
467 substr_containment_equality(Filter* stored, Filter* incoming) 
468 {
469         struct berval incoming_val[2];
470         int rc = 0;
471  
472         ber_dupbv(incoming_val, &(incoming->f_av_value));
473         incoming_val[1].bv_val = NULL;
474         incoming_val[1].bv_len = 0;
475  
476         if (find_and_remove(incoming_val,
477                         &(stored->f_sub_initial), 1) && find_and_remove(incoming_val, 
478                         &(stored->f_sub_final), 3)) {
479                 if (stored->f_sub_any == NULL){ 
480                         rc = 1;
481                         goto final;
482                 }       
483                 rc = strings_containment(stored->f_sub_any, incoming_val);
484         }
485 final:
486         free(incoming_val[0].bv_val);
487         return rc;
488 }
489
490 /* check whether query is contained in any of 
491  * the cached queries in template template_index 
492  */
493 static int 
494 query_containment(query_manager *qm, 
495                   Query *query, 
496                   int template_index)
497 {
498         QueryTemplate* templa= qm->templates;
499         CachedQuery* qc;
500         Query* q;
501         Filter* inputf = query->filter; 
502         struct berval* base = &(query->base); 
503         int scope = query->scope; 
504         int res=0;
505         Filter* fs;
506         Filter* fi;
507         int ret, rc; 
508         const char* text; 
509
510         MatchingRule* mrule = NULL;
511         if (inputf != NULL) {
512 #ifdef NEW_LOGGING
513                 LDAP_LOG( BACK_META, DETAIL1, "Lock QC index = %d\n",
514                                 template_index, 0, 0 );
515 #else
516                 Debug( LDAP_DEBUG_ANY, "Lock QC index = %d\n",
517                                 template_index, 0, 0 );
518 #endif
519                 ldap_pvt_thread_rdwr_rlock(&(templa[template_index].t_rwlock));  
520                 for(qc=templa[template_index].query; qc != NULL; qc= qc->next) {
521                         q = (Query*)qc; 
522                         if(base_scope_compare(&(q->base), base, q->scope, scope)) {
523                                 fi = inputf;
524                                 fs = q->filter;          
525                                 do {    
526                                         res=0;
527                                         switch (fs->f_choice) {
528                                         case LDAP_FILTER_EQUALITY:
529                                                 if (fi->f_choice == LDAP_FILTER_EQUALITY) 
530                                                         mrule = fs->f_ava->aa_desc->ad_type->sat_equality; 
531                                                 else 
532                                                         ret = 1; 
533                                                 break; 
534                                         case LDAP_FILTER_GE:
535                                         case LDAP_FILTER_LE:
536                                                 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering; 
537                                                 break; 
538                                         default: 
539                                                 mrule = NULL;   
540                                         }
541                                         if (mrule) { 
542                                                 rc = value_match(&ret, fs->f_ava->aa_desc, mrule, 
543                                                         SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, 
544                                                         &(fi->f_ava->aa_value), 
545                                                         &(fs->f_ava->aa_value), &text); 
546                                                 if (rc != LDAP_SUCCESS) {
547                                                         ldap_pvt_thread_rdwr_runlock(&(templa[template_index].t_rwlock));  
548 #ifdef NEW_LOGGING
549                                                         LDAP_LOG( BACK_META, DETAIL1,
550                                                         "Unlock: Exiting QC index=%d\n",
551                                                         template_index, 0, 0 );
552 #else
553                                                         Debug( LDAP_DEBUG_ANY,
554                                                         "Unlock: Exiting QC index=%d\n",
555                                                         template_index, 0, 0 );
556 #endif
557                                                         return 0; 
558                                                 }
559                                         }
560                                         switch (fs->f_choice) {
561                                         case LDAP_FILTER_OR: 
562                                         case LDAP_FILTER_AND:
563                                                 fs = fs->f_and;
564                                                 fi = fi->f_and;
565                                                 res=1;
566                                                 break; 
567                                         case LDAP_FILTER_SUBSTRINGS: 
568                                                 /* check if the equality query can be 
569                                                 * answered with cached substring query */
570                                                 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
571                                                         && substr_containment_equality(
572                                                         fs, fi))
573                                                         res=1;          
574                                                 /* check if the substring query can be 
575                                                 * answered with cached substring query */
576                                                 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
577                                                         ) && substr_containment_substr(
578                                                         fs, fi))
579                                                         res= 1;
580                                                 fs=fs->f_next;
581                                                 fi=fi->f_next;  
582                                                 break; 
583                                         case LDAP_FILTER_PRESENT: 
584                                                 res=1;
585                                                 fs=fs->f_next;
586                                                 fi=fi->f_next;  
587                                                 break; 
588                                         case LDAP_FILTER_EQUALITY: 
589                                                 if (ret == 0) 
590                                                         res = 1;
591                                                 fs=fs->f_next;
592                                                 fi=fi->f_next;  
593                                                 break; 
594                                         case LDAP_FILTER_GE: 
595                                                 if (ret >= 0)
596                                                         res = 1; 
597                                                 fs=fs->f_next;
598                                                 fi=fi->f_next;  
599                                                 break;
600                                         case LDAP_FILTER_LE: 
601                                                 if (ret <= 0)
602                                                         res = 1; 
603                                                 fs=fs->f_next;
604                                                 fi=fi->f_next;  
605                                                 break;
606                                         case LDAP_FILTER_NOT:
607                                                 res=0;
608                                                 break;
609                                         default:
610                                                 break;
611                                         } 
612                                 } while((res) && (fi != NULL) && (fs != NULL));
613
614                                 if(res) {
615                                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex); 
616                                         if (qm->lru_top != qc) {
617                                                 remove_query(qm, qc); 
618                                                 add_query_on_top(qm, qc); 
619                                         }
620                                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex); 
621                                         return 1;
622                                 }       
623                         }
624                 }
625 #ifdef NEW_LOGGING
626                 LDAP_LOG( BACK_META, DETAIL1,
627                         "Not answerable: Unlock QC index=%d\n",
628                         template_index, 0, 0 );
629 #else
630                 Debug( LDAP_DEBUG_ANY,
631                         "Not answerable: Unlock QC index=%d\n",
632                         template_index, 0, 0 );
633 #endif
634                 ldap_pvt_thread_rdwr_runlock(&(templa[template_index].t_rwlock));  
635         }
636         return 0; 
637 }
638
639 static void 
640 free_query (CachedQuery* qc) 
641 {
642         Query* q = (Query*)qc; 
643         free(qc->q_uuid.bv_val); 
644         filter_free(q->filter); 
645         free (q->base.bv_val); 
646
647         free(q->attrs); 
648         free(qc); 
649 }
650
651
652 /* Add query to query cache */
653 static void add_query(
654         query_manager* qm, 
655         Query* query, 
656         int template_index, 
657         struct berval* uuid)
658 {
659         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
660         QueryTemplate* templ = (qm->templates)+template_index;  
661         Query* new_query;
662         new_cached_query->template_id = template_index; 
663         new_cached_query->q_uuid = *uuid; 
664         new_cached_query->lru_up = NULL; 
665         new_cached_query->lru_down = NULL; 
666         new_cached_query->expiry_time = slap_get_time() + templ->ttl; 
667 #ifdef NEW_LOGGING
668         LDAP_LOG( BACK_META, DETAIL1, "Added query expires at %ld\n",
669                         (long) new_cached_query->expiry_time, 0, 0 );
670 #else
671         Debug( LDAP_DEBUG_ANY, "Added query expires at %ld\n",
672                         (long) new_cached_query->expiry_time, 0, 0 );
673 #endif
674         new_query = (Query*)new_cached_query; 
675
676         ber_dupbv(&new_query->base, &query->base);
677         new_query->scope = query->scope; 
678         new_query->filter = query->filter;
679         new_query->attrs = query->attrs; 
680
681         /* Adding a query    */
682 #ifdef NEW_LOGGING
683         LDAP_LOG( BACK_META, DETAIL1, "Lock AQ index = %d\n",
684                         template_index, 0, 0 );
685 #else
686         Debug( LDAP_DEBUG_ANY, "Lock AQ index = %d\n",
687                         template_index, 0, 0 );
688 #endif
689         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);  
690         if (templ->query == NULL) 
691                 templ->query_last = new_cached_query; 
692         else 
693                 templ->query->prev = new_cached_query; 
694         new_cached_query->next = templ->query; 
695         new_cached_query->prev = NULL; 
696         templ->query = new_cached_query; 
697         templ->no_of_queries++; 
698 #ifdef NEW_LOGGING
699         LDAP_LOG( BACK_META, DETAIL1, "TEMPLATE %d QUERIES++ %d\n",
700                         template_index, templ->no_of_queries, 0 );
701 #else
702         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES++ %d\n",
703                         template_index, templ->no_of_queries, 0 );
704 #endif
705
706 #ifdef NEW_LOGGING
707         LDAP_LOG( BACK_META, DETAIL1, "Unlock AQ index = %d \n",
708                         template_index, 0, 0 );
709 #else
710         Debug( LDAP_DEBUG_ANY, "Unlock AQ index = %d \n",
711                         template_index, 0, 0 );
712 #endif
713         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);  
714
715         /* Adding on top of LRU list  */
716         ldap_pvt_thread_mutex_lock(&qm->lru_mutex); 
717         add_query_on_top(qm, new_cached_query);  
718         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex); 
719 }
720
721 static void
722 remove_from_template (CachedQuery* qc, QueryTemplate* template)
723 {
724         if (!qc->prev && !qc->next) {
725                 template->query_last = template->query = NULL; 
726         } else if (qc->prev == NULL) {
727                 qc->next->prev = NULL; 
728                 template->query = qc->next; 
729         } else if (qc->next == NULL) {
730                 qc->prev->next = NULL; 
731                 template->query_last = qc->prev; 
732         } else {
733                 qc->next->prev = qc->prev; 
734                 qc->prev->next = qc->next; 
735         }
736
737         template->no_of_queries--;  
738 }
739
740 /* remove bottom query of LRU list from the query cache */      
741 static void cache_replacement(query_manager* qm, struct berval *result)
742 {
743         CachedQuery* bottom; 
744         int temp_id;
745
746         ldap_pvt_thread_mutex_lock(&qm->lru_mutex); 
747         bottom = qm->lru_bottom; 
748
749         result->bv_val = NULL;
750         result->bv_len = 0;
751
752         if (!bottom) {
753 #ifdef NEW_LOGGING
754                 LDAP_LOG ( BACK_META, DETAIL1,
755                         "Cache replacement invoked without "
756                         "any query in LRU list\n", 0, 0, 0 );
757 #else
758                 Debug ( LDAP_DEBUG_ANY,
759                         "Cache replacement invoked without "
760                         "any query in LRU list\n", 0, 0, 0 );
761 #endif
762                 return;
763         }
764
765         temp_id = bottom->template_id;
766         remove_query(qm, bottom); 
767         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex); 
768
769         *result = bottom->q_uuid; 
770         bottom->q_uuid.bv_val = NULL;
771
772 #ifdef NEW_LOGGING
773         LDAP_LOG( BACK_META, DETAIL1, "Lock CR index = %d\n", temp_id, 0, 0 );
774 #else
775         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n", temp_id, 0, 0 );
776 #endif
777         ldap_pvt_thread_rdwr_wlock(&(qm->templates[temp_id].t_rwlock));  
778         remove_from_template(bottom, (qm->templates+temp_id)); 
779 #ifdef NEW_LOGGING
780         LDAP_LOG( BACK_META, DETAIL1, "TEMPLATE %d QUERIES-- %d\n",
781                 temp_id, qm->templates[temp_id].no_of_queries, 0 );
782 #else
783         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
784                 temp_id, qm->templates[temp_id].no_of_queries, 0 );
785 #endif
786 #ifdef NEW_LOGGING
787         LDAP_LOG( BACK_META, DETAIL1, "Unlock CR index = %d\n", temp_id, 0, 0 );
788 #else
789         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n", temp_id, 0, 0 );
790 #endif
791         ldap_pvt_thread_rdwr_wunlock(&(qm->templates[temp_id].t_rwlock));  
792         free_query(bottom); 
793 }
794
795 struct query_info {
796         struct berval*          uuid; 
797         int                     deleted; 
798 }; 
799    
800 static int
801 remove_func (
802         Operation       *op,
803         SlapReply       *rs
804 )
805 {
806         struct query_info       *info = op->o_callback->sc_private;
807         int                     count = 0;
808         Modifications           mod;
809         struct berval vals[2];
810
811         Attribute               *attr;
812         Operation               op_tmp = *op;
813
814         SlapReply               sreply = {REP_RESULT}; 
815
816         if (rs->sr_type == REP_RESULT) 
817                 return 0; 
818
819         for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
820                 if (attr->a_desc == ad_queryid) {
821                         for (count=0; attr->a_vals[count].bv_val; count++) 
822                                 ;
823                         break; 
824                 }
825         }       
826
827         if (count == 0) {
828                 return 0; 
829         }
830         if (count == 1) {
831 #ifdef NEW_LOGGING
832                 LDAP_LOG( BACK_META, DETAIL1,
833                                 "DELETING ENTRY TEMPLATE=%s\n",
834                                 attr->a_vals[0].bv_val, 0, 0 );
835 #else
836                 Debug( LDAP_DEBUG_ANY, "DELETING ENTRY TEMPLATE=%s\n",
837                                 attr->a_vals[0].bv_val, 0, 0 );
838 #endif
839
840                 op_tmp.o_req_dn = rs->sr_entry->e_name;
841                 op_tmp.o_req_ndn = rs->sr_entry->e_nname;
842
843                 if (op->o_bd->be_delete(&op_tmp, rs) == LDAP_SUCCESS) {
844                         info->deleted++; 
845                 }
846                 return 0; 
847         }
848
849         vals[0] = *info->uuid;
850         vals[1].bv_val = NULL;
851         vals[1].bv_len = 0;
852         mod.sml_op = LDAP_MOD_DELETE; 
853         mod.sml_desc = ad_queryid;
854         mod.sml_type = ad_queryid->ad_cname;
855         mod.sml_bvalues = vals;
856         mod.sml_next = NULL; 
857 #ifdef NEW_LOGGING
858         LDAP_LOG( BACK_META, DETAIL1,
859                         "REMOVING TEMP ATTR : TEMPLATE=%s\n",
860                         attr->a_vals[0].bv_val, 0, 0 );
861 #else
862         Debug( LDAP_DEBUG_ANY, "REMOVING TEMP ATTR : TEMPLATE=%s\n",
863                         attr->a_vals[0].bv_val, 0, 0 );
864 #endif
865
866         op_tmp.o_req_dn = rs->sr_entry->e_name;
867         op_tmp.o_req_ndn = rs->sr_entry->e_nname;
868         op_tmp.orm_modlist = &mod;
869         
870         op->o_bd->be_modify( &op_tmp, &sreply );
871
872         return 0;
873 }
874  
875 static int 
876 remove_query_data (
877         Operation       *op,
878         SlapReply       *rs,
879         struct berval* query_uuid)
880 {
881         struct query_info       info; 
882         char                    filter_str[64]; 
883         Filter                  filter = {LDAP_FILTER_EQUALITY};
884         SlapReply               sreply = {REP_RESULT}; 
885         slap_callback cb = { remove_func, NULL }; 
886
887         sreply.sr_entry = NULL; 
888         sreply.sr_nentries = 0; 
889         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
890                 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
891         filter.f_av_desc = ad_queryid;
892         filter.f_av_value = *query_uuid;
893         info.uuid = query_uuid; 
894         info.deleted = 0; 
895         cb.sc_private = &info; 
896  
897         op->o_tag = LDAP_REQ_SEARCH;
898         op->o_protocol = LDAP_VERSION3;
899         op->o_callback = &cb;
900         op->o_time = slap_get_time();
901         op->o_do_not_cache = 1;
902
903         op->o_req_dn = op->o_bd->be_suffix[0];
904         op->o_req_ndn = op->o_bd->be_nsuffix[0];
905         op->ors_scope = LDAP_SCOPE_SUBTREE;
906         op->ors_deref = LDAP_DEREF_NEVER;
907         op->ors_slimit = 0;
908         op->ors_tlimit = 0;
909         op->ors_filter = &filter;
910         op->ors_filterstr.bv_val = filter_str;
911         op->ors_filterstr.bv_len = strlen(filter_str);
912         op->ors_attrs = NULL;
913         op->ors_attrsonly = 0;
914
915         op->o_bd->be_search( op, &sreply );
916
917         return info.deleted;
918 }
919
920 static int 
921 get_attr_set(
922         AttributeName* attrs, 
923         query_manager* qm, 
924         int num
925 );
926
927 static int 
928 attrscmp(
929         AttributeName* attrs_in, 
930         AttributeName* attrs
931 );
932
933 static int 
934 is_temp_answerable(
935         int attr_set, 
936         struct berval* tempstr, 
937         query_manager* qm, 
938         int template_id )
939 {
940         QueryTemplate *qt = qm->templates + template_id;
941
942         if (attr_set != qt->attr_set_index) {
943                 int* id_array = qm->attr_sets[attr_set].ID_array;    
944
945                 while (*id_array != -1) {
946                         if (*id_array == qt->attr_set_index)
947                                 break;
948                         id_array++; 
949                 }
950                 if (*id_array == -1)
951                         return 0; 
952         }
953         return (qt->querystr.bv_len == tempstr->bv_len &&
954                 strcasecmp(qt->querystr.bv_val, tempstr->bv_val) == 0);
955 }
956
957 static void*
958 consistency_check(
959         void    *op
960 ); 
961
962 static int 
963 filter2template(
964         Filter                  *f,
965         struct                  berval *fstr,
966         AttributeName**         filter_attrs, 
967         int*                    filter_cnt )
968 {
969         AttributeDescription *ad;
970
971         switch ( f->f_choice ) {
972         case LDAP_FILTER_EQUALITY:
973                 ad = f->f_av_desc;
974                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
975                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
976                 break;
977
978         case LDAP_FILTER_GE:
979                 ad = f->f_av_desc;
980                 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
981                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
982                 break;
983
984         case LDAP_FILTER_LE:
985                 ad = f->f_av_desc;
986                 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
987                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
988                 break;
989
990         case LDAP_FILTER_APPROX:
991                 ad = f->f_av_desc;
992                 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
993                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
994                 break;
995
996         case LDAP_FILTER_SUBSTRINGS:
997                 ad = f->f_sub_desc;
998                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
999                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1000                 break;
1001
1002         case LDAP_FILTER_PRESENT:
1003                 ad = f->f_desc;
1004                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1005                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1006                 break;
1007
1008         case LDAP_FILTER_AND:
1009         case LDAP_FILTER_OR:
1010         case LDAP_FILTER_NOT: {
1011                 int rc = 0;
1012                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1013                         f->f_choice == LDAP_FILTER_AND ? '&' :
1014                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1015                 fstr->bv_len += sizeof("(%") - 1;
1016
1017                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1018                         rc = filter2template( f, fstr, filter_attrs, filter_cnt ); 
1019                         if ( rc ) break;
1020                 }
1021                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1022                 fstr->bv_len += sizeof(")") - 1;
1023
1024                 return rc;
1025                 }
1026
1027         default:
1028                 strcpy( fstr->bv_val, "(?=?)" );
1029                 fstr->bv_len += sizeof("(?=?)")-1;
1030                 return -1;
1031         }
1032
1033         *filter_attrs = (AttributeName *)ch_realloc(*filter_attrs,
1034                                 (*filter_cnt + 2)*sizeof(AttributeName)); 
1035                 
1036         (*filter_attrs)[*filter_cnt].an_desc = ad;
1037         (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname; 
1038         (*filter_attrs)[*filter_cnt+1].an_name.bv_val = NULL; 
1039         (*filter_attrs)[*filter_cnt+1].an_name.bv_len = 0; 
1040         (*filter_cnt)++; 
1041         return 0;
1042 }
1043
1044 struct search_info {
1045         slap_overinst *on;
1046         slap_callback *prev;
1047         Query query;
1048         int template_id;
1049         int max;
1050         int over;
1051         int count;
1052         Entry *head, *tail;
1053 };
1054
1055 static int
1056 cache_entries(
1057         Operation       *op,
1058         SlapReply       *rs,
1059         struct berval *query_uuid)
1060 {
1061         struct search_info *si = op->o_callback->sc_private;
1062         slap_overinst *on = si->on;
1063         cache_manager *cm = on->on_bi.bi_private;
1064         query_manager*          qm = cm->qm; 
1065         int             i; 
1066         int             return_val; 
1067         Entry           *e; 
1068         struct berval   crp_uuid; 
1069         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1070         Operation op_tmp = *op;
1071         BackendDB db = *op->o_bd;
1072     
1073         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf)); 
1074         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1075
1076         op_tmp.o_bd = &db;
1077         db.bd_info = cm->bi;
1078         db.be_private =cm->be_private;
1079         db.be_flags |= SLAP_BFLAG_NO_SCHEMA_CHECK;
1080
1081 #ifdef NEW_LOGGING
1082         LDAP_LOG( BACK_META, DETAIL1, "UUID for query being added = %s\n",
1083                         uuidbuf, 0, 0 );
1084 #else /* !NEW_LOGGING */
1085         Debug( LDAP_DEBUG_ANY, "UUID for query being added = %s\n",
1086                         uuidbuf, 0, 0 );
1087 #endif /* !NEW_LOGGING */
1088         
1089         for ( e=si->head; e; e=si->head ) {
1090                 si->head = e->e_private;
1091                 e->e_private = NULL;
1092 #ifdef NEW_LOGGING
1093                 LDAP_LOG( BACK_META, DETAIL2, "LOCKING REMOVE MUTEX\n",
1094                                 0, 0, 0 );
1095 #else /* !NEW_LOGGING */
1096                 Debug( LDAP_DEBUG_NONE, "LOCKING REMOVE MUTEX\n", 0, 0, 0 );
1097 #endif /* !NEW_LOGGING */
1098                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex); 
1099 #ifdef NEW_LOGGING
1100                 LDAP_LOG( BACK_META, DETAIL2, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1101 #else /* !NEW_LOGGING */
1102                 Debug( LDAP_DEBUG_NONE, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1103 #endif /* !NEW_LOGGING */
1104                 while ( cm->cur_entries > (cm->max_entries) ) {
1105                                 qm->crfunc(qm, &crp_uuid);
1106                                 if (crp_uuid.bv_val) {
1107 #ifdef NEW_LOGGING
1108                                         LDAP_LOG( BACK_META, DETAIL1,
1109                                                 "Removing query UUID %s\n",
1110                                                 crp_uuid.bv_val, 0, 0 );
1111 #else /* !NEW_LOGGING */
1112                                         Debug( LDAP_DEBUG_ANY,
1113                                                 "Removing query UUID %s\n",
1114                                                 crp_uuid.bv_val, 0, 0 );
1115 #endif /* !NEW_LOGGING */
1116                                         return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1117 #ifdef NEW_LOGGING
1118                                         LDAP_LOG( BACK_META, DETAIL1,
1119                                                 "QUERY REMOVED, SIZE=%d\n",
1120                                                 return_val, 0, 0);
1121 #else /* !NEW_LOGGING */
1122                                         Debug( LDAP_DEBUG_ANY,
1123                                                 "QUERY REMOVED, SIZE=%d\n",
1124                                                 return_val, 0, 0);
1125 #endif /* !NEW_LOGGING */
1126                                         ldap_pvt_thread_mutex_lock(
1127                                                         &cm->cache_mutex ); 
1128                                         cm->cur_entries -= return_val;
1129                                         cm->num_cached_queries--; 
1130 #ifdef NEW_LOGGING
1131                                         LDAP_LOG( BACK_META, DETAIL1,
1132                                                 "STORED QUERIES = %lu\n",
1133                                                 cm->num_cached_queries, 0, 0 );
1134 #else /* !NEW_LOGGING */
1135                                         Debug( LDAP_DEBUG_ANY,
1136                                                 "STORED QUERIES = %lu\n",
1137                                                 cm->num_cached_queries, 0, 0 );
1138 #endif /* !NEW_LOGGING */
1139                                         ldap_pvt_thread_mutex_unlock(
1140                                                         &cm->cache_mutex );
1141 #ifdef NEW_LOGGING
1142                                         LDAP_LOG( BACK_META, DETAIL1,
1143                                                 "QUERY REMOVED, CACHE ="
1144                                                 "%d entries\n",
1145                                                 cm->cur_entries, 0, 0 );
1146 #else /* !NEW_LOGGING */
1147                                         Debug( LDAP_DEBUG_ANY,
1148                                                 "QUERY REMOVED, CACHE ="
1149                                                 "%d entries\n",
1150                                                 cm->cur_entries, 0, 0 );
1151 #endif /* !NEW_LOGGING */
1152                                 }
1153                 }
1154
1155                 return_val = merge_entry(&op_tmp, e, query_uuid);
1156 #ifdef NEW_LOGGING
1157                 LDAP_LOG( BACK_META, DETAIL1,
1158                         "ENTRY ADDED/MERGED, CACHE =%d entries\n",
1159                         cm->cur_entries, 0, 0 );
1160 #else /* !NEW_LOGGING */
1161                 Debug( LDAP_DEBUG_ANY,
1162                         "ENTRY ADDED/MERGED, CACHE =%d entries\n",
1163                         cm->cur_entries, 0, 0 );
1164 #endif /* !NEW_LOGGING */
1165 #ifdef NEW_LOGGING
1166                 LDAP_LOG( BACK_META, DETAIL2, "UNLOCKING REMOVE MUTEX\n",
1167                                 0, 0, 0 );
1168 #else /* !NEW_LOGGING */
1169                 Debug( LDAP_DEBUG_NONE, "UNLOCKING REMOVE MUTEX\n", 0, 0, 0 );
1170 #endif /* !NEW_LOGGING */
1171                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex); 
1172 #ifdef NEW_LOGGING
1173                 LDAP_LOG( BACK_META, DETAIL2, "UNLOCKED REMOVE MUTEX\n",
1174                                 0, 0, 0 );
1175 #else /* !NEW_LOGGING */
1176                 Debug( LDAP_DEBUG_NONE, "UNLOCKED REMOVE MUTEX\n", 0, 0, 0 );
1177 #endif /* !NEW_LOGGING */
1178                 if (return_val)
1179                         return 0; 
1180                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
1181                 cm->cur_entries++;
1182 #ifdef NEW_LOGGING
1183                 LDAP_LOG( BACK_META, DETAIL1,
1184                         "ENTRY ADDED/MERGED, SIZE=%d, CACHED ENTRIES=%d\n",
1185                         return_val, cm->cur_entries, 0 );
1186 #else /* !NEW_LOGGING */
1187                 Debug( LDAP_DEBUG_ANY,
1188                         "ENTRY ADDED/MERGED, SIZE=%d, CACHED ENTRIES=%d\n",
1189                         return_val, cm->cur_entries, 0 );
1190 #endif /* !NEW_LOGGING */
1191                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
1192         }
1193         ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
1194         cm->num_cached_queries++; 
1195 #ifdef NEW_LOGGING
1196         LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1197                         cm->num_cached_queries, 0, 0 );
1198 #else /* !NEW_LOGGING */
1199         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1200                         cm->num_cached_queries, 0, 0 );
1201 #endif /* !NEW_LOGGING */
1202         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
1203
1204         return return_val;
1205 }
1206
1207 static int
1208 proxy_cache_response(
1209         Operation       *op,
1210         SlapReply       *rs )
1211 {
1212         struct search_info *si = op->o_callback->sc_private;
1213         slap_overinst *on = si->on;
1214         cache_manager *cm = on->on_bi.bi_private;
1215         query_manager*          qm = cm->qm; 
1216         struct berval uuid;
1217
1218         if ( rs->sr_type == REP_SEARCH ) {
1219                 Entry *e;
1220                 /* If we haven't exceeded the limit for this query,
1221                  * build a chain of answers to store. If we hit the
1222                  * limit, empty the chain and ignore the rest.
1223                  */
1224                 if ( !si->over ) {
1225                         if ( si->count < si->max ) {
1226                                 si->count++;
1227                                 e = entry_dup( rs->sr_entry );
1228                                 if ( !si->head ) si->head = e;
1229                                 if ( si->tail ) si->tail->e_private = e;
1230                                 si->tail = e;
1231                         } else {
1232                                 si->over = 1;
1233                                 si->count = 0;
1234                                 for (;si->head; si->head=e) {
1235                                         e = si->head->e_private;
1236                                         si->head->e_private = NULL;
1237                                         entry_free(si->head);
1238                                 }
1239                                 si->tail = NULL;
1240                         }
1241                 }
1242         } else if ( rs->sr_type == REP_RESULT && !si->over ) {
1243                 if ( cache_entries( op, rs, &uuid ) == 0)
1244                         qm->addfunc(qm, &si->query, si->template_id, &uuid);
1245         }
1246         return SLAP_CB_CONTINUE;
1247 }
1248
1249 static void
1250 add_filter_attrs(
1251         Operation *op,
1252         AttributeName** new_attrs, 
1253         AttributeName* attrs, 
1254         AttributeName* filter_attrs )
1255 {
1256         int alluser = 0; 
1257         int allop = 0; 
1258         int i; 
1259         int count; 
1260
1261         /* duplicate attrs */
1262         if (attrs == NULL) {
1263                 count = 1; 
1264         } else { 
1265                 for (count=0; attrs[count].an_name.bv_val; count++) 
1266                         ;
1267         }
1268         *new_attrs = (AttributeName*)(op->o_tmpalloc((count+1)*
1269                 sizeof(AttributeName), op->o_tmpmemctx)); 
1270         if (attrs == NULL) { 
1271                 (*new_attrs)[0].an_name.bv_val = "*"; 
1272                 (*new_attrs)[0].an_name.bv_len = 1; 
1273                 (*new_attrs)[1].an_name.bv_val = NULL;
1274                 (*new_attrs)[1].an_name.bv_len = 0; 
1275                 alluser = 1; 
1276                 allop = 0; 
1277         } else {  
1278                 for (i=0; i<count; i++) {
1279                         (*new_attrs)[i].an_name = attrs[i].an_name; 
1280                         (*new_attrs)[i].an_desc = attrs[i].an_desc;  
1281                 }
1282                 (*new_attrs)[count].an_name.bv_val = NULL; 
1283                 (*new_attrs)[count].an_name.bv_len = 0; 
1284                 alluser = an_find(*new_attrs, &AllUser); 
1285                 allop = an_find(*new_attrs, &AllOper); 
1286         }
1287
1288         for ( i=0; filter_attrs[i].an_name.bv_val; i++ ) {
1289                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1290                         continue; 
1291                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1292                         if (allop) 
1293                                 continue; 
1294                 } else if (alluser) 
1295                         continue; 
1296                 *new_attrs = (AttributeName*)(op->o_tmprealloc(*new_attrs,
1297                                         (count+2)*sizeof(AttributeName), op->o_tmpmemctx)); 
1298                 (*new_attrs)[count].an_name = filter_attrs[i].an_name;
1299                 (*new_attrs)[count].an_desc = filter_attrs[i].an_desc; 
1300                 count++; 
1301                 (*new_attrs)[count].an_name.bv_val = NULL; 
1302                 (*new_attrs)[count].an_name.bv_len = 0; 
1303         }
1304 }
1305
1306 static int
1307 proxy_cache_search(
1308         Operation       *op,
1309         SlapReply       *rs )
1310 {
1311         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1312         cache_manager *cm = on->on_bi.bi_private;
1313         query_manager*          qm = cm->qm; 
1314
1315         int count;
1316             
1317         int i = -1;
1318
1319         AttributeName   *filter_attrs = NULL; 
1320         AttributeName   *new_attrs = NULL; 
1321
1322         Query           query; 
1323
1324         int             attr_set = -1; 
1325         int             template_id = -1; 
1326         int             answerable = 0; 
1327         int             cacheable = 0; 
1328         int             fattr_cnt=0; 
1329         int             oc_attr_absent = 1;
1330
1331         struct berval tempstr;
1332
1333         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1334         tempstr.bv_len = 0;
1335         if (filter2template(op->ors_filter, &tempstr, &filter_attrs, &fattr_cnt)) {
1336                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1337                 return SLAP_CB_CONTINUE;
1338         }
1339
1340 #ifdef NEW_LOGGING
1341         LDAP_LOG( BACK_META, DETAIL1, "query template of incoming query = %s\n",
1342                                         tempstr.bv_val, 0, 0 );
1343 #else /* !NEW_LOGGING */
1344         Debug( LDAP_DEBUG_ANY, "query template of incoming query = %s\n",
1345                                         tempstr.bv_val, 0, 0 );
1346 #endif /* !NEW_LOGGING */
1347
1348         /* find attr set */     
1349         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets); 
1350     
1351         query.filter = op->ors_filter; 
1352         query.attrs = op->ors_attrs; 
1353         query.base = op->o_req_ndn; 
1354         query.scope = op->ors_scope; 
1355
1356         /* check for query containment */
1357         if (attr_set > -1) {
1358                 for (i=0; i<cm->numtemplates; i++) {
1359                         /* find if template i can potentially answer tempstr */
1360                         if (!is_temp_answerable(attr_set, &tempstr, qm, i)) 
1361                                 continue; 
1362                         if (attr_set == qm->templates[i].attr_set_index) {
1363                                 cacheable = 1; 
1364                                 template_id = i; 
1365                         }
1366 #ifdef NEW_LOGGING
1367                         LDAP_LOG( BACK_META, DETAIL2,
1368                                         "Entering QC, querystr = %s\n",
1369                                         op->ors_filterstr.bv_val, 0, 0 );
1370 #else /* !NEW_LOGGING */
1371                         Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1372                                         op->ors_filterstr.bv_val, 0, 0 );
1373 #endif /* !NEW_LOGGING */
1374                         answerable = (*(qm->qcfunc))(qm, &query, i);
1375
1376                         if (answerable)
1377                                 break;
1378                 }
1379         }
1380         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1381
1382         if (answerable) {
1383                 BackendDB db, *be;
1384 #ifdef NEW_LOGGING
1385                 LDAP_LOG( BACK_META, DETAIL1, "QUERY ANSWERABLE\n", 0, 0, 0 );
1386 #else /* !NEW_LOGGING */
1387                 Debug( LDAP_DEBUG_ANY, "QUERY ANSWERABLE\n", 0, 0, 0 );
1388 #endif /* !NEW_LOGGING */
1389                 free(filter_attrs); 
1390                 ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock); 
1391                 db = *op->o_bd;
1392                 db.bd_info = cm->bi;
1393                 db.be_private = cm->be_private;
1394                 be = op->o_bd;
1395                 op->o_bd = &db;
1396                 i = cm->bi->bi_op_search( op, rs );
1397                 op->o_bd = be;
1398                 return i;
1399         }
1400
1401 #ifdef NEW_LOGGING
1402         LDAP_LOG( BACK_META, DETAIL1, "QUERY NOT ANSWERABLE\n",
1403                                 0, 0, 0 );
1404 #else /* !NEW_LOGGING */
1405         Debug( LDAP_DEBUG_ANY, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1406 #endif /* !NEW_LOGGING */
1407
1408         ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
1409         if (cm->num_cached_queries >= cm->max_queries) {
1410                 cacheable = 0; 
1411         }
1412         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
1413         
1414         if (cacheable) {
1415                 slap_callback *cb;
1416                 struct search_info *si;
1417 #ifdef NEW_LOGGING
1418                 LDAP_LOG( BACK_META, DETAIL1,
1419                         "QUERY CACHEABLE\n", 0, 0, 0 );
1420 #else /* !NEW_LOGGING */
1421                 Debug( LDAP_DEBUG_ANY, "QUERY CACHEABLE\n", 0, 0, 0 );
1422 #endif /* !NEW_LOGGING */
1423                 query.filter = str2filter(op->ors_filterstr.bv_val); 
1424                 if (op->ors_attrs) {
1425                         for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ ) {
1426                                 if ( op->ors_attrs[count].an_desc == slap_schema.si_ad_objectClass )
1427                                         oc_attr_absent = 0;
1428                         }
1429                         query.attrs = (AttributeName*)ch_malloc( ( count + 1 + oc_attr_absent )
1430                                                                         *sizeof(AttributeName));
1431                         for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ ) {
1432                                 ber_dupbv( &query.attrs[count].an_name, &op->ors_attrs[count].an_name );
1433                                 query.attrs[count].an_desc = op->ors_attrs[count].an_desc;
1434                         }
1435                         if ( oc_attr_absent ) {
1436                                 query.attrs[ count ].an_desc = slap_schema.si_ad_objectClass;
1437                                 query.attrs[ count ].an_name = query.attrs[count].an_desc->ad_cname;
1438                                 count++;
1439                         }
1440                         query.attrs[ count ].an_name.bv_val = NULL;
1441                         query.attrs[ count ].an_name.bv_len = 0;
1442                 }
1443                 op->o_tmpfree(op->ors_attrs, op->o_tmpmemctx);
1444                 add_filter_attrs(op, &op->ors_attrs, query.attrs, filter_attrs);
1445                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1446                 cb->sc_response = proxy_cache_response;
1447                 cb->sc_private = (cb+1);
1448                 si = cb->sc_private;
1449                 si->on = on;
1450                 si->prev = op->o_callback;
1451                 si->query = query;
1452                 si->template_id = template_id;
1453                 si->max = cm->num_entries_limit ;
1454                 si->over = 0;
1455                 si->count = 0;
1456                 si->head = NULL;
1457                 si->tail = NULL;
1458                 op->o_callback = cb;
1459         } else {
1460 #ifdef NEW_LOGGING
1461                 LDAP_LOG( BACK_META, DETAIL1,
1462                                         "QUERY NOT CACHEABLE no\n",
1463                                         0, 0, 0);
1464 #else /* !NEW_LOGGING */
1465                 Debug( LDAP_DEBUG_ANY, "QUERY NOT CACHEABLE no\n",
1466                                         0, 0, 0);
1467 #endif /* !NEW_LOGGING */
1468         }
1469
1470         free(filter_attrs); 
1471         
1472         return SLAP_CB_CONTINUE;
1473 }
1474
1475 static int 
1476 attrscmp(
1477         AttributeName* attrs_in, 
1478         AttributeName* attrs)
1479 {
1480         int i, count1, count2; 
1481         if ( attrs_in == NULL ) {
1482                 return (attrs ? 0 : 1); 
1483         } 
1484         if ( attrs == NULL ) 
1485                 return 0; 
1486         
1487         for ( count1=0;
1488               attrs_in && attrs_in[count1].an_name.bv_val != NULL;
1489               count1++ )
1490                 ;
1491         for ( count2=0;
1492               attrs && attrs[count2].an_name.bv_val != NULL;
1493               count2++) 
1494                 ;
1495         if ( count1 != count2 )
1496                 return 0; 
1497
1498         for ( i=0; i<count1; i++ ) {
1499                 if ( !an_find(attrs, &attrs_in[i].an_name ))
1500                         return 0; 
1501         }
1502         return 1; 
1503 }
1504
1505 static int 
1506 get_attr_set(
1507         AttributeName* attrs, 
1508         query_manager* qm, 
1509         int num )
1510 {
1511         int i; 
1512         for (i=0; i<num; i++) {
1513                 if (attrscmp(attrs, qm->attr_sets[i].attrs)) 
1514                         return i;
1515         }
1516         return -1; 
1517 }
1518
1519 static void* 
1520 consistency_check(void* operation)
1521 {
1522         Operation op = *(Operation*)operation; 
1523         BackendDB be = *op.o_bd;
1524
1525         SlapReply rs = {REP_RESULT}; 
1526
1527         slap_overinst *on = (slap_overinst *)op.o_bd->bd_info;
1528         cache_manager*  cm = on->on_bi.bi_private;
1529         query_manager* qm = cm->qm; 
1530         CachedQuery* query, *query_prev; 
1531         time_t curr_time; 
1532         struct berval uuid;  
1533         int i, return_val; 
1534         QueryTemplate* templ;
1535
1536         op.o_bd = &be;
1537         be.bd_info = cm->bi;
1538         be.be_private = cm->be_private;
1539       
1540         for(;;) {
1541                 ldap_pvt_thread_sleep(cm->cc_period);     
1542                 for (i=0; qm->templates[i].querystr.bv_val; i++) {
1543                         templ = qm->templates + i; 
1544                         query = templ->query_last; 
1545                         curr_time = slap_get_time(); 
1546                         ldap_pvt_thread_mutex_lock(&cm->remove_mutex); 
1547                         while (query && (query->expiry_time < curr_time)) {
1548                                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex); 
1549                                 remove_query(qm, query); 
1550                                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex); 
1551 #ifdef NEW_LOGGING
1552                                 LDAP_LOG( BACK_META, DETAIL1, "Lock CR index = %d\n",
1553                                                 i, 0, 0 );
1554 #else /* !NEW_LOGGING */
1555                                 Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n",
1556                                                 i, 0, 0 );
1557 #endif /* !NEW_LOGGING */
1558                                 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);  
1559                                 remove_from_template(query, templ); 
1560 #ifdef NEW_LOGGING
1561                                 LDAP_LOG( BACK_META, DETAIL1,
1562                                                 "TEMPLATE %d QUERIES-- %d\n",
1563                                                 i, templ->no_of_queries, 0 );
1564 #else /* !NEW_LOGGING */
1565                                 Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
1566                                                 i, templ->no_of_queries, 0 );
1567 #endif /* !NEW_LOGGING */
1568 #ifdef NEW_LOGGING
1569                                 LDAP_LOG( BACK_META, DETAIL1, "Unlock CR index = %d\n",
1570                                                 i, 0, 0 );
1571 #else /* !NEW_LOGGING */
1572                                 Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n",
1573                                                 i, 0, 0 );
1574 #endif /* !NEW_LOGGING */
1575                                 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);  
1576                                 uuid = query->q_uuid; 
1577                                 return_val = remove_query_data(&op, &rs, &uuid);
1578 #ifdef NEW_LOGGING
1579                                 LDAP_LOG( BACK_META, DETAIL1,
1580                                                 "STALE QUERY REMOVED, SIZE=%d\n",
1581                                                 return_val, 0, 0 );
1582 #else /* !NEW_LOGGING */
1583                                 Debug( LDAP_DEBUG_ANY, "STALE QUERY REMOVED, SIZE=%d\n",
1584                                                         return_val, 0, 0 );
1585 #endif /* !NEW_LOGGING */
1586                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex); 
1587                                 cm->cur_entries -= return_val;
1588                                 cm->num_cached_queries--; 
1589 #ifdef NEW_LOGGING
1590                                 LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1591                                                 cm->num_cached_queries, 0, 0 );
1592 #else /* !NEW_LOGGING */
1593                                 Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1594                                                 cm->num_cached_queries, 0, 0 );
1595 #endif /* !NEW_LOGGING */
1596                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex); 
1597 #ifdef NEW_LOGGING
1598                                 LDAP_LOG( BACK_META, DETAIL1,
1599                                         "STALE QUERY REMOVED, CACHE ="
1600                                         "%d entries\n", 
1601                                         cm->cur_entries, 0, 0 );
1602 #else /* !NEW_LOGGING */
1603                                 Debug( LDAP_DEBUG_ANY,
1604                                         "STALE QUERY REMOVED, CACHE ="
1605                                         "%d entries\n", 
1606                                         cm->cur_entries, 0, 0 );
1607 #endif /* !NEW_LOGGING */
1608                                 query_prev = query; 
1609                                 query = query->prev; 
1610                                 free_query(query_prev); 
1611                         }
1612                         ldap_pvt_thread_mutex_unlock(&cm->remove_mutex); 
1613                 }
1614         }
1615 }
1616
1617
1618 #define MAX_ATTR_SETS 500 
1619 static void find_supersets( struct attr_set* attr_sets, int numsets ); 
1620 static int compare_sets( struct attr_set* setA, int, int );
1621
1622 static int
1623 proxy_cache_config(
1624         BackendDB       *be,
1625         const char      *fname,
1626         int             lineno,
1627         int             argc,
1628         char            **argv
1629 )
1630 {
1631         slap_overinst *on = (slap_overinst *)be->bd_info;
1632         cache_manager*  cm = on->on_bi.bi_private;
1633         query_manager*  qm = cm->qm;
1634         QueryTemplate*  temp;
1635         AttributeName*  attr_name; 
1636         AttributeName*  attrarray;
1637         const char*     text=NULL; 
1638         void *private = be->be_private;
1639
1640         int             index, i; 
1641         int             num; 
1642
1643         if ( strcasecmp( argv[0], "proxycache" ) == 0 ) {
1644                 if ( argc < 6 ) {
1645                         fprintf( stderr, "%s: line %d: missing arguments in \"proxycache"
1646                                 " <backend> <max_entries> <numattrsets> <entry limit> "
1647                                 "<cycle_time>\"\n", fname, lineno );
1648                         return( 1 );
1649                 }
1650
1651                 cm->bi = backend_info( argv[1] );
1652                 if ( !cm->bi ) {
1653                         fprintf( stderr, "%s: line %d: backend %s unknown\n",
1654                                 fname, lineno, argv[1] );
1655                         return( 1 );
1656                 }
1657                 be->be_private = NULL;
1658                 i = cm->bi->bi_db_init( be );
1659                 cm->be_private = be->be_private;
1660                 be->be_private = private;
1661                 if ( i ) return( 1 );
1662
1663                 cm->max_entries = atoi( argv[2] );
1664
1665                 cm->numattrsets = atoi( argv[3] );
1666                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1667                         fprintf( stderr, "%s: line %d: numattrsets must be <= %d\n",
1668                                 fname, lineno, MAX_ATTR_SETS );
1669                         return( 1 );
1670                 }
1671
1672                 cm->num_entries_limit = atoi( argv[4] ); 
1673                 cm->cc_period = atoi( argv[5] ); 
1674 #ifdef NEW_LOGGING
1675                 LDAP_LOG( BACK_META, DETAIL1,
1676                                 "Total # of attribute sets to be cached = %d\n",
1677                                 cm->numattrsets, 0, 0 ); 
1678 #else
1679                 Debug( LDAP_DEBUG_ANY,
1680                                 "Total # of attribute sets to be cached = %d\n",
1681                                 cm->numattrsets, 0, 0 ); 
1682 #endif
1683                 qm->attr_sets = ( struct attr_set * )ch_malloc( cm->numattrsets *
1684                                                 sizeof( struct attr_set ));
1685                 for ( i = 0; i < cm->numattrsets; i++ ) {
1686                         qm->attr_sets[i].attrs = NULL; 
1687                 }
1688
1689         } else if ( strcasecmp( argv[0], "proxyattrset" ) == 0 ) {
1690                 if ( argc < 3 ) {
1691                         fprintf( stderr, "%s: line %d: missing arguments in \"proxyattrset "
1692                                 "<index> <attributes>\"\n", fname, lineno );
1693                         return( 1 );
1694                 }
1695 #ifdef NEW_LOGGING
1696                 LDAP_LOG( BACK_META, DETAIL1, "Attribute Set # %d\n",
1697                                 atoi( argv[1] ), 0, 0 ); 
1698 #else
1699                 Debug( LDAP_DEBUG_ANY, "Attribute Set # %d\n",
1700                                 atoi( argv[1] ), 0, 0 ); 
1701 #endif
1702                 if (atoi(argv[1]) >= cm->numattrsets) {
1703                         fprintf( stderr, "%s; line %d index out of bounds \n",
1704                                         fname, lineno );
1705                         return 1; 
1706                 } 
1707                 index = atoi( argv[1] );
1708                 if ( argv[2] && strcmp( argv[2], "*" ) ) {
1709                         qm->attr_sets[index].count = argc - 2; 
1710                         qm->attr_sets[index].attrs = (AttributeName*)ch_malloc(
1711                                                 (argc-1) * sizeof( AttributeName ));
1712                         attr_name = qm->attr_sets[index].attrs;
1713                         for ( i = 2; i < argc; i++ ) {
1714 #ifdef NEW_LOGGING
1715                                 LDAP_LOG( BACK_META, DETAIL1, "\t %s\n",
1716                                                 argv[i], 0, 0 );
1717 #else
1718                                 Debug( LDAP_DEBUG_ANY, "\t %s\n",
1719                                                 argv[i], 0, 0 );
1720 #endif
1721                                 ber_str2bv( argv[i], 0, 1,
1722                                                 &attr_name->an_name); 
1723                                 attr_name->an_desc = NULL; 
1724                                 slap_bv2ad( &attr_name->an_name,
1725                                                 &attr_name->an_desc, &text );
1726                                 attr_name++; 
1727                                 attr_name->an_name.bv_val = NULL; 
1728                                 attr_name->an_name.bv_len = 0; 
1729                         }
1730                 }
1731         } else if ( strcasecmp( argv[0], "proxytemplate" ) == 0 ) {
1732                 if ( argc != 4 ) {
1733                         fprintf( stderr, "%s: line %d: missing argument(s) in "
1734                                 "\"proxytemplate <filter> <proj attr set> <TTL>\" line\n",
1735                                 fname, lineno );
1736                         return( 1 );
1737                 }
1738                 if (( i = atoi( argv[2] )) >= cm->numattrsets ) {
1739 #ifdef NEW_LOGGING
1740                         LDAP_LOG( BACK_META, DETAIL1,
1741                                         "%s: line %d, template index invalid\n",
1742                                         fname, lineno, 0 );  
1743 #else
1744                         Debug( LDAP_DEBUG_ANY,
1745                                         "%s: line %d, template index invalid\n",
1746                                         fname, lineno, 0 );  
1747 #endif
1748                         return 1; 
1749                 }
1750                 num = cm->numtemplates; 
1751                 if ( num == 0 )
1752                         find_supersets( qm->attr_sets, cm->numattrsets );
1753                 qm->templates = ( QueryTemplate* )ch_realloc( qm->templates,
1754                                 ( num + 2 ) * sizeof( QueryTemplate ));
1755                 temp = qm->templates + num; 
1756                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock ); 
1757                 temp->query = temp->query_last = NULL;
1758                 temp->ttl = atoi( argv[3] );
1759                 temp->no_of_queries = 0; 
1760                 if ( argv[1] == NULL ) {
1761 #ifdef NEW_LOGGING
1762                         LDAP_LOG( BACK_META, DETAIL1,
1763                                         "Templates string not specified "
1764                                         "for template %d\n", num, 0, 0 ); 
1765 #else
1766                         Debug( LDAP_DEBUG_ANY,
1767                                         "Templates string not specified "
1768                                         "for template %d\n", num, 0, 0 ); 
1769 #endif
1770                         return 1; 
1771                 }
1772                 ber_str2bv( argv[1], 0, 1, &temp->querystr );
1773 #ifdef NEW_LOGGING
1774                 LDAP_LOG( BACK_META, DETAIL1, "Template:\n", 0, 0, 0 );
1775 #else
1776                 Debug( LDAP_DEBUG_ANY, "Template:\n", 0, 0, 0 );
1777 #endif
1778 #ifdef NEW_LOGGING
1779                 LDAP_LOG( BACK_META, DETAIL1, "  query template: %s\n",
1780                                 temp->querystr.bv_val, 0, 0 );
1781 #else
1782                 Debug( LDAP_DEBUG_ANY, "  query template: %s\n",
1783                                 temp->querystr.bv_val, 0, 0 );
1784 #endif
1785                 temp->attr_set_index = i; 
1786 #ifdef NEW_LOGGING
1787                 LDAP_LOG( BACK_META, DETAIL1, "  attributes: \n", 0, 0, 0 );
1788 #else
1789                 Debug( LDAP_DEBUG_ANY, "  attributes: \n", 0, 0, 0 );
1790 #endif
1791                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
1792                         for ( i=0; attrarray[i].an_name.bv_val; i++ ) 
1793 #ifdef NEW_LOGGING
1794                                 LDAP_LOG( BACK_META, DETAIL1, "\t%s\n",
1795                                         attrarray[i].an_name.bv_val, 0, 0 );
1796 #else
1797                                 Debug( LDAP_DEBUG_ANY, "\t%s\n",
1798                                         attrarray[i].an_name.bv_val, 0, 0 );
1799 #endif
1800                 }
1801                 temp++;         
1802                 temp->querystr.bv_val = NULL; 
1803                 cm->numtemplates++;
1804         } 
1805         /* anything else */
1806         else {
1807                 be->be_private = cm->be_private;
1808                 i = cm->bi->bi_db_config( be, fname, lineno, argc, argv );
1809                 be->be_private = private;
1810                 return i;
1811         }
1812         return 0;
1813 }
1814
1815 static int
1816 proxy_cache_init(
1817         BackendDB *be
1818 )
1819 {
1820         slap_overinst *on = (slap_overinst *)be->bd_info;
1821         cache_manager *cm;
1822         query_manager *qm;
1823
1824         cm = (cache_manager *)ch_malloc(sizeof(cache_manager)); 
1825         on->on_bi.bi_private = cm;
1826
1827         qm = (query_manager*)ch_malloc(sizeof(query_manager)); 
1828
1829         cm->qm = qm; 
1830         cm->numattrsets = 0; 
1831         cm->numtemplates = 0;   
1832         cm->num_entries_limit = 5;
1833         cm->num_cached_queries = 0; 
1834         cm->max_entries = 0; 
1835         cm->cur_entries = 0; 
1836         cm->max_queries = 10000; 
1837         cm->cc_thread_started = 0; 
1838         cm->cc_period = 1000; 
1839        
1840         qm->attr_sets = NULL; 
1841         qm->templates = NULL; 
1842         qm->lru_top = NULL;
1843         qm->lru_bottom = NULL;
1844
1845         qm->qcfunc = query_containment; 
1846         qm->crfunc = cache_replacement; 
1847         qm->addfunc = add_query; 
1848         ldap_pvt_thread_mutex_init(&qm->lru_mutex); 
1849         
1850         ldap_pvt_thread_mutex_init(&cm->cache_mutex); 
1851         ldap_pvt_thread_mutex_init(&cm->remove_mutex); 
1852         return 0;
1853 }
1854
1855 static int
1856 proxy_cache_open(
1857         BackendDB *be
1858 )
1859 {
1860         slap_overinst *on = (slap_overinst *)be->bd_info;
1861         cache_manager *cm = on->on_bi.bi_private;
1862         void *private = be->be_private;
1863         int rc = 0;
1864
1865         if ( cm->be_private && cm->bi->bi_db_open ) {
1866                 be->be_private = cm->be_private;
1867                 rc = cm->bi->bi_db_open( be );
1868                 be->be_private = private;
1869         }
1870         return rc;
1871 }
1872
1873 static int
1874 proxy_cache_close(
1875         BackendDB *be
1876 )
1877 {
1878         slap_overinst *on = (slap_overinst *)be->bd_info;
1879         cache_manager *cm = on->on_bi.bi_private;
1880         void *private = be->be_private;
1881         int rc = 0;
1882
1883         if ( cm->be_private && cm->bi->bi_db_close ) {
1884                 be->be_private = cm->be_private;
1885                 rc = cm->bi->bi_db_close( be );
1886                 be->be_private = private;
1887         }
1888         return rc;
1889 }
1890
1891 static int
1892 proxy_cache_destroy(
1893         BackendDB *be
1894 )
1895 {
1896         slap_overinst *on = (slap_overinst *)be->bd_info;
1897         cache_manager *cm = on->on_bi.bi_private;
1898         void *private = be->be_private;
1899         int rc = 0;
1900
1901         if ( cm->be_private && cm->bi->bi_db_destroy ) {
1902                 be->be_private = cm->be_private;
1903                 rc = cm->bi->bi_db_destroy( be );
1904                 be->be_private = private;
1905         }
1906         free( cm );
1907         return rc;
1908 }
1909
1910 static void
1911 find_supersets ( struct attr_set* attr_sets, int numsets )
1912 {
1913         int num[MAX_ATTR_SETS];
1914         int i, j, res;
1915         int* id_array;
1916         for ( i = 0; i < MAX_ATTR_SETS; i++ )
1917                 num[i] = 0;
1918
1919         for ( i = 0; i < numsets; i++ ) {
1920                 attr_sets[i].ID_array = (int*) ch_malloc( sizeof( int ) );
1921                 attr_sets[i].ID_array[0] = -1; 
1922         } 
1923
1924         for ( i = 0; i < numsets; i++ ) {
1925                 for ( j=i+1; j < numsets; j++ ) {
1926                         res = compare_sets( attr_sets, i, j ); 
1927                         switch ( res ) {
1928                         case 0:
1929                                 break;
1930                         case 3: 
1931                         case 1: 
1932                                 id_array = attr_sets[i].ID_array; 
1933                                 attr_sets[i].ID_array = (int *) ch_realloc( id_array,
1934                                                         ( num[i] + 2 ) * sizeof( int )); 
1935                                 attr_sets[i].ID_array[num[i]] = j; 
1936                                 attr_sets[i].ID_array[num[i]+1] = -1; 
1937                                 num[i]++;
1938                                 if (res == 1) 
1939                                         break;
1940                         case 2: 
1941                                 id_array = attr_sets[j].ID_array; 
1942                                 attr_sets[j].ID_array = (int *) ch_realloc( id_array,
1943                                                 ( num[j] + 2 ) * sizeof( int )); 
1944                                 attr_sets[j].ID_array[num[j]] = i; 
1945                                 attr_sets[j].ID_array[num[j]+1] = -1; 
1946                                 num[j]++;
1947                                 break;
1948                         }
1949                 }
1950         }
1951 }
1952
1953 /* 
1954  * compares two sets of attributes (indices i and j) 
1955  * returns 0: if neither set is contained in the other set 
1956  *         1: if set i is contained in set j
1957  *         2: if set j is contained in set i
1958  *         3: the sets are equivalent 
1959  */
1960
1961 static int 
1962 compare_sets(struct attr_set* set, int i, int j)
1963 {
1964         int k,l,numI,numJ;
1965         int common=0;
1966         int result=0;
1967
1968         if (( set[i].attrs == NULL ) && ( set[j].attrs == NULL ))
1969                 return 3;       
1970
1971         if ( set[i].attrs == NULL )
1972                 return 2; 
1973
1974         if ( set[j].attrs == NULL )
1975                 return 1; 
1976    
1977         numI = set[i].count; 
1978         numJ = set[j].count; 
1979
1980         for ( l=0; l < numI; l++ ) {
1981                 for ( k = 0; k < numJ; k++ ) {
1982                         if ( strcmp( set[i].attrs[l].an_name.bv_val,
1983                                      set[j].attrs[k].an_name.bv_val ) == 0 )
1984                                 common++;       
1985                 }
1986         }
1987
1988         if ( common == numI )
1989                 result = 1; 
1990
1991         if ( common == numJ )
1992                 result += 2;
1993
1994         return result; 
1995 }
1996
1997 static slap_overinst proxy_cache;
1998
1999 int pcache_init()
2000 {
2001         LDAPAttributeType *at;
2002         int code;
2003         const char *err;
2004
2005         at = ldap_str2attributetype( queryid_schema, &code, &err,
2006                 LDAP_SCHEMA_ALLOW_ALL );
2007         if ( !at ) {
2008                 fprintf( stderr, "AttributeType Load failed %s %s\n",
2009                         ldap_scherr2str(code), err );
2010                 return code;
2011         }
2012         code = at_add( at, &err );
2013         if ( !code ) {
2014                 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2015         }
2016         ldap_memfree( at );
2017         if ( code ) {
2018                 fprintf( stderr, "AttributeType Load failed %s %s\n",
2019                         scherr2str(code), err );
2020                 return code;
2021         }
2022
2023         proxy_cache.on_bi.bi_type = "proxycache";
2024         proxy_cache.on_bi.bi_db_init = proxy_cache_init;
2025         proxy_cache.on_bi.bi_db_config = proxy_cache_config;
2026         proxy_cache.on_bi.bi_db_open = proxy_cache_open;
2027         proxy_cache.on_bi.bi_db_close = proxy_cache_close;
2028         proxy_cache.on_bi.bi_db_destroy = proxy_cache_destroy;
2029         proxy_cache.on_bi.bi_op_search = proxy_cache_search;
2030
2031         return overlay_register( &proxy_cache );
2032 }
2033
2034 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2035 int init_module(int argc, char *argv[]) {
2036         return pcache_init();
2037 }
2038 #endif
2039
2040 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */