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