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