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