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