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