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