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