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