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