]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
Sync with HEAD
[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, 1 );
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_flags = 0;
858                         mod.sml_desc = ad_queryid;
859                         mod.sml_type = ad_queryid->ad_cname;
860                         mod.sml_values = vals;
861                         mod.sml_nvalues = NULL;
862                         mod.sml_next = NULL;
863                         Debug( LDAP_DEBUG_ANY,
864                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
865                                 query_uuid->bv_val, 0, 0 );
866
867                         op->orm_modlist = &mod;
868
869                         op->o_bd->be_modify( op, &sreply );
870                 }
871                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
872                 op->o_tmpfree( qi, op->o_tmpmemctx );
873         }
874         return deleted;
875 }
876
877 static int
878 get_attr_set(
879         AttributeName* attrs,
880         query_manager* qm,
881         int num
882 );
883
884 static int
885 attrscmp(
886         AttributeName* attrs_in,
887         AttributeName* attrs
888 );
889
890 static int
891 is_temp_answerable(
892         int attr_set,
893         struct berval* tempstr,
894         query_manager* qm,
895         int template_id )
896 {
897         QueryTemplate *qt = qm->templates + template_id;
898
899         if (attr_set != qt->attr_set_index) {
900                 int* id_array = qm->attr_sets[attr_set].ID_array;
901
902                 while (*id_array != -1) {
903                         if (*id_array == qt->attr_set_index)
904                                 break;
905                         id_array++;
906                 }
907                 if (*id_array == -1)
908                         return 0;
909         }
910         return (qt->querystr.bv_len == tempstr->bv_len &&
911                 strcasecmp(qt->querystr.bv_val, tempstr->bv_val) == 0);
912 }
913
914 static int
915 filter2template(
916         Filter                  *f,
917         struct                  berval *fstr,
918         AttributeName**         filter_attrs,
919         int*                    filter_cnt )
920 {
921         AttributeDescription *ad;
922
923         switch ( f->f_choice ) {
924         case LDAP_FILTER_EQUALITY:
925                 ad = f->f_av_desc;
926                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
927                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
928                 break;
929
930         case LDAP_FILTER_GE:
931                 ad = f->f_av_desc;
932                 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
933                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
934                 break;
935
936         case LDAP_FILTER_LE:
937                 ad = f->f_av_desc;
938                 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
939                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
940                 break;
941
942         case LDAP_FILTER_APPROX:
943                 ad = f->f_av_desc;
944                 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
945                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
946                 break;
947
948         case LDAP_FILTER_SUBSTRINGS:
949                 ad = f->f_sub_desc;
950                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
951                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
952                 break;
953
954         case LDAP_FILTER_PRESENT:
955                 ad = f->f_desc;
956                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
957                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
958                 break;
959
960         case LDAP_FILTER_AND:
961         case LDAP_FILTER_OR:
962         case LDAP_FILTER_NOT: {
963                 int rc = 0;
964                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
965                         f->f_choice == LDAP_FILTER_AND ? '&' :
966                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
967                 fstr->bv_len += sizeof("(%") - 1;
968
969                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
970                         rc = filter2template( f, fstr, filter_attrs, filter_cnt );
971                         if ( rc ) break;
972                 }
973                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
974                 fstr->bv_len += sizeof(")") - 1;
975
976                 return rc;
977                 }
978
979         default:
980                 strcpy( fstr->bv_val, "(?=?)" );
981                 fstr->bv_len += sizeof("(?=?)")-1;
982                 return -1;
983         }
984
985         *filter_attrs = (AttributeName *)ch_realloc(*filter_attrs,
986                                 (*filter_cnt + 2)*sizeof(AttributeName));
987
988         (*filter_attrs)[*filter_cnt].an_desc = ad;
989         (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
990         (*filter_attrs)[*filter_cnt].an_oc = NULL;
991         (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
992         BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
993         (*filter_cnt)++;
994         return 0;
995 }
996
997 struct search_info {
998         slap_overinst *on;
999         Query query;
1000         int template_id;
1001         int max;
1002         int over;
1003         int count;
1004         Entry *head, *tail;
1005 };
1006
1007 static int
1008 cache_entries(
1009         Operation       *op,
1010         SlapReply       *rs,
1011         struct berval *query_uuid)
1012 {
1013         struct search_info *si = op->o_callback->sc_private;
1014         slap_overinst *on = si->on;
1015         cache_manager *cm = on->on_bi.bi_private;
1016         query_manager*          qm = cm->qm;
1017         int             return_val = 0;
1018         Entry           *e;
1019         struct berval   crp_uuid;
1020         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1021         Operation op_tmp = *op;
1022
1023         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1024         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1025
1026         op_tmp.o_bd = &cm->db;
1027         op_tmp.o_dn = cm->db.be_rootdn;
1028         op_tmp.o_ndn = cm->db.be_rootndn;
1029
1030         Debug( LDAP_DEBUG_ANY, "UUID for query being added = %s\n",
1031                         uuidbuf, 0, 0 );
1032
1033         for ( e=si->head; e; e=si->head ) {
1034                 si->head = e->e_private;
1035                 e->e_private = NULL;
1036                 Debug( LDAP_DEBUG_NONE, "LOCKING REMOVE MUTEX\n", 0, 0, 0 );
1037                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1038                 Debug( LDAP_DEBUG_NONE, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1039                 while ( cm->cur_entries > (cm->max_entries) ) {
1040                                 qm->crfunc(qm, &crp_uuid);
1041                                 if (crp_uuid.bv_val) {
1042                                         Debug( LDAP_DEBUG_ANY,
1043                                                 "Removing query UUID %s\n",
1044                                                 crp_uuid.bv_val, 0, 0 );
1045                                         return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1046                                         Debug( LDAP_DEBUG_ANY,
1047                                                 "QUERY REMOVED, SIZE=%d\n",
1048                                                 return_val, 0, 0);
1049                                         ldap_pvt_thread_mutex_lock(
1050                                                         &cm->cache_mutex );
1051                                         cm->cur_entries -= return_val;
1052                                         cm->num_cached_queries--;
1053                                         Debug( LDAP_DEBUG_ANY,
1054                                                 "STORED QUERIES = %lu\n",
1055                                                 cm->num_cached_queries, 0, 0 );
1056                                         ldap_pvt_thread_mutex_unlock(
1057                                                         &cm->cache_mutex );
1058                                         Debug( LDAP_DEBUG_ANY,
1059                                                 "QUERY REMOVED, CACHE ="
1060                                                 "%d entries\n",
1061                                                 cm->cur_entries, 0, 0 );
1062                                 }
1063                 }
1064
1065                 return_val = merge_entry(&op_tmp, e, query_uuid);
1066                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1067                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1068                 cm->cur_entries += return_val;
1069                 Debug( LDAP_DEBUG_ANY,
1070                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1071                         cm->cur_entries, 0, 0 );
1072                 return_val = 0;
1073                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1074         }
1075         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1076         cm->num_cached_queries++;
1077         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1078                         cm->num_cached_queries, 0, 0 );
1079         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1080
1081         return return_val;
1082 }
1083
1084 static int
1085 proxy_cache_response(
1086         Operation       *op,
1087         SlapReply       *rs )
1088 {
1089         struct search_info *si = op->o_callback->sc_private;
1090         slap_overinst *on = si->on;
1091         cache_manager *cm = on->on_bi.bi_private;
1092         query_manager*          qm = cm->qm;
1093         struct berval uuid;
1094
1095         if ( rs->sr_type == REP_SEARCH ) {
1096                 Entry *e;
1097                 /* If we haven't exceeded the limit for this query,
1098                  * build a chain of answers to store. If we hit the
1099                  * limit, empty the chain and ignore the rest.
1100                  */
1101                 if ( !si->over ) {
1102                         if ( si->count < si->max ) {
1103                                 si->count++;
1104                                 e = entry_dup( rs->sr_entry );
1105                                 if ( !si->head ) si->head = e;
1106                                 if ( si->tail ) si->tail->e_private = e;
1107                                 si->tail = e;
1108                         } else {
1109                                 si->over = 1;
1110                                 si->count = 0;
1111                                 for (;si->head; si->head=e) {
1112                                         e = si->head->e_private;
1113                                         si->head->e_private = NULL;
1114                                         entry_free(si->head);
1115                                 }
1116                                 si->tail = NULL;
1117                         }
1118                 }
1119
1120                 if (rs->sr_attrs != op->ors_attrs ) {
1121                         op->o_tmpfree( rs->sr_attrs, op->o_tmpmemctx );
1122                 }
1123                 rs->sr_attrs = si->query.save_attrs;
1124                 op->o_tmpfree( op->ors_attrs, op->o_tmpmemctx );
1125                 op->ors_attrs = si->query.save_attrs;
1126                 si->query.save_attrs = NULL;
1127
1128         } else if ( rs->sr_type == REP_RESULT ) {
1129                 if ( si->count && cache_entries( op, rs, &uuid ) == 0 ) {
1130                         qm->addfunc(qm, &si->query, si->template_id, &uuid);
1131                         /* If the consistency checker suspended itself,
1132                          * wake it back up
1133                          */
1134                         if ( cm->cc_paused ) {
1135                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1136                                 if ( cm->cc_paused ) {
1137                                         cm->cc_paused = 0;
1138                                         ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1139                                 }
1140                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1141                         }
1142                 }
1143
1144                 /* free self */
1145                 op->o_callback->sc_cleanup = slap_freeself_cb;
1146         }
1147         return SLAP_CB_CONTINUE;
1148 }
1149
1150 static void
1151 add_filter_attrs(
1152         Operation *op,
1153         AttributeName** new_attrs,
1154         AttributeName* attrs,
1155         AttributeName* filter_attrs )
1156 {
1157         int alluser = 0;
1158         int allop = 0;
1159         int i;
1160         int count;
1161
1162         /* duplicate attrs */
1163         if (attrs == NULL) {
1164                 count = 1;
1165         } else {
1166                 for (count=0; attrs[count].an_name.bv_val; count++)
1167                         ;
1168         }
1169         *new_attrs = (AttributeName*)(op->o_tmpalloc((count+1)*
1170                 sizeof(AttributeName), op->o_tmpmemctx));
1171         if (attrs == NULL) {
1172                 BER_BVSTR( &(*new_attrs)[0].an_name, "*" );
1173                 (*new_attrs)[0].an_desc = NULL;
1174                 (*new_attrs)[0].an_oc = NULL;
1175                 (*new_attrs)[0].an_oc_exclude = 0;
1176                 BER_BVZERO( &(*new_attrs)[1].an_name );
1177                 alluser = 1;
1178                 allop = 0;
1179         } else {
1180                 for (i=0; i<count; i++) {
1181                         (*new_attrs)[i].an_name = attrs[i].an_name;
1182                         (*new_attrs)[i].an_desc = attrs[i].an_desc;
1183                 }
1184                 BER_BVZERO( &(*new_attrs)[count].an_name );
1185                 alluser = an_find(*new_attrs, &AllUser);
1186                 allop = an_find(*new_attrs, &AllOper);
1187         }
1188
1189         for ( i=0; filter_attrs[i].an_name.bv_val; i++ ) {
1190                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1191                         continue;
1192                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1193                         if (allop)
1194                                 continue;
1195                 } else if (alluser)
1196                         continue;
1197                 *new_attrs = (AttributeName*)(op->o_tmprealloc(*new_attrs,
1198                                         (count+2)*sizeof(AttributeName), op->o_tmpmemctx));
1199                 (*new_attrs)[count].an_name = filter_attrs[i].an_name;
1200                 (*new_attrs)[count].an_desc = filter_attrs[i].an_desc;
1201                 (*new_attrs)[count].an_oc = NULL;
1202                 (*new_attrs)[count].an_oc_exclude = 0;
1203                 count++;
1204                 BER_BVZERO( &(*new_attrs)[count].an_name );
1205         }
1206 }
1207
1208 /* NOTE: this is a quick workaround to let pcache minimally interact
1209  * with pagedResults.  A more articulated solutions would be to
1210  * perform the remote query without control and cache all results,
1211  * performing the pagedResults search only within the client
1212  * and the proxy.  This requires pcache to understand pagedResults. */
1213 static int
1214 proxy_cache_chk_controls(
1215         Operation       *op,
1216         SlapReply       *rs )
1217 {
1218         const char      *non = "";
1219         const char      *stripped = "";
1220
1221         switch( op->o_pagedresults ) {
1222         case SLAP_CONTROL_NONCRITICAL:
1223                 non = "non-";
1224                 stripped = "; stripped";
1225                 /* fallthru */
1226
1227         case SLAP_CONTROL_CRITICAL:
1228                 Debug( LDAP_DEBUG_ANY, "%s: "
1229                         "%scritical pagedResults control "
1230                         "disabled with proxy cache%s.\n",
1231                         op->o_log_prefix, non, stripped );
1232                 
1233                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1234                 break;
1235
1236         default:
1237                 rs->sr_err = SLAP_CB_CONTINUE;
1238                 break;
1239         }
1240
1241         return rs->sr_err;
1242 }
1243
1244 static int
1245 proxy_cache_search(
1246         Operation       *op,
1247         SlapReply       *rs )
1248 {
1249         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1250         cache_manager *cm = on->on_bi.bi_private;
1251         query_manager*          qm = cm->qm;
1252
1253         int count;
1254
1255         int i = -1;
1256
1257         AttributeName   *filter_attrs = NULL;
1258
1259         Query           query;
1260
1261         int             attr_set = -1;
1262         int             template_id = -1;
1263         int             answerable = 0;
1264         int             cacheable = 0;
1265         int             fattr_cnt=0;
1266         int             oc_attr_absent = 1;
1267
1268         struct berval tempstr;
1269
1270         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1271         tempstr.bv_len = 0;
1272         if (filter2template(op->ors_filter, &tempstr, &filter_attrs, &fattr_cnt)) {
1273                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1274                 return SLAP_CB_CONTINUE;
1275         }
1276
1277         Debug( LDAP_DEBUG_ANY, "query template of incoming query = %s\n",
1278                                         tempstr.bv_val, 0, 0 );
1279
1280         /* FIXME: cannot cache/answer requests with pagedResults control */
1281         
1282
1283         /* find attr set */
1284         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1285
1286         query.filter = op->ors_filter;
1287         query.attrs = op->ors_attrs;
1288         query.save_attrs = NULL;
1289         query.base = op->o_req_ndn;
1290         query.scope = op->ors_scope;
1291
1292         /* check for query containment */
1293         if (attr_set > -1) {
1294                 for (i=0; i<cm->numtemplates; i++) {
1295                         /* find if template i can potentially answer tempstr */
1296                         if (!is_temp_answerable(attr_set, &tempstr, qm, i))
1297                                 continue;
1298                         if (attr_set == qm->templates[i].attr_set_index) {
1299                                 cacheable = 1;
1300                                 template_id = i;
1301                         }
1302                         Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1303                                         op->ors_filterstr.bv_val, 0, 0 );
1304                         answerable = (*(qm->qcfunc))(qm, &query, i);
1305
1306                         if (answerable)
1307                                 break;
1308                 }
1309         }
1310         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1311
1312         query.save_attrs = op->ors_attrs;
1313         query.attrs = NULL;
1314
1315         if (answerable) {
1316                 /* Need to clear the callbacks of the original operation,
1317                  * in case there are other overlays */
1318                 BackendDB       *save_bd = op->o_bd;
1319                 slap_callback   *save_cb = op->o_callback;
1320
1321                 Debug( LDAP_DEBUG_ANY, "QUERY ANSWERABLE\n", 0, 0, 0 );
1322                 free(filter_attrs);
1323                 ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock);
1324                 op->o_bd = &cm->db;
1325                 op->o_callback = NULL;
1326                 i = cm->db.bd_info->bi_op_search( op, rs );
1327                 op->o_bd = save_bd;
1328                 op->o_callback = save_cb;
1329                 return i;
1330         }
1331
1332         Debug( LDAP_DEBUG_ANY, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1333
1334         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1335         if (cm->num_cached_queries >= cm->max_queries) {
1336                 cacheable = 0;
1337         }
1338         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1339
1340         if (cacheable) {
1341                 slap_callback           *cb;
1342                 struct search_info      *si;
1343
1344                 Debug( LDAP_DEBUG_ANY, "QUERY CACHEABLE\n", 0, 0, 0 );
1345                 query.filter = str2filter(op->ors_filterstr.bv_val);
1346                 if (op->ors_attrs) {
1347                         for ( count = 0; !BER_BVISNULL( &op->ors_attrs[ count ].an_name ); count++ ) {
1348                                 if ( op->ors_attrs[count].an_desc == slap_schema.si_ad_objectClass ) {
1349                                         oc_attr_absent = 0;
1350                                 }
1351                         }
1352                         query.attrs = (AttributeName *)ch_malloc( ( count + 1 + oc_attr_absent )
1353                                                                         *sizeof(AttributeName) );
1354                         for ( count = 0; !BER_BVISNULL( &op->ors_attrs[ count ].an_name ); count++ ) {
1355                                 ber_dupbv( &query.attrs[count].an_name, &op->ors_attrs[count].an_name );
1356                                 query.attrs[count].an_desc = op->ors_attrs[count].an_desc;
1357                                 query.attrs[count].an_oc = op->ors_attrs[count].an_oc;
1358                                 query.attrs[count].an_oc_exclude = op->ors_attrs[count].an_oc_exclude;
1359                         }
1360                         if ( oc_attr_absent ) {
1361                                 query.attrs[ count ].an_desc = slap_schema.si_ad_objectClass;
1362                                 ber_dupbv( &query.attrs[count].an_name,
1363                                         &slap_schema.si_ad_objectClass->ad_cname );
1364                                 query.attrs[ count ].an_oc = NULL;
1365                                 query.attrs[ count ].an_oc_exclude = 0;
1366                                 count++;
1367                         }
1368                         BER_BVZERO( &query.attrs[ count ].an_name );
1369                 }
1370                 add_filter_attrs(op, &op->ors_attrs, query.attrs, filter_attrs);
1371
1372                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1373                 cb->sc_response = proxy_cache_response;
1374                 cb->sc_cleanup = NULL;
1375                 cb->sc_private = (cb+1);
1376                 si = cb->sc_private;
1377                 si->on = on;
1378                 si->query = query;
1379                 si->template_id = template_id;
1380                 si->max = cm->num_entries_limit ;
1381                 si->over = 0;
1382                 si->count = 0;
1383                 si->head = NULL;
1384                 si->tail = NULL;
1385
1386                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1387                         cb->sc_next = op->o_callback;
1388                         op->o_callback = cb;
1389
1390                 } else {
1391                         slap_callback           **pcb;
1392
1393                         /* need to move the callback at the end, in case other
1394                          * overlays are present, so that the final entry is
1395                          * actually cached */
1396                         cb->sc_next = NULL;
1397                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1398                         *pcb = cb;
1399                 }
1400
1401         } else {
1402                 Debug( LDAP_DEBUG_ANY, "QUERY NOT CACHEABLE\n",
1403                                         0, 0, 0);
1404         }
1405
1406         free(filter_attrs);
1407
1408         return SLAP_CB_CONTINUE;
1409 }
1410
1411 static int
1412 attrscmp(
1413         AttributeName* attrs_in,
1414         AttributeName* attrs)
1415 {
1416         int i, count1, count2;
1417         if ( attrs_in == NULL ) {
1418                 return (attrs ? 0 : 1);
1419         }
1420         if ( attrs == NULL )
1421                 return 0;
1422
1423         for ( count1=0;
1424               attrs_in && attrs_in[count1].an_name.bv_val != NULL;
1425               count1++ )
1426                 ;
1427         for ( count2=0;
1428               attrs && attrs[count2].an_name.bv_val != NULL;
1429               count2++)
1430                 ;
1431         if ( count1 != count2 )
1432                 return 0;
1433
1434         for ( i=0; i<count1; i++ ) {
1435                 if ( !an_find(attrs, &attrs_in[i].an_name ))
1436                         return 0;
1437         }
1438         return 1;
1439 }
1440
1441 static int
1442 get_attr_set(
1443         AttributeName* attrs,
1444         query_manager* qm,
1445         int num )
1446 {
1447         int i;
1448         for (i=0; i<num; i++) {
1449                 if (attrscmp(attrs, qm->attr_sets[i].attrs))
1450                         return i;
1451         }
1452         return -1;
1453 }
1454
1455 static void*
1456 consistency_check(
1457         void *ctx,
1458         void *arg )
1459 {
1460         struct re_s *rtask = arg;
1461         slap_overinst *on = rtask->arg;
1462         cache_manager *cm = on->on_bi.bi_private;
1463         query_manager *qm = cm->qm;
1464         Connection conn = {0};
1465         OperationBuffer opbuf;
1466         Operation *op;
1467
1468         SlapReply rs = {REP_RESULT};
1469         CachedQuery* query, *query_prev;
1470         int i, return_val, pause = 1;
1471         QueryTemplate* templ;
1472
1473         op = (Operation *) &opbuf;
1474         connection_fake_init( &conn, op, ctx );
1475
1476         op->o_bd = &cm->db;
1477         op->o_dn = cm->db.be_rootdn;
1478         op->o_ndn = cm->db.be_rootndn;
1479
1480         cm->cc_arg = arg;
1481
1482         for (i=0; qm->templates[i].querystr.bv_val; i++) {
1483                 templ = qm->templates + i;
1484                 query = templ->query_last;
1485                 if ( query ) pause = 0;
1486                 op->o_time = slap_get_time();
1487                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1488                 while (query && (query->expiry_time < op->o_time)) {
1489                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1490                         remove_query(qm, query);
1491                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1492                         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n",
1493                                         i, 0, 0 );
1494                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1495                         remove_from_template(query, templ);
1496                         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
1497                                         i, templ->no_of_queries, 0 );
1498                         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n",
1499                                         i, 0, 0 );
1500                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1501                         return_val = remove_query_data(op, &rs, &query->q_uuid);
1502                         Debug( LDAP_DEBUG_ANY, "STALE QUERY REMOVED, SIZE=%d\n",
1503                                                 return_val, 0, 0 );
1504                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1505                         cm->cur_entries -= return_val;
1506                         cm->num_cached_queries--;
1507                         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1508                                         cm->num_cached_queries, 0, 0 );
1509                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1510                         Debug( LDAP_DEBUG_ANY,
1511                                 "STALE QUERY REMOVED, CACHE ="
1512                                 "%d entries\n",
1513                                 cm->cur_entries, 0, 0 );
1514                         query_prev = query;
1515                         query = query->prev;
1516                         free_query(query_prev);
1517                 }
1518                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1519         }
1520         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1521         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1522                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1523         }
1524         /* If there were no queries, defer processing for a while */
1525         cm->cc_paused = pause;
1526         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1527
1528         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1529         return NULL;
1530 }
1531
1532
1533 #define MAX_ATTR_SETS 500
1534
1535 /*
1536  * compares two sets of attributes (indices i and j)
1537  * returns 0: if neither set is contained in the other set
1538  *         1: if set i is contained in set j
1539  *         2: if set j is contained in set i
1540  *         3: the sets are equivalent
1541  */
1542
1543 static int
1544 compare_sets(struct attr_set* set, int i, int j)
1545 {
1546         int k,l,numI,numJ;
1547         int common=0;
1548         int result=0;
1549
1550         if (( set[i].attrs == NULL ) && ( set[j].attrs == NULL ))
1551                 return 3;
1552
1553         if ( set[i].attrs == NULL )
1554                 return 2;
1555
1556         if ( set[j].attrs == NULL )
1557                 return 1;
1558
1559         numI = set[i].count;
1560         numJ = set[j].count;
1561
1562         for ( l=0; l < numI; l++ ) {
1563                 for ( k = 0; k < numJ; k++ ) {
1564                         if ( strcmp( set[i].attrs[l].an_name.bv_val,
1565                                      set[j].attrs[k].an_name.bv_val ) == 0 )
1566                                 common++;
1567                 }
1568         }
1569
1570         if ( common == numI )
1571                 result = 1;
1572
1573         if ( common == numJ )
1574                 result += 2;
1575
1576         return result;
1577 }
1578
1579 static void
1580 find_supersets ( struct attr_set* attr_sets, int numsets )
1581 {
1582         int num[MAX_ATTR_SETS];
1583         int i, j, res;
1584         int* id_array;
1585         for ( i = 0; i < MAX_ATTR_SETS; i++ )
1586                 num[i] = 0;
1587
1588         for ( i = 0; i < numsets; i++ ) {
1589                 attr_sets[i].ID_array = (int*) ch_malloc( sizeof( int ) );
1590                 attr_sets[i].ID_array[0] = -1;
1591         }
1592
1593         for ( i = 0; i < numsets; i++ ) {
1594                 for ( j=i+1; j < numsets; j++ ) {
1595                         res = compare_sets( attr_sets, i, j );
1596                         switch ( res ) {
1597                         case 0:
1598                                 break;
1599                         case 3:
1600                         case 1:
1601                                 id_array = attr_sets[i].ID_array;
1602                                 attr_sets[i].ID_array = (int *) ch_realloc( id_array,
1603                                                         ( num[i] + 2 ) * sizeof( int ));
1604                                 attr_sets[i].ID_array[num[i]] = j;
1605                                 attr_sets[i].ID_array[num[i]+1] = -1;
1606                                 num[i]++;
1607                                 if (res == 1)
1608                                         break;
1609                         case 2:
1610                                 id_array = attr_sets[j].ID_array;
1611                                 attr_sets[j].ID_array = (int *) ch_realloc( id_array,
1612                                                 ( num[j] + 2 ) * sizeof( int ));
1613                                 attr_sets[j].ID_array[num[j]] = i;
1614                                 attr_sets[j].ID_array[num[j]+1] = -1;
1615                                 num[j]++;
1616                                 break;
1617                         }
1618                 }
1619         }
1620 }
1621
1622 enum {
1623         PC_MAIN = 1,
1624         PC_ATTR,
1625         PC_TEMP,
1626         PC_RESP
1627 };
1628
1629 static ConfigDriver pc_cf_gen;
1630 static ConfigLDAPadd pc_ldadd;
1631 static ConfigCfAdd pc_cfadd;
1632
1633 static ConfigTable pccfg[] = {
1634         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1635                                 "<cycle_time",
1636                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1637                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1638                         "DESC 'ProxyCache basic parameters' "
1639                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1640         { "proxyattrset", "index> <attributes...",
1641                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1642                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1643                         "DESC 'A set of attributes to cache' "
1644                         "SYNTAX OMsDirectoryString )", NULL, NULL },
1645         { "proxytemplate", "filter> <attrset-index> <TTL",
1646                 4, 4, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1647                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1648                         "DESC 'Filter template, attrset, and cache TTL' "
1649                         "SYNTAX OMsDirectoryString )", NULL, NULL },
1650         { "response-callback", "head|tail(default)",
1651                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1652                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1653                         "DESC 'Response callback position in overlay stack' "
1654                         "SYNTAX OMsDirectoryString )", NULL, NULL },
1655         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1656 };
1657
1658 static ConfigOCs pcocs[] = {
1659         { "( OLcfgOvOc:2.1 "
1660                 "NAME 'olcPcacheConfig' "
1661                 "DESC 'ProxyCache configuration' "
1662                 "SUP olcOverlayConfig "
1663                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1664                 "MAY olcProxyResponseCB )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1665         { "( OLcfgOvOc:2.2 "
1666                 "NAME 'olcPcacheDatabase' "
1667                 "DESC 'Cache database configuration' "
1668                 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1669         { NULL, 0, NULL }
1670 };
1671
1672 static int
1673 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1674 {
1675         slap_overinst *on;
1676         cache_manager *cm;
1677
1678         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1679                 p->ce_bi->bi_cf_ocs != pcocs )
1680                 return LDAP_CONSTRAINT_VIOLATION;
1681
1682         on = (slap_overinst *)p->ce_bi;
1683         cm = on->on_bi.bi_private;
1684         ca->be = &cm->db;
1685         return LDAP_SUCCESS;
1686 }
1687
1688 static int
1689 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1690 {
1691         CfEntryInfo *pe = p->e_private;
1692         slap_overinst *on = (slap_overinst *)pe->ce_bi;
1693         cache_manager *cm = on->on_bi.bi_private;
1694         struct berval bv;
1695
1696         /* FIXME: should not hardcode "olcDatabase" here */
1697         bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1698         bv.bv_val = ca->msg;
1699         ca->be = &cm->db;
1700
1701         /* We can only create this entry if the database is table-driven
1702          */
1703         if ( cm->db.bd_info->bi_cf_ocs )
1704                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1705                         &pcocs[1] );
1706
1707         return 0;
1708 }
1709
1710 static int
1711 pc_cf_gen( ConfigArgs *c )
1712 {
1713         slap_overinst *on = (slap_overinst *)c->bi;
1714         cache_manager*  cm = on->on_bi.bi_private;
1715         query_manager*  qm = cm->qm;
1716         QueryTemplate*  temp;
1717         AttributeName*  attr_name;
1718         AttributeName*  attrarray;
1719         const char*     text=NULL;
1720         int i, num, rc = 0;
1721         char *ptr;
1722
1723         if ( c->op == SLAP_CONFIG_EMIT ) {
1724                 struct berval bv;
1725                 switch( c->type ) {
1726                 case PC_MAIN:
1727                         bv.bv_len = sprintf( c->msg, "%s %d %d %d %d",
1728                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1729                                 cm->num_entries_limit, cm->cc_period );
1730                         bv.bv_val = c->msg;
1731                         value_add_one( &c->rvalue_vals, &bv );
1732                         break;
1733                 case PC_ATTR:
1734                         for (i=0; i<cm->numattrsets; i++) {
1735                                 if ( !qm->attr_sets[i].count ) continue;
1736
1737                                 bv.bv_len = sprintf( c->msg, "%d", i );
1738
1739                                 /* count the attr length */
1740                                 for ( attr_name = qm->attr_sets[i].attrs;
1741                                         attr_name->an_name.bv_val; attr_name++ )
1742                                         bv.bv_len += attr_name->an_name.bv_len + 1;
1743
1744                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
1745                                 ptr = lutil_strcopy( bv.bv_val, c->msg );
1746                                 for ( attr_name = qm->attr_sets[i].attrs;
1747                                         attr_name->an_name.bv_val; attr_name++ ) {
1748                                         *ptr++ = ' ';
1749                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1750                                 }
1751                                 ber_bvarray_add( &c->rvalue_vals, &bv );
1752                         }
1753                         if ( !c->rvalue_vals )
1754                                 rc = 1;
1755                         break;
1756                 case PC_TEMP:
1757                         for (i=0; i<cm->numtemplates; i++) {
1758                                 bv.bv_len = sprintf( c->msg, " %d %ld",
1759                                         qm->templates[i].attr_set_index,
1760                                         qm->templates[i].ttl );
1761                                 bv.bv_len += qm->templates[i].querystr.bv_len + 2;
1762                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
1763                                 ptr = bv.bv_val;
1764                                 *ptr++ = '"';
1765                                 ptr = lutil_strcopy( ptr, qm->templates[i].querystr.bv_val );
1766                                 *ptr++ = '"';
1767                                 strcpy( ptr, c->msg );
1768                                 ber_bvarray_add( &c->rvalue_vals, &bv );
1769                         }
1770                         if ( !c->rvalue_vals )
1771                                 rc = 1;
1772                         break;
1773                 case PC_RESP:
1774                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1775                                 BER_BVSTR( &bv, "head" );
1776                         } else {
1777                                 BER_BVSTR( &bv, "tail" );
1778                         }
1779                         value_add_one( &c->rvalue_vals, &bv );
1780                         break;
1781                 }
1782                 return rc;
1783         } else if ( c->op == LDAP_MOD_DELETE ) {
1784                 return 1;       /* FIXME */
1785 #if 0
1786                 switch( c->type ) {
1787                 case PC_ATTR:
1788                 case PC_TEMP:
1789                 }
1790                 return rc;
1791 #endif
1792         }
1793
1794         switch( c->type ) {
1795         case PC_MAIN:
1796                 cm->numattrsets = atoi( c->argv[3] );
1797                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1798                         sprintf( c->msg, "numattrsets must be <= %d", MAX_ATTR_SETS );
1799                         Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
1800                         return( 1 );
1801                 }
1802                 if ( !backend_db_init( c->argv[1], &cm->db )) {
1803                         sprintf( c->msg, "unknown backend type" );
1804                         Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
1805                         return( 1 );
1806                 }
1807                 cm->max_entries = atoi( c->argv[2] );
1808
1809                 cm->num_entries_limit = atoi( c->argv[4] );
1810                 cm->cc_period = atoi( c->argv[5] );
1811                 Debug( LDAP_DEBUG_TRACE,
1812                                 "Total # of attribute sets to be cached = %d\n",
1813                                 cm->numattrsets, 0, 0 );
1814                 qm->attr_sets = ( struct attr_set * )ch_malloc( cm->numattrsets *
1815                                                 sizeof( struct attr_set ));
1816                 for ( i = 0; i < cm->numattrsets; i++ ) {
1817                         qm->attr_sets[i].attrs = NULL;
1818                 }
1819                 break;
1820         case PC_ATTR:
1821                 num = atoi( c->argv[1] );
1822                 if (num >= cm->numattrsets) {
1823                         sprintf( c->msg, "attrset index out of bounds" );
1824                         Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
1825                         return 1;
1826                 }
1827                 if ( c->argv[2] && strcmp( c->argv[2], "*" ) ) {
1828                         qm->attr_sets[num].count = c->argc - 2;
1829                         qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
1830                                                 (c->argc-1) * sizeof( AttributeName ));
1831                         attr_name = qm->attr_sets[num].attrs;
1832                         for ( i = 2; i < c->argc; i++ ) {
1833                                 ber_str2bv( c->argv[i], 0, 1, &attr_name->an_name);
1834                                 attr_name->an_desc = NULL;
1835                                 if ( slap_bv2ad( &attr_name->an_name,
1836                                                 &attr_name->an_desc, &text )) {
1837                                         strcpy( c->msg, text );
1838                                         Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
1839                                         ch_free( qm->attr_sets[num].attrs );
1840                                         qm->attr_sets[num].attrs = NULL;
1841                                         qm->attr_sets[num].count = 0;
1842                                         return 1;
1843                                 }
1844                                 attr_name->an_oc = NULL;
1845                                 attr_name->an_oc_exclude = 0;
1846                                 attr_name++;
1847                                 BER_BVZERO( &attr_name->an_name );
1848                         }
1849                 }
1850                 break;
1851         case PC_TEMP:
1852                 if (( i = atoi( c->argv[2] )) >= cm->numattrsets ) {
1853                         sprintf( c->msg, "template index invalid" );
1854                         Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
1855                         return 1;
1856                 }
1857                 num = cm->numtemplates;
1858                 if ( num == 0 )
1859                         find_supersets( qm->attr_sets, cm->numattrsets );
1860                 qm->templates = ( QueryTemplate* )ch_realloc( qm->templates,
1861                                 ( num + 2 ) * sizeof( QueryTemplate ));
1862                 temp = qm->templates + num;
1863                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
1864                 temp->query = temp->query_last = NULL;
1865                 temp->ttl = atoi( c->argv[3] );
1866                 temp->no_of_queries = 0;
1867
1868                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
1869                 Debug( LDAP_DEBUG_TRACE, "Template:\n", 0, 0, 0 );
1870                 Debug( LDAP_DEBUG_TRACE, "  query template: %s\n",
1871                                 temp->querystr.bv_val, 0, 0 );
1872                 temp->attr_set_index = i;
1873                 Debug( LDAP_DEBUG_TRACE, "  attributes: \n", 0, 0, 0 );
1874                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
1875                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
1876                                 Debug( LDAP_DEBUG_TRACE, "\t%s\n",
1877                                         attrarray[i].an_name.bv_val, 0, 0 );
1878                 }
1879                 temp++; 
1880                 temp->querystr.bv_val = NULL;
1881                 cm->numtemplates++;
1882                 break;
1883         case PC_RESP:
1884                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
1885                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
1886
1887                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
1888                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1889
1890                 } else {
1891                         sprintf( c->msg, "unknown specifier" );
1892                         Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
1893                         return 1;
1894                 }
1895                 break;
1896         }
1897         return rc;
1898 }
1899
1900 static int
1901 proxy_cache_config(
1902         BackendDB       *be,
1903         const char      *fname,
1904         int             lineno,
1905         int             argc,
1906         char            **argv
1907 )
1908 {
1909         slap_overinst   *on = (slap_overinst *)be->bd_info;
1910         cache_manager*  cm = on->on_bi.bi_private;
1911
1912         /* Something for the cache database? */
1913         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
1914                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
1915                         argc, argv );
1916         return SLAP_CONF_UNKNOWN;
1917 }
1918
1919 static int
1920 proxy_cache_init(
1921         BackendDB *be
1922 )
1923 {
1924         slap_overinst *on = (slap_overinst *)be->bd_info;
1925         cache_manager *cm;
1926         query_manager *qm;
1927
1928         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
1929         on->on_bi.bi_private = cm;
1930
1931         qm = (query_manager*)ch_malloc(sizeof(query_manager));
1932
1933         cm->db = *be;
1934         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
1935         cm->db.be_private = NULL;
1936         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
1937         cm->qm = qm;
1938         cm->numattrsets = 0;
1939         cm->numtemplates = 0; 
1940         cm->num_entries_limit = 5;
1941         cm->num_cached_queries = 0;
1942         cm->max_entries = 0;
1943         cm->cur_entries = 0;
1944         cm->max_queries = 10000;
1945         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1946         cm->cc_period = 1000;
1947         cm->cc_paused = 0;
1948
1949         qm->attr_sets = NULL;
1950         qm->templates = NULL;
1951         qm->lru_top = NULL;
1952         qm->lru_bottom = NULL;
1953
1954         qm->qcfunc = query_containment;
1955         qm->crfunc = cache_replacement;
1956         qm->addfunc = add_query;
1957         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
1958
1959         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
1960         ldap_pvt_thread_mutex_init(&cm->remove_mutex);
1961         return 0;
1962 }
1963
1964 static int
1965 proxy_cache_open(
1966         BackendDB *be
1967 )
1968 {
1969         slap_overinst   *on = (slap_overinst *)be->bd_info;
1970         cache_manager   *cm = on->on_bi.bi_private;
1971         int             rc = 0;
1972
1973         /* need to inherit something from the original database... */
1974         cm->db.be_def_limit = be->be_def_limit;
1975         cm->db.be_limits = be->be_limits;
1976         cm->db.be_acl = be->be_acl;
1977         cm->db.be_dfltaccess = be->be_dfltaccess;
1978
1979         rc = backend_startup_one( &cm->db );
1980
1981         /* There is no runqueue in TOOL mode */
1982         if ( slapMode & SLAP_SERVER_MODE ) {
1983                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1984                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
1985                         consistency_check, on,
1986                         "pcache_consistency", be->be_suffix[0].bv_val );
1987                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1988
1989                 /* Cached database must have the rootdn */
1990                 if ( BER_BVISNULL( &cm->db.be_rootndn )
1991                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
1992                 {
1993                         Debug( LDAP_DEBUG_ANY, "proxy_cache_open(): "
1994                                 "underlying database of type \"%s\"\n"
1995                                 "    serving naming context \"%s\"\n"
1996                                 "    has no \"rootdn\", required by \"proxycache\".\n",
1997                                 on->on_info->oi_orig->bi_type,
1998                                 cm->db.be_suffix[0].bv_val, 0 );
1999                         return 1;
2000                 }
2001         }
2002
2003         return rc;
2004 }
2005
2006 static int
2007 proxy_cache_close(
2008         BackendDB *be
2009 )
2010 {
2011         slap_overinst *on = (slap_overinst *)be->bd_info;
2012         cache_manager *cm = on->on_bi.bi_private;
2013         query_manager *qm = cm->qm;
2014         int i, j, rc = 0;
2015
2016         /* cleanup stuff inherited from the original database... */
2017         cm->db.be_limits = NULL;
2018         cm->db.be_acl = NULL;
2019
2020         if ( cm->db.bd_info->bi_db_close ) {
2021                 rc = cm->db.bd_info->bi_db_close( &cm->db );
2022         }
2023         for ( i=0; i<cm->numtemplates; i++ ) {
2024                 CachedQuery *qc, *qn;
2025                 for ( qc = qm->templates[i].query; qc; qc = qn ) {
2026                         qn = qc->next;
2027                         free_query( qc );
2028                 }
2029                 free( qm->templates[i].querystr.bv_val );
2030                 ldap_pvt_thread_rdwr_destroy( &qm->templates[i].t_rwlock );
2031         }
2032         free( qm->templates );
2033         qm->templates = NULL;
2034
2035         for ( i=0; i<cm->numattrsets; i++ ) {
2036                 free( qm->attr_sets[i].ID_array );
2037                 for ( j=0; j<qm->attr_sets[i].count; j++ ) {
2038                         free( qm->attr_sets[i].attrs[j].an_name.bv_val );
2039                 }
2040                 free( qm->attr_sets[i].attrs );
2041         }
2042         free( qm->attr_sets );
2043         qm->attr_sets = NULL;
2044
2045         return rc;
2046 }
2047
2048 static int
2049 proxy_cache_destroy(
2050         BackendDB *be
2051 )
2052 {
2053         slap_overinst *on = (slap_overinst *)be->bd_info;
2054         cache_manager *cm = on->on_bi.bi_private;
2055         query_manager *qm = cm->qm;
2056
2057         /* cleanup stuff inherited from the original database... */
2058         cm->db.be_suffix = NULL;
2059         cm->db.be_nsuffix = NULL;
2060         BER_BVZERO( &cm->db.be_rootdn );
2061         BER_BVZERO( &cm->db.be_rootndn );
2062         BER_BVZERO( &cm->db.be_rootpw );
2063         /* FIXME: there might be more... */
2064
2065         backend_destroy_one( &cm->db, 0 );
2066
2067         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2068         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2069         ldap_pvt_thread_mutex_destroy( &cm->remove_mutex );
2070         free( qm );
2071         free( cm );
2072
2073         return 0;
2074 }
2075
2076 static slap_overinst proxy_cache;
2077
2078 int pcache_init()
2079 {
2080         LDAPAttributeType *at;
2081         int code;
2082         const char *err;
2083
2084         at = ldap_str2attributetype( queryid_schema, &code, &err,
2085                 LDAP_SCHEMA_ALLOW_ALL );
2086         if ( !at ) {
2087                 Debug( LDAP_DEBUG_ANY,
2088                         "pcache_init: ldap_str2attributetype failed %s %s\n",
2089                         ldap_scherr2str(code), err, 0 );
2090                 return code;
2091         }
2092         code = at_add( at, 0, NULL, &err );
2093         if ( !code ) {
2094                 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2095         }
2096         ldap_memfree( at );
2097         if ( code ) {
2098                 Debug( LDAP_DEBUG_ANY,
2099                         "pcache_init: at_add failed %s %s\n",
2100                         scherr2str(code), err, 0 );
2101                 return code;
2102         }
2103
2104         proxy_cache.on_bi.bi_type = "pcache";
2105         proxy_cache.on_bi.bi_db_init = proxy_cache_init;
2106         proxy_cache.on_bi.bi_db_config = proxy_cache_config;
2107         proxy_cache.on_bi.bi_db_open = proxy_cache_open;
2108         proxy_cache.on_bi.bi_db_close = proxy_cache_close;
2109         proxy_cache.on_bi.bi_db_destroy = proxy_cache_destroy;
2110         proxy_cache.on_bi.bi_op_search = proxy_cache_search;
2111
2112         proxy_cache.on_bi.bi_chk_controls = proxy_cache_chk_controls;
2113
2114         proxy_cache.on_bi.bi_cf_ocs = pcocs;
2115
2116         code = config_register_schema( pccfg, pcocs );
2117         if ( code ) return code;
2118
2119         return overlay_register( &proxy_cache );
2120 }
2121
2122 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2123 int init_module(int argc, char *argv[]) {
2124         return pcache_init();
2125 }
2126 #endif
2127
2128 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */