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