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