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