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