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