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