]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
60395e62c6c964e7cee0212beb11d5cb748a34f1
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003-2004 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         for (i=0; q->attrs[i].an_name.bv_val; i++) {
655                 free(q->attrs[i].an_name.bv_val);
656         }
657         free(q->attrs);
658         free(qc);
659 }
660
661
662 /* Add query to query cache */
663 static void add_query(
664         query_manager* qm,
665         Query* query,
666         int template_index,
667         struct berval* uuid)
668 {
669         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
670         QueryTemplate* templ = (qm->templates)+template_index;
671         Query* new_query;
672         new_cached_query->template_id = template_index;
673         new_cached_query->q_uuid = *uuid;
674         new_cached_query->lru_up = NULL;
675         new_cached_query->lru_down = NULL;
676         new_cached_query->expiry_time = slap_get_time() + templ->ttl;
677 #ifdef NEW_LOGGING
678         LDAP_LOG( BACK_META, DETAIL1, "Added query expires at %ld\n",
679                         (long) new_cached_query->expiry_time, 0, 0 );
680 #else
681         Debug( LDAP_DEBUG_ANY, "Added query expires at %ld\n",
682                         (long) new_cached_query->expiry_time, 0, 0 );
683 #endif
684         new_query = (Query*)new_cached_query;
685
686         ber_dupbv(&new_query->base, &query->base);
687         new_query->scope = query->scope;
688         new_query->filter = query->filter;
689         new_query->attrs = query->attrs;
690
691         /* Adding a query    */
692 #ifdef NEW_LOGGING
693         LDAP_LOG( BACK_META, DETAIL1, "Lock AQ index = %d\n",
694                         template_index, 0, 0 );
695 #else
696         Debug( LDAP_DEBUG_ANY, "Lock AQ index = %d\n",
697                         template_index, 0, 0 );
698 #endif
699         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
700         if (templ->query == NULL)
701                 templ->query_last = new_cached_query;
702         else
703                 templ->query->prev = new_cached_query;
704         new_cached_query->next = templ->query;
705         new_cached_query->prev = NULL;
706         templ->query = new_cached_query;
707         templ->no_of_queries++;
708 #ifdef NEW_LOGGING
709         LDAP_LOG( BACK_META, DETAIL1, "TEMPLATE %d QUERIES++ %d\n",
710                         template_index, templ->no_of_queries, 0 );
711 #else
712         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES++ %d\n",
713                         template_index, templ->no_of_queries, 0 );
714 #endif
715
716 #ifdef NEW_LOGGING
717         LDAP_LOG( BACK_META, DETAIL1, "Unlock AQ index = %d \n",
718                         template_index, 0, 0 );
719 #else
720         Debug( LDAP_DEBUG_ANY, "Unlock AQ index = %d \n",
721                         template_index, 0, 0 );
722 #endif
723         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
724
725         /* Adding on top of LRU list  */
726         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
727         add_query_on_top(qm, new_cached_query);
728         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
729 }
730
731 static void
732 remove_from_template (CachedQuery* qc, QueryTemplate* template)
733 {
734         if (!qc->prev && !qc->next) {
735                 template->query_last = template->query = NULL;
736         } else if (qc->prev == NULL) {
737                 qc->next->prev = NULL;
738                 template->query = qc->next;
739         } else if (qc->next == NULL) {
740                 qc->prev->next = NULL;
741                 template->query_last = qc->prev;
742         } else {
743                 qc->next->prev = qc->prev;
744                 qc->prev->next = qc->next;
745         }
746
747         template->no_of_queries--;
748 }
749
750 /* remove bottom query of LRU list from the query cache */
751 static void cache_replacement(query_manager* qm, struct berval *result)
752 {
753         CachedQuery* bottom;
754         int temp_id;
755
756         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
757         bottom = qm->lru_bottom;
758
759         result->bv_val = NULL;
760         result->bv_len = 0;
761
762         if (!bottom) {
763 #ifdef NEW_LOGGING
764                 LDAP_LOG ( BACK_META, DETAIL1,
765                         "Cache replacement invoked without "
766                         "any query in LRU list\n", 0, 0, 0 );
767 #else
768                 Debug ( LDAP_DEBUG_ANY,
769                         "Cache replacement invoked without "
770                         "any query in LRU list\n", 0, 0, 0 );
771 #endif
772                 return;
773         }
774
775         temp_id = bottom->template_id;
776         remove_query(qm, bottom);
777         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
778
779         *result = bottom->q_uuid;
780         bottom->q_uuid.bv_val = NULL;
781
782 #ifdef NEW_LOGGING
783         LDAP_LOG( BACK_META, DETAIL1, "Lock CR index = %d\n", temp_id, 0, 0 );
784 #else
785         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n", temp_id, 0, 0 );
786 #endif
787         ldap_pvt_thread_rdwr_wlock(&(qm->templates[temp_id].t_rwlock));
788         remove_from_template(bottom, (qm->templates+temp_id));
789 #ifdef NEW_LOGGING
790         LDAP_LOG( BACK_META, DETAIL1, "TEMPLATE %d QUERIES-- %d\n",
791                 temp_id, qm->templates[temp_id].no_of_queries, 0 );
792 #else
793         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
794                 temp_id, qm->templates[temp_id].no_of_queries, 0 );
795 #endif
796 #ifdef NEW_LOGGING
797         LDAP_LOG( BACK_META, DETAIL1, "Unlock CR index = %d\n", temp_id, 0, 0 );
798 #else
799         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n", temp_id, 0, 0 );
800 #endif
801         ldap_pvt_thread_rdwr_wunlock(&(qm->templates[temp_id].t_rwlock));
802         free_query(bottom);
803 }
804
805 struct query_info {
806         struct query_info *next;
807         struct berval xdn;
808         int del;
809 };
810
811 static int
812 remove_func (
813         Operation       *op,
814         SlapReply       *rs
815 )
816 {
817         Attribute *attr;
818         struct query_info *qi;
819         int count = 0;
820
821         if ( rs->sr_type != REP_SEARCH ) return 0;
822
823         for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
824                 if (attr->a_desc == ad_queryid) {
825                         for (count=0; attr->a_vals[count].bv_val; count++)
826                                 ;
827                         break;
828                 }
829         }
830         if ( count == 0 ) return 0;
831         qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
832         qi->next = op->o_callback->sc_private;
833         op->o_callback->sc_private = qi;
834         ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
835         qi->del = ( count == 1 );
836
837         return 0;
838 }
839
840 static int
841 remove_query_data (
842         Operation       *op,
843         SlapReply       *rs,
844         struct berval* query_uuid)
845 {
846         struct query_info       *qi, *qnext;
847         char                    filter_str[64];
848         AttributeAssertion      ava;
849         Filter                  filter = {LDAP_FILTER_EQUALITY};
850         SlapReply               sreply = {REP_RESULT};
851         slap_callback cb = { NULL, remove_func, NULL, NULL };
852         int deleted = 0;
853
854         sreply.sr_entry = NULL;
855         sreply.sr_nentries = 0;
856         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
857                 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
858         filter.f_ava = &ava;
859         filter.f_av_desc = ad_queryid;
860         filter.f_av_value = *query_uuid;
861
862         op->o_tag = LDAP_REQ_SEARCH;
863         op->o_protocol = LDAP_VERSION3;
864         op->o_callback = &cb;
865         op->o_time = slap_get_time();
866         op->o_do_not_cache = 1;
867
868         op->o_req_dn = op->o_bd->be_suffix[0];
869         op->o_req_ndn = op->o_bd->be_nsuffix[0];
870         op->ors_scope = LDAP_SCOPE_SUBTREE;
871         op->ors_deref = LDAP_DEREF_NEVER;
872         op->ors_slimit = -1;
873         op->ors_tlimit = -1;
874         op->ors_filter = &filter;
875         op->ors_filterstr.bv_val = filter_str;
876         op->ors_filterstr.bv_len = strlen(filter_str);
877         op->ors_attrs = NULL;
878         op->ors_attrsonly = 0;
879
880         op->o_bd->be_search( op, &sreply );
881
882         for ( qi=cb.sc_private; qi; qi=qnext ) {
883                 qnext = qi->next;
884
885                 op->o_req_dn = qi->xdn;
886                 op->o_req_ndn = qi->xdn;
887
888                 if ( qi->del) {
889 #ifdef NEW_LOGGING
890                         LDAP_LOG( BACK_META, DETAIL1,
891                                 "DELETING ENTRY TEMPLATE=%s\n",
892                                 query_uuid->bv_val, 0, 0 );
893 #else
894                         Debug( LDAP_DEBUG_ANY, "DELETING ENTRY TEMPLATE=%s\n",
895                                 query_uuid->bv_val, 0, 0 );
896 #endif
897
898                         op->o_tag = LDAP_REQ_DELETE;
899
900                         if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
901                                 deleted++;
902                         }
903                 } else {
904                         Modifications mod;
905                         struct berval vals[2];
906
907                         vals[0] = *query_uuid;
908                         vals[1].bv_val = NULL;
909                         vals[1].bv_len = 0;
910                         mod.sml_op = LDAP_MOD_DELETE;
911                         mod.sml_desc = ad_queryid;
912                         mod.sml_type = ad_queryid->ad_cname;
913                         mod.sml_values = vals;
914                         mod.sml_next = NULL;
915 #ifdef NEW_LOGGING
916                         LDAP_LOG( BACK_META, DETAIL1,
917                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
918                                 query_uuid->bv_val, 0, 0 );
919 #else
920                         Debug( LDAP_DEBUG_ANY,
921                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
922                                 query_uuid->bv_val, 0, 0 );
923 #endif
924
925                         op->orm_modlist = &mod;
926
927                         op->o_bd->be_modify( op, &sreply );
928                 }
929                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
930                 op->o_tmpfree( qi, op->o_tmpmemctx );
931         }
932         return deleted;
933 }
934
935 static int
936 get_attr_set(
937         AttributeName* attrs,
938         query_manager* qm,
939         int num
940 );
941
942 static int
943 attrscmp(
944         AttributeName* attrs_in,
945         AttributeName* attrs
946 );
947
948 static int
949 is_temp_answerable(
950         int attr_set,
951         struct berval* tempstr,
952         query_manager* qm,
953         int template_id )
954 {
955         QueryTemplate *qt = qm->templates + template_id;
956
957         if (attr_set != qt->attr_set_index) {
958                 int* id_array = qm->attr_sets[attr_set].ID_array;
959
960                 while (*id_array != -1) {
961                         if (*id_array == qt->attr_set_index)
962                                 break;
963                         id_array++;
964                 }
965                 if (*id_array == -1)
966                         return 0;
967         }
968         return (qt->querystr.bv_len == tempstr->bv_len &&
969                 strcasecmp(qt->querystr.bv_val, tempstr->bv_val) == 0);
970 }
971
972 static int
973 filter2template(
974         Filter                  *f,
975         struct                  berval *fstr,
976         AttributeName**         filter_attrs,
977         int*                    filter_cnt )
978 {
979         AttributeDescription *ad;
980
981         switch ( f->f_choice ) {
982         case LDAP_FILTER_EQUALITY:
983                 ad = f->f_av_desc;
984                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
985                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
986                 break;
987
988         case LDAP_FILTER_GE:
989                 ad = f->f_av_desc;
990                 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
991                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
992                 break;
993
994         case LDAP_FILTER_LE:
995                 ad = f->f_av_desc;
996                 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
997                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
998                 break;
999
1000         case LDAP_FILTER_APPROX:
1001                 ad = f->f_av_desc;
1002                 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1003                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1004                 break;
1005
1006         case LDAP_FILTER_SUBSTRINGS:
1007                 ad = f->f_sub_desc;
1008                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1009                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1010                 break;
1011
1012         case LDAP_FILTER_PRESENT:
1013                 ad = f->f_desc;
1014                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1015                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1016                 break;
1017
1018         case LDAP_FILTER_AND:
1019         case LDAP_FILTER_OR:
1020         case LDAP_FILTER_NOT: {
1021                 int rc = 0;
1022                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1023                         f->f_choice == LDAP_FILTER_AND ? '&' :
1024                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1025                 fstr->bv_len += sizeof("(%") - 1;
1026
1027                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1028                         rc = filter2template( f, fstr, filter_attrs, filter_cnt );
1029                         if ( rc ) break;
1030                 }
1031                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1032                 fstr->bv_len += sizeof(")") - 1;
1033
1034                 return rc;
1035                 }
1036
1037         default:
1038                 strcpy( fstr->bv_val, "(?=?)" );
1039                 fstr->bv_len += sizeof("(?=?)")-1;
1040                 return -1;
1041         }
1042
1043         *filter_attrs = (AttributeName *)ch_realloc(*filter_attrs,
1044                                 (*filter_cnt + 2)*sizeof(AttributeName));
1045
1046         (*filter_attrs)[*filter_cnt].an_desc = ad;
1047         (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1048         (*filter_attrs)[*filter_cnt+1].an_name.bv_val = NULL;
1049         (*filter_attrs)[*filter_cnt+1].an_name.bv_len = 0;
1050         (*filter_cnt)++;
1051         return 0;
1052 }
1053
1054 struct search_info {
1055         slap_overinst *on;
1056         Query query;
1057         int template_id;
1058         int max;
1059         int over;
1060         int count;
1061         Entry *head, *tail;
1062 };
1063
1064 static int
1065 cache_entries(
1066         Operation       *op,
1067         SlapReply       *rs,
1068         struct berval *query_uuid)
1069 {
1070         struct search_info *si = op->o_callback->sc_private;
1071         slap_overinst *on = si->on;
1072         cache_manager *cm = on->on_bi.bi_private;
1073         query_manager*          qm = cm->qm;
1074         int             i;
1075         int             return_val = 0;
1076         Entry           *e;
1077         struct berval   crp_uuid;
1078         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1079         Operation op_tmp = *op;
1080
1081         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1082         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1083
1084         op_tmp.o_bd = &cm->db;
1085         op_tmp.o_dn = cm->db.be_rootdn;
1086         op_tmp.o_ndn = cm->db.be_rootndn;
1087
1088 #ifdef NEW_LOGGING
1089         LDAP_LOG( BACK_META, DETAIL1, "UUID for query being added = %s\n",
1090                         uuidbuf, 0, 0 );
1091 #else /* !NEW_LOGGING */
1092         Debug( LDAP_DEBUG_ANY, "UUID for query being added = %s\n",
1093                         uuidbuf, 0, 0 );
1094 #endif /* !NEW_LOGGING */
1095
1096         for ( e=si->head; e; e=si->head ) {
1097                 si->head = e->e_private;
1098                 e->e_private = NULL;
1099 #ifdef NEW_LOGGING
1100                 LDAP_LOG( BACK_META, DETAIL2, "LOCKING REMOVE MUTEX\n",
1101                                 0, 0, 0 );
1102 #else /* !NEW_LOGGING */
1103                 Debug( LDAP_DEBUG_NONE, "LOCKING REMOVE MUTEX\n", 0, 0, 0 );
1104 #endif /* !NEW_LOGGING */
1105                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1106 #ifdef NEW_LOGGING
1107                 LDAP_LOG( BACK_META, DETAIL2, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1108 #else /* !NEW_LOGGING */
1109                 Debug( LDAP_DEBUG_NONE, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1110 #endif /* !NEW_LOGGING */
1111                 while ( cm->cur_entries > (cm->max_entries) ) {
1112                                 qm->crfunc(qm, &crp_uuid);
1113                                 if (crp_uuid.bv_val) {
1114 #ifdef NEW_LOGGING
1115                                         LDAP_LOG( BACK_META, DETAIL1,
1116                                                 "Removing query UUID %s\n",
1117                                                 crp_uuid.bv_val, 0, 0 );
1118 #else /* !NEW_LOGGING */
1119                                         Debug( LDAP_DEBUG_ANY,
1120                                                 "Removing query UUID %s\n",
1121                                                 crp_uuid.bv_val, 0, 0 );
1122 #endif /* !NEW_LOGGING */
1123                                         return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1124 #ifdef NEW_LOGGING
1125                                         LDAP_LOG( BACK_META, DETAIL1,
1126                                                 "QUERY REMOVED, SIZE=%d\n",
1127                                                 return_val, 0, 0);
1128 #else /* !NEW_LOGGING */
1129                                         Debug( LDAP_DEBUG_ANY,
1130                                                 "QUERY REMOVED, SIZE=%d\n",
1131                                                 return_val, 0, 0);
1132 #endif /* !NEW_LOGGING */
1133                                         ldap_pvt_thread_mutex_lock(
1134                                                         &cm->cache_mutex );
1135                                         cm->cur_entries -= return_val;
1136                                         cm->num_cached_queries--;
1137 #ifdef NEW_LOGGING
1138                                         LDAP_LOG( BACK_META, DETAIL1,
1139                                                 "STORED QUERIES = %lu\n",
1140                                                 cm->num_cached_queries, 0, 0 );
1141 #else /* !NEW_LOGGING */
1142                                         Debug( LDAP_DEBUG_ANY,
1143                                                 "STORED QUERIES = %lu\n",
1144                                                 cm->num_cached_queries, 0, 0 );
1145 #endif /* !NEW_LOGGING */
1146                                         ldap_pvt_thread_mutex_unlock(
1147                                                         &cm->cache_mutex );
1148 #ifdef NEW_LOGGING
1149                                         LDAP_LOG( BACK_META, DETAIL1,
1150                                                 "QUERY REMOVED, CACHE ="
1151                                                 "%d entries\n",
1152                                                 cm->cur_entries, 0, 0 );
1153 #else /* !NEW_LOGGING */
1154                                         Debug( LDAP_DEBUG_ANY,
1155                                                 "QUERY REMOVED, CACHE ="
1156                                                 "%d entries\n",
1157                                                 cm->cur_entries, 0, 0 );
1158 #endif /* !NEW_LOGGING */
1159                                 }
1160                 }
1161
1162                 return_val = merge_entry(&op_tmp, e, query_uuid);
1163                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1164                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1165                 cm->cur_entries += return_val;
1166 #ifdef NEW_LOGGING
1167                 LDAP_LOG( BACK_META, DETAIL1,
1168                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1169                         cm->cur_entries, 0, 0 );
1170 #else /* !NEW_LOGGING */
1171                 Debug( LDAP_DEBUG_ANY,
1172                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1173                         cm->cur_entries, 0, 0 );
1174 #endif /* !NEW_LOGGING */
1175                 return_val = 0;
1176                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1177         }
1178         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1179         cm->num_cached_queries++;
1180 #ifdef NEW_LOGGING
1181         LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1182                         cm->num_cached_queries, 0, 0 );
1183 #else /* !NEW_LOGGING */
1184         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1185                         cm->num_cached_queries, 0, 0 );
1186 #endif /* !NEW_LOGGING */
1187         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1188
1189         return return_val;
1190 }
1191
1192 static int
1193 proxy_cache_response(
1194         Operation       *op,
1195         SlapReply       *rs )
1196 {
1197         struct search_info *si = op->o_callback->sc_private;
1198         slap_overinst *on = si->on;
1199         cache_manager *cm = on->on_bi.bi_private;
1200         query_manager*          qm = cm->qm;
1201         struct berval uuid;
1202
1203         if ( rs->sr_type == REP_SEARCH ) {
1204                 Entry *e;
1205                 /* If we haven't exceeded the limit for this query,
1206                  * build a chain of answers to store. If we hit the
1207                  * limit, empty the chain and ignore the rest.
1208                  */
1209                 if ( !si->over ) {
1210                         if ( si->count < si->max ) {
1211                                 si->count++;
1212                                 e = entry_dup( rs->sr_entry );
1213                                 if ( !si->head ) si->head = e;
1214                                 if ( si->tail ) si->tail->e_private = e;
1215                                 si->tail = e;
1216                         } else {
1217                                 si->over = 1;
1218                                 si->count = 0;
1219                                 for (;si->head; si->head=e) {
1220                                         e = si->head->e_private;
1221                                         si->head->e_private = NULL;
1222                                         entry_free(si->head);
1223                                 }
1224                                 si->tail = NULL;
1225                         }
1226                 }
1227         } else if ( rs->sr_type == REP_RESULT && si->count ) {
1228                 if ( cache_entries( op, rs, &uuid ) == 0) {
1229                         qm->addfunc(qm, &si->query, si->template_id, &uuid);
1230                         /* If the consistency checker suspended itself,
1231                          * wake it back up
1232                          */
1233                         if ( cm->cc_paused ) {
1234                                 ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
1235                                 if ( cm->cc_paused ) {
1236                                         cm->cc_paused = 0;
1237                                         ldap_pvt_runqueue_resched( &syncrepl_rq, cm->cc_arg, 0 );
1238                                 }
1239                                 ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
1240                         }
1241                 }
1242         }
1243         return SLAP_CB_CONTINUE;
1244 }
1245
1246 static void
1247 add_filter_attrs(
1248         Operation *op,
1249         AttributeName** new_attrs,
1250         AttributeName* attrs,
1251         AttributeName* filter_attrs )
1252 {
1253         int alluser = 0;
1254         int allop = 0;
1255         int i;
1256         int count;
1257
1258         /* duplicate attrs */
1259         if (attrs == NULL) {
1260                 count = 1;
1261         } else {
1262                 for (count=0; attrs[count].an_name.bv_val; count++)
1263                         ;
1264         }
1265         *new_attrs = (AttributeName*)(op->o_tmpalloc((count+1)*
1266                 sizeof(AttributeName), op->o_tmpmemctx));
1267         if (attrs == NULL) {
1268                 (*new_attrs)[0].an_name.bv_val = "*";
1269                 (*new_attrs)[0].an_name.bv_len = 1;
1270                 (*new_attrs)[1].an_name.bv_val = NULL;
1271                 (*new_attrs)[1].an_name.bv_len = 0;
1272                 alluser = 1;
1273                 allop = 0;
1274         } else {
1275                 for (i=0; i<count; i++) {
1276                         (*new_attrs)[i].an_name = attrs[i].an_name;
1277                         (*new_attrs)[i].an_desc = attrs[i].an_desc;
1278                 }
1279                 (*new_attrs)[count].an_name.bv_val = NULL;
1280                 (*new_attrs)[count].an_name.bv_len = 0;
1281                 alluser = an_find(*new_attrs, &AllUser);
1282                 allop = an_find(*new_attrs, &AllOper);
1283         }
1284
1285         for ( i=0; filter_attrs[i].an_name.bv_val; i++ ) {
1286                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1287                         continue;
1288                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1289                         if (allop)
1290                                 continue;
1291                 } else if (alluser)
1292                         continue;
1293                 *new_attrs = (AttributeName*)(op->o_tmprealloc(*new_attrs,
1294                                         (count+2)*sizeof(AttributeName), op->o_tmpmemctx));
1295                 (*new_attrs)[count].an_name = filter_attrs[i].an_name;
1296                 (*new_attrs)[count].an_desc = filter_attrs[i].an_desc;
1297                 count++;
1298                 (*new_attrs)[count].an_name.bv_val = NULL;
1299                 (*new_attrs)[count].an_name.bv_len = 0;
1300         }
1301 }
1302
1303 static int
1304 proxy_cache_search(
1305         Operation       *op,
1306         SlapReply       *rs )
1307 {
1308         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1309         cache_manager *cm = on->on_bi.bi_private;
1310         query_manager*          qm = cm->qm;
1311
1312         int count;
1313
1314         int i = -1;
1315
1316         AttributeName   *filter_attrs = NULL;
1317         AttributeName   *new_attrs = NULL;
1318
1319         Query           query;
1320
1321         int             attr_set = -1;
1322         int             template_id = -1;
1323         int             answerable = 0;
1324         int             cacheable = 0;
1325         int             fattr_cnt=0;
1326         int             oc_attr_absent = 1;
1327
1328         struct berval tempstr;
1329
1330         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1331         tempstr.bv_len = 0;
1332         if (filter2template(op->ors_filter, &tempstr, &filter_attrs, &fattr_cnt)) {
1333                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1334                 return SLAP_CB_CONTINUE;
1335         }
1336
1337 #ifdef NEW_LOGGING
1338         LDAP_LOG( BACK_META, DETAIL1, "query template of incoming query = %s\n",
1339                                         tempstr.bv_val, 0, 0 );
1340 #else /* !NEW_LOGGING */
1341         Debug( LDAP_DEBUG_ANY, "query template of incoming query = %s\n",
1342                                         tempstr.bv_val, 0, 0 );
1343 #endif /* !NEW_LOGGING */
1344
1345         /* find attr set */
1346         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1347
1348         query.filter = op->ors_filter;
1349         query.attrs = op->ors_attrs;
1350         query.base = op->o_req_ndn;
1351         query.scope = op->ors_scope;
1352
1353         /* check for query containment */
1354         if (attr_set > -1) {
1355                 for (i=0; i<cm->numtemplates; i++) {
1356                         /* find if template i can potentially answer tempstr */
1357                         if (!is_temp_answerable(attr_set, &tempstr, qm, i))
1358                                 continue;
1359                         if (attr_set == qm->templates[i].attr_set_index) {
1360                                 cacheable = 1;
1361                                 template_id = i;
1362                         }
1363 #ifdef NEW_LOGGING
1364                         LDAP_LOG( BACK_META, DETAIL2,
1365                                         "Entering QC, querystr = %s\n",
1366                                         op->ors_filterstr.bv_val, 0, 0 );
1367 #else /* !NEW_LOGGING */
1368                         Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1369                                         op->ors_filterstr.bv_val, 0, 0 );
1370 #endif /* !NEW_LOGGING */
1371                         answerable = (*(qm->qcfunc))(qm, &query, i);
1372
1373                         if (answerable)
1374                                 break;
1375                 }
1376         }
1377         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1378
1379         if (answerable) {
1380                 BackendDB *be = op->o_bd;
1381 #ifdef NEW_LOGGING
1382                 LDAP_LOG( BACK_META, DETAIL1, "QUERY ANSWERABLE\n", 0, 0, 0 );
1383 #else /* !NEW_LOGGING */
1384                 Debug( LDAP_DEBUG_ANY, "QUERY ANSWERABLE\n", 0, 0, 0 );
1385 #endif /* !NEW_LOGGING */
1386                 free(filter_attrs);
1387                 ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock);
1388                 op->o_bd = &cm->db;
1389                 i = cm->db.bd_info->bi_op_search( op, rs );
1390                 op->o_bd = be;
1391                 return i;
1392         }
1393
1394 #ifdef NEW_LOGGING
1395         LDAP_LOG( BACK_META, DETAIL1, "QUERY NOT ANSWERABLE\n",
1396                                 0, 0, 0 );
1397 #else /* !NEW_LOGGING */
1398         Debug( LDAP_DEBUG_ANY, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1399 #endif /* !NEW_LOGGING */
1400
1401         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1402         if (cm->num_cached_queries >= cm->max_queries) {
1403                 cacheable = 0;
1404         }
1405         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1406
1407         if (cacheable) {
1408                 slap_callback *cb;
1409                 struct search_info *si;
1410 #ifdef NEW_LOGGING
1411                 LDAP_LOG( BACK_META, DETAIL1,
1412                         "QUERY CACHEABLE\n", 0, 0, 0 );
1413 #else /* !NEW_LOGGING */
1414                 Debug( LDAP_DEBUG_ANY, "QUERY CACHEABLE\n", 0, 0, 0 );
1415 #endif /* !NEW_LOGGING */
1416                 query.filter = str2filter(op->ors_filterstr.bv_val);
1417                 if (op->ors_attrs) {
1418                         for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ ) {
1419                                 if ( op->ors_attrs[count].an_desc == slap_schema.si_ad_objectClass )
1420                                         oc_attr_absent = 0;
1421                         }
1422                         query.attrs = (AttributeName*)ch_malloc( ( count + 1 + oc_attr_absent )
1423                                                                         *sizeof(AttributeName));
1424                         for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ ) {
1425                                 ber_dupbv( &query.attrs[count].an_name, &op->ors_attrs[count].an_name );
1426                                 query.attrs[count].an_desc = op->ors_attrs[count].an_desc;
1427                         }
1428                         if ( oc_attr_absent ) {
1429                                 query.attrs[ count ].an_desc = slap_schema.si_ad_objectClass;
1430                                 ber_dupbv( &query.attrs[count].an_name,
1431                                         &slap_schema.si_ad_objectClass->ad_cname );
1432                                 count++;
1433                         }
1434                         query.attrs[ count ].an_name.bv_val = NULL;
1435                         query.attrs[ count ].an_name.bv_len = 0;
1436                 }
1437                 op->o_tmpfree(op->ors_attrs, op->o_tmpmemctx);
1438                 add_filter_attrs(op, &op->ors_attrs, query.attrs, filter_attrs);
1439                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1440                 cb->sc_next = op->o_callback;
1441                 cb->sc_response = proxy_cache_response;
1442                 cb->sc_cleanup = NULL;
1443                 cb->sc_private = (cb+1);
1444                 si = cb->sc_private;
1445                 si->on = on;
1446                 si->query = query;
1447                 si->template_id = template_id;
1448                 si->max = cm->num_entries_limit ;
1449                 si->over = 0;
1450                 si->count = 0;
1451                 si->head = NULL;
1452                 si->tail = NULL;
1453                 op->o_callback = cb;
1454         } else {
1455 #ifdef NEW_LOGGING
1456                 LDAP_LOG( BACK_META, DETAIL1,
1457                                         "QUERY NOT CACHEABLE\n",
1458                                         0, 0, 0);
1459 #else /* !NEW_LOGGING */
1460                 Debug( LDAP_DEBUG_ANY, "QUERY NOT CACHEABLE\n",
1461                                         0, 0, 0);
1462 #endif /* !NEW_LOGGING */
1463         }
1464
1465         free(filter_attrs);
1466
1467         return SLAP_CB_CONTINUE;
1468 }
1469
1470 static int
1471 attrscmp(
1472         AttributeName* attrs_in,
1473         AttributeName* attrs)
1474 {
1475         int i, count1, count2;
1476         if ( attrs_in == NULL ) {
1477                 return (attrs ? 0 : 1);
1478         }
1479         if ( attrs == NULL )
1480                 return 0;
1481
1482         for ( count1=0;
1483               attrs_in && attrs_in[count1].an_name.bv_val != NULL;
1484               count1++ )
1485                 ;
1486         for ( count2=0;
1487               attrs && attrs[count2].an_name.bv_val != NULL;
1488               count2++)
1489                 ;
1490         if ( count1 != count2 )
1491                 return 0;
1492
1493         for ( i=0; i<count1; i++ ) {
1494                 if ( !an_find(attrs, &attrs_in[i].an_name ))
1495                         return 0;
1496         }
1497         return 1;
1498 }
1499
1500 static int
1501 get_attr_set(
1502         AttributeName* attrs,
1503         query_manager* qm,
1504         int num )
1505 {
1506         int i;
1507         for (i=0; i<num; i++) {
1508                 if (attrscmp(attrs, qm->attr_sets[i].attrs))
1509                         return i;
1510         }
1511         return -1;
1512 }
1513
1514 static void*
1515 consistency_check(
1516         void *ctx,
1517         void *arg )
1518 {
1519         struct re_s *rtask = arg;
1520         slap_overinst *on = rtask->arg;
1521         cache_manager *cm = on->on_bi.bi_private;
1522         query_manager *qm = cm->qm;
1523         Operation op = {0};
1524         Connection conn = {0};
1525
1526         SlapReply rs = {REP_RESULT};
1527         CachedQuery* query, *query_prev;
1528         int i, return_val, pause = 1;
1529         QueryTemplate* templ;
1530
1531         connection_fake_init( &conn, &op, ctx );
1532
1533         op.o_bd = &cm->db;
1534         op.o_dn = cm->db.be_rootdn;
1535         op.o_ndn = cm->db.be_rootndn;
1536
1537         cm->cc_arg = arg;
1538
1539         for (i=0; qm->templates[i].querystr.bv_val; i++) {
1540                 templ = qm->templates + i;
1541                 query = templ->query_last;
1542                 if ( query ) pause = 0;
1543                 op.o_time = slap_get_time();
1544                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1545                 while (query && (query->expiry_time < op.o_time)) {
1546                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1547                         remove_query(qm, query);
1548                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1549 #ifdef NEW_LOGGING
1550                         LDAP_LOG( BACK_META, DETAIL1, "Lock CR index = %d\n",
1551                                         i, 0, 0 );
1552 #else /* !NEW_LOGGING */
1553                         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n",
1554                                         i, 0, 0 );
1555 #endif /* !NEW_LOGGING */
1556                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1557                         remove_from_template(query, templ);
1558 #ifdef NEW_LOGGING
1559                         LDAP_LOG( BACK_META, DETAIL1,
1560                                         "TEMPLATE %d QUERIES-- %d\n",
1561                                         i, templ->no_of_queries, 0 );
1562 #else /* !NEW_LOGGING */
1563                         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
1564                                         i, templ->no_of_queries, 0 );
1565 #endif /* !NEW_LOGGING */
1566 #ifdef NEW_LOGGING
1567                         LDAP_LOG( BACK_META, DETAIL1, "Unlock CR index = %d\n",
1568                                         i, 0, 0 );
1569 #else /* !NEW_LOGGING */
1570                         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n",
1571                                         i, 0, 0 );
1572 #endif /* !NEW_LOGGING */
1573                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1574                         return_val = remove_query_data(&op, &rs, &query->q_uuid);
1575 #ifdef NEW_LOGGING
1576                         LDAP_LOG( BACK_META, DETAIL1,
1577                                         "STALE QUERY REMOVED, SIZE=%d\n",
1578                                         return_val, 0, 0 );
1579 #else /* !NEW_LOGGING */
1580                         Debug( LDAP_DEBUG_ANY, "STALE QUERY REMOVED, SIZE=%d\n",
1581                                                 return_val, 0, 0 );
1582 #endif /* !NEW_LOGGING */
1583                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1584                         cm->cur_entries -= return_val;
1585                         cm->num_cached_queries--;
1586 #ifdef NEW_LOGGING
1587                         LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1588                                         cm->num_cached_queries, 0, 0 );
1589 #else /* !NEW_LOGGING */
1590                         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1591                                         cm->num_cached_queries, 0, 0 );
1592 #endif /* !NEW_LOGGING */
1593                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1594 #ifdef NEW_LOGGING
1595                         LDAP_LOG( BACK_META, DETAIL1,
1596                                 "STALE QUERY REMOVED, CACHE ="
1597                                 "%d entries\n",
1598                                 cm->cur_entries, 0, 0 );
1599 #else /* !NEW_LOGGING */
1600                         Debug( LDAP_DEBUG_ANY,
1601                                 "STALE QUERY REMOVED, CACHE ="
1602                                 "%d entries\n",
1603                                 cm->cur_entries, 0, 0 );
1604 #endif /* !NEW_LOGGING */
1605                         query_prev = query;
1606                         query = query->prev;
1607                         free_query(query_prev);
1608                 }
1609                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1610         }
1611         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
1612         if ( ldap_pvt_runqueue_isrunning( &syncrepl_rq, rtask )) {
1613                 ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
1614         }
1615         /* If there were no queries, defer processing for a while */
1616         cm->cc_paused = pause;
1617         ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, pause );
1618
1619         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
1620         return NULL;
1621 }
1622
1623
1624 #define MAX_ATTR_SETS 500
1625 static void find_supersets( struct attr_set* attr_sets, int numsets );
1626 static int compare_sets( struct attr_set* setA, int, int );
1627
1628 static int
1629 proxy_cache_config(
1630         BackendDB       *be,
1631         const char      *fname,
1632         int             lineno,
1633         int             argc,
1634         char            **argv
1635 )
1636 {
1637         slap_overinst *on = (slap_overinst *)be->bd_info;
1638         cache_manager*  cm = on->on_bi.bi_private;
1639         query_manager*  qm = cm->qm;
1640         QueryTemplate*  temp;
1641         AttributeName*  attr_name;
1642         AttributeName*  attrarray;
1643         const char*     text=NULL;
1644
1645         int             index, i;
1646         int             num;
1647
1648         if ( strcasecmp( argv[0], "proxycache" ) == 0 ) {
1649                 if ( argc < 6 ) {
1650                         fprintf( stderr, "%s: line %d: missing arguments in \"proxycache"
1651                                 " <backend> <max_entries> <numattrsets> <entry limit> "
1652                                 "<cycle_time>\"\n", fname, lineno );
1653                         return( 1 );
1654                 }
1655
1656                 cm->db.bd_info = backend_info( argv[1] );
1657                 if ( !cm->db.bd_info ) {
1658                         fprintf( stderr, "%s: line %d: backend %s unknown\n",
1659                                 fname, lineno, argv[1] );
1660                         return( 1 );
1661                 }
1662                 if ( cm->db.bd_info->bi_db_init( &cm->db ) ) return( 1 );
1663
1664                 /* This type is in use, needs to be opened */
1665                 cm->db.bd_info->bi_nDB++;
1666
1667                 cm->max_entries = atoi( argv[2] );
1668
1669                 cm->numattrsets = atoi( argv[3] );
1670                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1671                         fprintf( stderr, "%s: line %d: numattrsets must be <= %d\n",
1672                                 fname, lineno, MAX_ATTR_SETS );
1673                         return( 1 );
1674                 }
1675
1676                 cm->num_entries_limit = atoi( argv[4] );
1677                 cm->cc_period = atoi( argv[5] );
1678 #ifdef NEW_LOGGING
1679                 LDAP_LOG( BACK_META, DETAIL1,
1680                                 "Total # of attribute sets to be cached = %d\n",
1681                                 cm->numattrsets, 0, 0 );
1682 #else
1683                 Debug( LDAP_DEBUG_ANY,
1684                                 "Total # of attribute sets to be cached = %d\n",
1685                                 cm->numattrsets, 0, 0 );
1686 #endif
1687                 qm->attr_sets = ( struct attr_set * )ch_malloc( cm->numattrsets *
1688                                                 sizeof( struct attr_set ));
1689                 for ( i = 0; i < cm->numattrsets; i++ ) {
1690                         qm->attr_sets[i].attrs = NULL;
1691                 }
1692
1693         } else if ( strcasecmp( argv[0], "proxyattrset" ) == 0 ) {
1694                 if ( argc < 3 ) {
1695                         fprintf( stderr, "%s: line %d: missing arguments in \"proxyattrset "
1696                                 "<index> <attributes>\"\n", fname, lineno );
1697                         return( 1 );
1698                 }
1699 #ifdef NEW_LOGGING
1700                 LDAP_LOG( BACK_META, DETAIL1, "Attribute Set # %d\n",
1701                                 atoi( argv[1] ), 0, 0 );
1702 #else
1703                 Debug( LDAP_DEBUG_ANY, "Attribute Set # %d\n",
1704                                 atoi( argv[1] ), 0, 0 );
1705 #endif
1706                 if (atoi(argv[1]) >= cm->numattrsets) {
1707                         fprintf( stderr, "%s; line %d index out of bounds \n",
1708                                         fname, lineno );
1709                         return 1;
1710                 }
1711                 index = atoi( argv[1] );
1712                 if ( argv[2] && strcmp( argv[2], "*" ) ) {
1713                         qm->attr_sets[index].count = argc - 2;
1714                         qm->attr_sets[index].attrs = (AttributeName*)ch_malloc(
1715                                                 (argc-1) * sizeof( AttributeName ));
1716                         attr_name = qm->attr_sets[index].attrs;
1717                         for ( i = 2; i < argc; i++ ) {
1718 #ifdef NEW_LOGGING
1719                                 LDAP_LOG( BACK_META, DETAIL1, "\t %s\n",
1720                                                 argv[i], 0, 0 );
1721 #else
1722                                 Debug( LDAP_DEBUG_ANY, "\t %s\n",
1723                                                 argv[i], 0, 0 );
1724 #endif
1725                                 ber_str2bv( argv[i], 0, 1,
1726                                                 &attr_name->an_name);
1727                                 attr_name->an_desc = NULL;
1728                                 slap_bv2ad( &attr_name->an_name,
1729                                                 &attr_name->an_desc, &text );
1730                                 attr_name++;
1731                                 attr_name->an_name.bv_val = NULL;
1732                                 attr_name->an_name.bv_len = 0;
1733                         }
1734                 }
1735         } else if ( strcasecmp( argv[0], "proxytemplate" ) == 0 ) {
1736                 if ( argc != 4 ) {
1737                         fprintf( stderr, "%s: line %d: missing argument(s) in "
1738                                 "\"proxytemplate <filter> <proj attr set> <TTL>\" line\n",
1739                                 fname, lineno );
1740                         return( 1 );
1741                 }
1742                 if (( i = atoi( argv[2] )) >= cm->numattrsets ) {
1743 #ifdef NEW_LOGGING
1744                         LDAP_LOG( BACK_META, DETAIL1,
1745                                         "%s: line %d, template index invalid\n",
1746                                         fname, lineno, 0 );
1747 #else
1748                         Debug( LDAP_DEBUG_ANY,
1749                                         "%s: line %d, template index invalid\n",
1750                                         fname, lineno, 0 );
1751 #endif
1752                         return 1;
1753                 }
1754                 num = cm->numtemplates;
1755                 if ( num == 0 )
1756                         find_supersets( qm->attr_sets, cm->numattrsets );
1757                 qm->templates = ( QueryTemplate* )ch_realloc( qm->templates,
1758                                 ( num + 2 ) * sizeof( QueryTemplate ));
1759                 temp = qm->templates + num;
1760                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
1761                 temp->query = temp->query_last = NULL;
1762                 temp->ttl = atoi( argv[3] );
1763                 temp->no_of_queries = 0;
1764                 if ( argv[1] == NULL ) {
1765 #ifdef NEW_LOGGING
1766                         LDAP_LOG( BACK_META, DETAIL1,
1767                                         "Templates string not specified "
1768                                         "for template %d\n", num, 0, 0 );
1769 #else
1770                         Debug( LDAP_DEBUG_ANY,
1771                                         "Templates string not specified "
1772                                         "for template %d\n", num, 0, 0 );
1773 #endif
1774                         return 1;
1775                 }
1776                 ber_str2bv( argv[1], 0, 1, &temp->querystr );
1777 #ifdef NEW_LOGGING
1778                 LDAP_LOG( BACK_META, DETAIL1, "Template:\n", 0, 0, 0 );
1779 #else
1780                 Debug( LDAP_DEBUG_ANY, "Template:\n", 0, 0, 0 );
1781 #endif
1782 #ifdef NEW_LOGGING
1783                 LDAP_LOG( BACK_META, DETAIL1, "  query template: %s\n",
1784                                 temp->querystr.bv_val, 0, 0 );
1785 #else
1786                 Debug( LDAP_DEBUG_ANY, "  query template: %s\n",
1787                                 temp->querystr.bv_val, 0, 0 );
1788 #endif
1789                 temp->attr_set_index = i;
1790 #ifdef NEW_LOGGING
1791                 LDAP_LOG( BACK_META, DETAIL1, "  attributes: \n", 0, 0, 0 );
1792 #else
1793                 Debug( LDAP_DEBUG_ANY, "  attributes: \n", 0, 0, 0 );
1794 #endif
1795                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
1796                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
1797 #ifdef NEW_LOGGING
1798                                 LDAP_LOG( BACK_META, DETAIL1, "\t%s\n",
1799                                         attrarray[i].an_name.bv_val, 0, 0 );
1800 #else
1801                                 Debug( LDAP_DEBUG_ANY, "\t%s\n",
1802                                         attrarray[i].an_name.bv_val, 0, 0 );
1803 #endif
1804                 }
1805                 temp++; 
1806                 temp->querystr.bv_val = NULL;
1807                 cm->numtemplates++;
1808         }
1809         /* anything else */
1810         else {
1811                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno, argc, argv );
1812         }
1813         return 0;
1814 }
1815
1816 static int
1817 proxy_cache_init(
1818         BackendDB *be
1819 )
1820 {
1821         slap_overinst *on = (slap_overinst *)be->bd_info;
1822         cache_manager *cm;
1823         query_manager *qm;
1824
1825         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
1826         on->on_bi.bi_private = cm;
1827
1828         qm = (query_manager*)ch_malloc(sizeof(query_manager));
1829
1830         cm->db = *be;
1831         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
1832         cm->db.be_private = NULL;
1833         cm->qm = qm;
1834         cm->numattrsets = 0;
1835         cm->numtemplates = 0; 
1836         cm->num_entries_limit = 5;
1837         cm->num_cached_queries = 0;
1838         cm->max_entries = 0;
1839         cm->cur_entries = 0;
1840         cm->max_queries = 10000;
1841         cm->cc_period = 1000;
1842         cm->cc_paused = 0;
1843
1844         qm->attr_sets = NULL;
1845         qm->templates = NULL;
1846         qm->lru_top = NULL;
1847         qm->lru_bottom = NULL;
1848
1849         qm->qcfunc = query_containment;
1850         qm->crfunc = cache_replacement;
1851         qm->addfunc = add_query;
1852         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
1853
1854         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
1855         ldap_pvt_thread_mutex_init(&cm->remove_mutex);
1856         return 0;
1857 }
1858
1859 static int
1860 proxy_cache_open(
1861         BackendDB *be
1862 )
1863 {
1864         slap_overinst *on = (slap_overinst *)be->bd_info;
1865         cache_manager *cm = on->on_bi.bi_private;
1866         int rc = 0;
1867
1868         if ( cm->db.bd_info->bi_db_open ) {
1869                 rc = cm->db.bd_info->bi_db_open( &cm->db );
1870         }
1871
1872         /* There is no runqueue in TOOL mode */
1873         if ( slapMode & SLAP_SERVER_MODE ) {
1874                 ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
1875                 ldap_pvt_runqueue_insert( &syncrepl_rq, cm->cc_period,
1876                         consistency_check, on );
1877                 ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
1878         }
1879
1880         return rc;
1881 }
1882
1883 static int
1884 proxy_cache_close(
1885         BackendDB *be
1886 )
1887 {
1888         slap_overinst *on = (slap_overinst *)be->bd_info;
1889         cache_manager *cm = on->on_bi.bi_private;
1890         query_manager *qm = cm->qm;
1891         int i, j, rc = 0;
1892
1893         if ( cm->db.bd_info->bi_db_close ) {
1894                 rc = cm->db.bd_info->bi_db_close( &cm->db );
1895         }
1896         for ( i=0; i<cm->numtemplates; i++ ) {
1897                 CachedQuery *qc, *qn;
1898                 for ( qc = qm->templates[i].query; qc; qc = qn ) {
1899                         qn = qc->next;
1900                         free_query( qc );
1901                 }
1902                 free( qm->templates[i].querystr.bv_val );
1903                 ldap_pvt_thread_rdwr_destroy( &qm->templates[i].t_rwlock );
1904         }
1905         free( qm->templates );
1906         qm->templates = NULL;
1907
1908         for ( i=0; i<cm->numattrsets; i++ ) {
1909                 free( qm->attr_sets[i].ID_array );
1910                 for ( j=0; j<qm->attr_sets[i].count; j++ ) {
1911                         free( qm->attr_sets[i].attrs[j].an_name.bv_val );
1912                 }
1913                 free( qm->attr_sets[i].attrs );
1914         }
1915         free( qm->attr_sets );
1916         qm->attr_sets = NULL;
1917
1918         return rc;
1919 }
1920
1921 static int
1922 proxy_cache_destroy(
1923         BackendDB *be
1924 )
1925 {
1926         slap_overinst *on = (slap_overinst *)be->bd_info;
1927         cache_manager *cm = on->on_bi.bi_private;
1928         query_manager *qm = cm->qm;
1929         int rc = 0;
1930
1931         if ( cm->db.bd_info->bi_db_destroy ) {
1932                 rc = cm->db.bd_info->bi_db_destroy( &cm->db );
1933         }
1934         ldap_pvt_thread_mutex_destroy(&qm->lru_mutex);
1935         ldap_pvt_thread_mutex_destroy(&cm->cache_mutex);
1936         ldap_pvt_thread_mutex_destroy(&cm->remove_mutex);
1937         free( qm );
1938         free( cm );
1939         return rc;
1940 }
1941
1942 static void
1943 find_supersets ( struct attr_set* attr_sets, int numsets )
1944 {
1945         int num[MAX_ATTR_SETS];
1946         int i, j, res;
1947         int* id_array;
1948         for ( i = 0; i < MAX_ATTR_SETS; i++ )
1949                 num[i] = 0;
1950
1951         for ( i = 0; i < numsets; i++ ) {
1952                 attr_sets[i].ID_array = (int*) ch_malloc( sizeof( int ) );
1953                 attr_sets[i].ID_array[0] = -1;
1954         }
1955
1956         for ( i = 0; i < numsets; i++ ) {
1957                 for ( j=i+1; j < numsets; j++ ) {
1958                         res = compare_sets( attr_sets, i, j );
1959                         switch ( res ) {
1960                         case 0:
1961                                 break;
1962                         case 3:
1963                         case 1:
1964                                 id_array = attr_sets[i].ID_array;
1965                                 attr_sets[i].ID_array = (int *) ch_realloc( id_array,
1966                                                         ( num[i] + 2 ) * sizeof( int ));
1967                                 attr_sets[i].ID_array[num[i]] = j;
1968                                 attr_sets[i].ID_array[num[i]+1] = -1;
1969                                 num[i]++;
1970                                 if (res == 1)
1971                                         break;
1972                         case 2:
1973                                 id_array = attr_sets[j].ID_array;
1974                                 attr_sets[j].ID_array = (int *) ch_realloc( id_array,
1975                                                 ( num[j] + 2 ) * sizeof( int ));
1976                                 attr_sets[j].ID_array[num[j]] = i;
1977                                 attr_sets[j].ID_array[num[j]+1] = -1;
1978                                 num[j]++;
1979                                 break;
1980                         }
1981                 }
1982         }
1983 }
1984
1985 /*
1986  * compares two sets of attributes (indices i and j)
1987  * returns 0: if neither set is contained in the other set
1988  *         1: if set i is contained in set j
1989  *         2: if set j is contained in set i
1990  *         3: the sets are equivalent
1991  */
1992
1993 static int
1994 compare_sets(struct attr_set* set, int i, int j)
1995 {
1996         int k,l,numI,numJ;
1997         int common=0;
1998         int result=0;
1999
2000         if (( set[i].attrs == NULL ) && ( set[j].attrs == NULL ))
2001                 return 3;
2002
2003         if ( set[i].attrs == NULL )
2004                 return 2;
2005
2006         if ( set[j].attrs == NULL )
2007                 return 1;
2008
2009         numI = set[i].count;
2010         numJ = set[j].count;
2011
2012         for ( l=0; l < numI; l++ ) {
2013                 for ( k = 0; k < numJ; k++ ) {
2014                         if ( strcmp( set[i].attrs[l].an_name.bv_val,
2015                                      set[j].attrs[k].an_name.bv_val ) == 0 )
2016                                 common++;
2017                 }
2018         }
2019
2020         if ( common == numI )
2021                 result = 1;
2022
2023         if ( common == numJ )
2024                 result += 2;
2025
2026         return result;
2027 }
2028
2029 static slap_overinst proxy_cache;
2030
2031 int pcache_init()
2032 {
2033         LDAPAttributeType *at;
2034         int code;
2035         const char *err;
2036
2037         at = ldap_str2attributetype( queryid_schema, &code, &err,
2038                 LDAP_SCHEMA_ALLOW_ALL );
2039         if ( !at ) {
2040                 fprintf( stderr, "AttributeType Load failed %s %s\n",
2041                         ldap_scherr2str(code), err );
2042                 return code;
2043         }
2044         code = at_add( at, &err );
2045         if ( !code ) {
2046                 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2047         }
2048         ldap_memfree( at );
2049         if ( code ) {
2050                 fprintf( stderr, "AttributeType Load failed %s %s\n",
2051                         scherr2str(code), err );
2052                 return code;
2053         }
2054
2055         proxy_cache.on_bi.bi_type = "proxycache";
2056         proxy_cache.on_bi.bi_db_init = proxy_cache_init;
2057         proxy_cache.on_bi.bi_db_config = proxy_cache_config;
2058         proxy_cache.on_bi.bi_db_open = proxy_cache_open;
2059         proxy_cache.on_bi.bi_db_close = proxy_cache_close;
2060         proxy_cache.on_bi.bi_db_destroy = proxy_cache_destroy;
2061         proxy_cache.on_bi.bi_op_search = proxy_cache_search;
2062
2063         return overlay_register( &proxy_cache );
2064 }
2065
2066 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2067 int init_module(int argc, char *argv[]) {
2068         return pcache_init();
2069 }
2070 #endif
2071
2072 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */