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