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