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