]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
happy new year
[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_response(
1256         Operation       *op,
1257         SlapReply       *rs )
1258 {
1259         struct search_info *si = op->o_callback->sc_private;
1260         slap_overinst *on = si->on;
1261         cache_manager *cm = on->on_bi.bi_private;
1262         query_manager*          qm = cm->qm;
1263
1264         if ( si->save_attrs != NULL ) {
1265                 rs->sr_attrs = si->save_attrs;
1266                 op->ors_attrs = si->save_attrs;
1267                 si->save_attrs = NULL;
1268         }
1269
1270         if ( rs->sr_type == REP_SEARCH ) {
1271                 Entry *e;
1272                 /* If we haven't exceeded the limit for this query,
1273                  * build a chain of answers to store. If we hit the
1274                  * limit, empty the chain and ignore the rest.
1275                  */
1276                 if ( !si->over ) {
1277                         if ( si->count < si->max ) {
1278                                 si->count++;
1279                                 e = entry_dup( rs->sr_entry );
1280                                 if ( !si->head ) si->head = e;
1281                                 if ( si->tail ) si->tail->e_private = e;
1282                                 si->tail = e;
1283                         } else {
1284                                 si->over = 1;
1285                                 si->count = 0;
1286                                 for (;si->head; si->head=e) {
1287                                         e = si->head->e_private;
1288                                         si->head->e_private = NULL;
1289                                         entry_free(si->head);
1290                                 }
1291                                 si->tail = NULL;
1292                         }
1293                 }
1294
1295         } else if ( rs->sr_type == REP_RESULT ) {
1296                 if ( si->count ||
1297                         ( si->qtemp->negttl && !si->count && !si->over &&
1298                                 rs->sr_err == LDAP_SUCCESS )) {
1299                         CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1300                                 si->count);
1301
1302                         if ( qc != NULL ) {
1303                                 if ( si->count )
1304                                         cache_entries( op, rs, &qc->q_uuid );
1305                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1306                                 cm->num_cached_queries++;
1307                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1308                                                 cm->num_cached_queries, 0, 0 );
1309                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1310
1311                                 /* If the consistency checker suspended itself,
1312                                  * wake it back up
1313                                  */
1314                                 if ( cm->cc_paused ) {
1315                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1316                                         if ( cm->cc_paused ) {
1317                                                 cm->cc_paused = 0;
1318                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1319                                         }
1320                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1321                                 }
1322                         } else if ( si->count ) {
1323                                 /* duplicate query, free it */
1324                                 Entry *e;
1325                                 for (;si->head; si->head=e) {
1326                                         e = si->head->e_private;
1327                                         si->head->e_private = NULL;
1328                                         entry_free(si->head);
1329                                 }
1330                         }
1331                 } else {
1332                         filter_free( si->query.filter );
1333                 }
1334
1335                 /* free self */
1336                 op->o_callback->sc_cleanup = slap_freeself_cb;
1337         }
1338         return SLAP_CB_CONTINUE;
1339 }
1340
1341 static void
1342 add_filter_attrs(
1343         Operation *op,
1344         AttributeName** new_attrs,
1345         struct attr_set *attrs,
1346         AttributeName* filter_attrs,
1347         int fattr_cnt,
1348         int fattr_got_oc)
1349 {
1350         int alluser = 0;
1351         int allop = 0;
1352         int i, j;
1353         int count;
1354         int addoc = 0;
1355
1356         /* duplicate attrs */
1357         count = attrs->count + fattr_cnt;
1358         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1359                 addoc = 1;
1360                 count++;
1361         }
1362
1363         *new_attrs = (AttributeName*)ch_malloc((count+1)*
1364                 sizeof(AttributeName));
1365         for (i=0; i<attrs->count; i++) {
1366                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1367                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1368         }
1369         BER_BVZERO( &(*new_attrs)[i].an_name );
1370         alluser = an_find(*new_attrs, &AllUser);
1371         allop = an_find(*new_attrs, &AllOper);
1372
1373         j = i;
1374         for ( i=0; i<fattr_cnt; i++ ) {
1375                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1376                         continue;
1377                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1378                         if (allop)
1379                                 continue;
1380                 } else if (alluser)
1381                         continue;
1382                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1383                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1384                 (*new_attrs)[j].an_oc = NULL;
1385                 (*new_attrs)[j].an_oc_exclude = 0;
1386                 j++;
1387         }
1388         if ( addoc ) {
1389                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1390                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1391                 (*new_attrs)[j].an_oc = NULL;
1392                 (*new_attrs)[j].an_oc_exclude = 0;
1393                 j++;
1394         }
1395         BER_BVZERO( &(*new_attrs)[j].an_name );
1396 }
1397
1398 /* NOTE: this is a quick workaround to let pcache minimally interact
1399  * with pagedResults.  A more articulated solutions would be to
1400  * perform the remote query without control and cache all results,
1401  * performing the pagedResults search only within the client
1402  * and the proxy.  This requires pcache to understand pagedResults. */
1403 static int
1404 pcache_chk_controls(
1405         Operation       *op,
1406         SlapReply       *rs )
1407 {
1408         const char      *non = "";
1409         const char      *stripped = "";
1410
1411         switch( op->o_pagedresults ) {
1412         case SLAP_CONTROL_NONCRITICAL:
1413                 non = "non-";
1414                 stripped = "; stripped";
1415                 /* fallthru */
1416
1417         case SLAP_CONTROL_CRITICAL:
1418                 Debug( pcache_debug, "%s: "
1419                         "%scritical pagedResults control "
1420                         "disabled with proxy cache%s.\n",
1421                         op->o_log_prefix, non, stripped );
1422                 
1423                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1424                 break;
1425
1426         default:
1427                 rs->sr_err = SLAP_CB_CONTINUE;
1428                 break;
1429         }
1430
1431         return rs->sr_err;
1432 }
1433
1434 static int
1435 pcache_op_search(
1436         Operation       *op,
1437         SlapReply       *rs )
1438 {
1439         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1440         cache_manager *cm = on->on_bi.bi_private;
1441         query_manager*          qm = cm->qm;
1442
1443         int i = -1;
1444
1445         AttributeName   *filter_attrs = NULL;
1446
1447         Query           query;
1448         QueryTemplate *qtemp = NULL;
1449
1450         int             attr_set = -1;
1451         CachedQuery     *answerable = NULL;
1452         int             cacheable = 0;
1453         int             fattr_cnt=0;
1454         int             fattr_got_oc = 0;
1455
1456         struct berval tempstr;
1457
1458         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1459         tempstr.bv_len = 0;
1460         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1461                 &fattr_cnt, &fattr_got_oc )) {
1462                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1463                 return SLAP_CB_CONTINUE;
1464         }
1465
1466         Debug( pcache_debug, "query template of incoming query = %s\n",
1467                                         tempstr.bv_val, 0, 0 );
1468
1469         /* FIXME: cannot cache/answer requests with pagedResults control */
1470
1471         /* find attr set */
1472         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1473
1474         query.filter = op->ors_filter;
1475         query.base = op->o_req_ndn;
1476         query.scope = op->ors_scope;
1477
1478         /* check for query containment */
1479         if (attr_set > -1) {
1480                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1481                 for (; qt; qt = qt->qtnext ) {
1482                         /* find if template i can potentially answer tempstr */
1483                         if (qt->querystr.bv_len != tempstr.bv_len ||
1484                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1485                                 continue;
1486                         cacheable = 1;
1487                         qtemp = qt;
1488                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
1489                                         op->ors_filterstr.bv_val, 0, 0 );
1490                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1491
1492                         if (answerable)
1493                                 break;
1494                 }
1495         }
1496         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1497
1498         if (answerable) {
1499                 /* Need to clear the callbacks of the original operation,
1500                  * in case there are other overlays */
1501                 BackendDB       *save_bd = op->o_bd;
1502                 slap_callback   *save_cb = op->o_callback;
1503
1504                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1505                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1506                 if ( BER_BVISNULL( &answerable->q_uuid )) {
1507                         /* No entries cached, just an empty result set */
1508                         i = rs->sr_err = 0;
1509                         send_ldap_result( op, rs );
1510                 } else {
1511                         op->o_bd = &cm->db;
1512                         op->o_callback = NULL;
1513                         i = cm->db.bd_info->bi_op_search( op, rs );
1514                 }
1515                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1516                 op->o_bd = save_bd;
1517                 op->o_callback = save_cb;
1518                 return i;
1519         }
1520
1521         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1522
1523         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1524         if (cm->num_cached_queries >= cm->max_queries) {
1525                 cacheable = 0;
1526         }
1527         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1528
1529         if (op->ors_attrsonly)
1530                 cacheable = 0;
1531
1532         if (cacheable) {
1533                 slap_callback           *cb;
1534                 struct search_info      *si;
1535
1536                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1537                 query.filter = filter_dup(op->ors_filter, NULL);
1538                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
1539                 if ( !qtemp->t_attrs.count ) {
1540                         add_filter_attrs(op, &qtemp->t_attrs.attrs,
1541                                 &qm->attr_sets[attr_set],
1542                                 filter_attrs, fattr_cnt, fattr_got_oc);
1543                 }
1544                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
1545
1546                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1547                 cb->sc_response = pcache_response;
1548                 cb->sc_cleanup = NULL;
1549                 cb->sc_private = (cb+1);
1550                 si = cb->sc_private;
1551                 si->on = on;
1552                 si->query = query;
1553                 si->qtemp = qtemp;
1554                 si->max = cm->num_entries_limit ;
1555                 si->over = 0;
1556                 si->count = 0;
1557                 si->head = NULL;
1558                 si->tail = NULL;
1559                 si->save_attrs = op->ors_attrs;
1560
1561                 op->ors_attrs = qtemp->t_attrs.attrs;
1562
1563                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1564                         cb->sc_next = op->o_callback;
1565                         op->o_callback = cb;
1566
1567                 } else {
1568                         slap_callback           **pcb;
1569
1570                         /* need to move the callback at the end, in case other
1571                          * overlays are present, so that the final entry is
1572                          * actually cached */
1573                         cb->sc_next = NULL;
1574                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1575                         *pcb = cb;
1576                 }
1577
1578         } else {
1579                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1580                                         0, 0, 0);
1581         }
1582
1583         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1584
1585         return SLAP_CB_CONTINUE;
1586 }
1587
1588 static int
1589 get_attr_set(
1590         AttributeName* attrs,
1591         query_manager* qm,
1592         int num )
1593 {
1594         int i;
1595         int count = 0;
1596
1597         if ( attrs ) {
1598                 for ( ; attrs[count].an_name.bv_val; count++ );
1599         }
1600
1601         for (i=0; i<num; i++) {
1602                 AttributeName *a2;
1603                 int found = 1;
1604
1605                 if ( count > qm->attr_sets[i].count )
1606                         continue;
1607                 if ( !count ) {
1608                         if ( !qm->attr_sets[i].count )
1609                                 break;
1610                         continue;
1611                 }
1612                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1613                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1614                                 found = 0;
1615                                 break;
1616                         }
1617                 }
1618                 if ( found )
1619                         break;
1620         }
1621         if ( i == num )
1622                 i = -1;
1623         return i;
1624 }
1625
1626 static void*
1627 consistency_check(
1628         void *ctx,
1629         void *arg )
1630 {
1631         struct re_s *rtask = arg;
1632         slap_overinst *on = rtask->arg;
1633         cache_manager *cm = on->on_bi.bi_private;
1634         query_manager *qm = cm->qm;
1635         Connection conn = {0};
1636         OperationBuffer opbuf;
1637         Operation *op;
1638
1639         SlapReply rs = {REP_RESULT};
1640         CachedQuery* query;
1641         int return_val, pause = 1;
1642         QueryTemplate* templ;
1643
1644         op = (Operation *) &opbuf;
1645         connection_fake_init( &conn, op, ctx );
1646
1647         op->o_bd = &cm->db;
1648         op->o_dn = cm->db.be_rootdn;
1649         op->o_ndn = cm->db.be_rootndn;
1650
1651         cm->cc_arg = arg;
1652
1653         for (templ = qm->templates; templ; templ=templ->qmnext) {
1654                 query = templ->query_last;
1655                 if ( query ) pause = 0;
1656                 op->o_time = slap_get_time();
1657                 while (query && (query->expiry_time < op->o_time)) {
1658                         int rem = 0;
1659                         Debug( pcache_debug, "Lock CR index = %p\n",
1660                                         (void *) templ, 0, 0 );
1661                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1662                         if ( query == templ->query_last ) {
1663                                 rem = 1;
1664                                 remove_from_template(query, templ);
1665                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1666                                                 (void *) templ, templ->no_of_queries, 0 );
1667                                 Debug( pcache_debug, "Unlock CR index = %p\n",
1668                                                 (void *) templ, 0, 0 );
1669                         }
1670                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1671                         if ( !rem ) {
1672                                 query = templ->query_last;
1673                                 continue;
1674                         }
1675                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1676                         remove_query(qm, query);
1677                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1678                         if ( BER_BVISNULL( &query->q_uuid ))
1679                                 return_val = 0;
1680                         else
1681                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
1682                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1683                                                 return_val, 0, 0 );
1684                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1685                         cm->cur_entries -= return_val;
1686                         cm->num_cached_queries--;
1687                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
1688                                         cm->num_cached_queries, 0, 0 );
1689                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1690                         Debug( pcache_debug,
1691                                 "STALE QUERY REMOVED, CACHE ="
1692                                 "%d entries\n",
1693                                 cm->cur_entries, 0, 0 );
1694                         free_query(query);
1695                         query = templ->query_last;
1696                 }
1697         }
1698         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1699         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1700                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1701         }
1702         /* If there were no queries, defer processing for a while */
1703         cm->cc_paused = pause;
1704         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1705
1706         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1707         return NULL;
1708 }
1709
1710
1711 #define MAX_ATTR_SETS 500
1712
1713 enum {
1714         PC_MAIN = 1,
1715         PC_ATTR,
1716         PC_TEMP,
1717         PC_RESP,
1718         PC_QUERIES
1719 };
1720
1721 static ConfigDriver pc_cf_gen;
1722 static ConfigLDAPadd pc_ldadd;
1723 static ConfigCfAdd pc_cfadd;
1724
1725 static ConfigTable pccfg[] = {
1726         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1727                                 "<cycle_time",
1728                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1729                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1730                         "DESC 'ProxyCache basic parameters' "
1731                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1732         { "proxyattrset", "index> <attributes...",
1733                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1734                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1735                         "DESC 'A set of attributes to cache' "
1736                         "SYNTAX OMsDirectoryString )", NULL, NULL },
1737         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1738                 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1739                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1740                         "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1741                         "SYNTAX OMsDirectoryString )", NULL, NULL },
1742         { "response-callback", "head|tail(default)",
1743                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1744                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1745                         "DESC 'Response callback position in overlay stack' "
1746                         "SYNTAX OMsDirectoryString )", NULL, NULL },
1747         { "proxyCacheQueries", "queries",
1748                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1749                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1750                         "DESC 'Maximum number of queries to cache' "
1751                         "SYNTAX OMsInteger )", NULL, NULL },
1752
1753         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1754 };
1755
1756 static ConfigOCs pcocs[] = {
1757         { "( OLcfgOvOc:2.1 "
1758                 "NAME 'olcPcacheConfig' "
1759                 "DESC 'ProxyCache configuration' "
1760                 "SUP olcOverlayConfig "
1761                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1762                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1763         { "( OLcfgOvOc:2.2 "
1764                 "NAME 'olcPcacheDatabase' "
1765                 "DESC 'Cache database configuration' "
1766                 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1767         { NULL, 0, NULL }
1768 };
1769
1770 static int
1771 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1772 {
1773         slap_overinst *on;
1774         cache_manager *cm;
1775
1776         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1777                 p->ce_bi->bi_cf_ocs != pcocs )
1778                 return LDAP_CONSTRAINT_VIOLATION;
1779
1780         on = (slap_overinst *)p->ce_bi;
1781         cm = on->on_bi.bi_private;
1782         ca->be = &cm->db;
1783         return LDAP_SUCCESS;
1784 }
1785
1786 static int
1787 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1788 {
1789         CfEntryInfo *pe = p->e_private;
1790         slap_overinst *on = (slap_overinst *)pe->ce_bi;
1791         cache_manager *cm = on->on_bi.bi_private;
1792         struct berval bv;
1793
1794         /* FIXME: should not hardcode "olcDatabase" here */
1795         bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1796         bv.bv_val = ca->msg;
1797         ca->be = &cm->db;
1798
1799         /* We can only create this entry if the database is table-driven
1800          */
1801         if ( cm->db.bd_info->bi_cf_ocs )
1802                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1803                         &pcocs[1] );
1804
1805         return 0;
1806 }
1807
1808 static int
1809 pc_cf_gen( ConfigArgs *c )
1810 {
1811         slap_overinst   *on = (slap_overinst *)c->bi;
1812         cache_manager*  cm = on->on_bi.bi_private;
1813         query_manager*  qm = cm->qm;
1814         QueryTemplate*  temp;
1815         AttributeName*  attr_name;
1816         AttributeName*  attrarray;
1817         const char*     text=NULL;
1818         int             i, num, rc = 0;
1819         char            *ptr;
1820         unsigned long   t;
1821
1822         if ( c->op == SLAP_CONFIG_EMIT ) {
1823                 struct berval bv;
1824                 switch( c->type ) {
1825                 case PC_MAIN:
1826                         bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1827                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1828                                 cm->num_entries_limit, cm->cc_period );
1829                         bv.bv_val = c->msg;
1830                         value_add_one( &c->rvalue_vals, &bv );
1831                         break;
1832                 case PC_ATTR:
1833                         for (i=0; i<cm->numattrsets; i++) {
1834                                 if ( !qm->attr_sets[i].count ) continue;
1835
1836                                 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1837
1838                                 /* count the attr length */
1839                                 for ( attr_name = qm->attr_sets[i].attrs;
1840                                         attr_name->an_name.bv_val; attr_name++ )
1841                                         bv.bv_len += attr_name->an_name.bv_len + 1;
1842
1843                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
1844                                 ptr = lutil_strcopy( bv.bv_val, c->msg );
1845                                 for ( attr_name = qm->attr_sets[i].attrs;
1846                                         attr_name->an_name.bv_val; attr_name++ ) {
1847                                         *ptr++ = ' ';
1848                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1849                                 }
1850                                 ber_bvarray_add( &c->rvalue_vals, &bv );
1851                         }
1852                         if ( !c->rvalue_vals )
1853                                 rc = 1;
1854                         break;
1855                 case PC_TEMP:
1856                         for (temp=qm->templates; temp; temp=temp->qmnext) {
1857                                 if ( temp->negttl ) {
1858                                         bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1859                                                 " %d %ld %ld",
1860                                                 temp->attr_set_index,
1861                                                 temp->ttl,
1862                                                 temp->negttl );
1863                                 } else {
1864                                         bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1865                                                 temp->attr_set_index,
1866                                                 temp->ttl );
1867                                 }
1868                                 bv.bv_len += temp->querystr.bv_len + 2;
1869                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
1870                                 ptr = bv.bv_val;
1871                                 *ptr++ = '"';
1872                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
1873                                 *ptr++ = '"';
1874                                 strcpy( ptr, c->msg );
1875                                 ber_bvarray_add( &c->rvalue_vals, &bv );
1876                         }
1877                         if ( !c->rvalue_vals )
1878                                 rc = 1;
1879                         break;
1880                 case PC_RESP:
1881                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1882                                 BER_BVSTR( &bv, "head" );
1883                         } else {
1884                                 BER_BVSTR( &bv, "tail" );
1885                         }
1886                         value_add_one( &c->rvalue_vals, &bv );
1887                         break;
1888                 case PC_QUERIES:
1889                         c->value_int = cm->max_queries;
1890                         break;
1891                 }
1892                 return rc;
1893         } else if ( c->op == LDAP_MOD_DELETE ) {
1894                 return 1;       /* FIXME */
1895 #if 0
1896                 switch( c->type ) {
1897                 case PC_ATTR:
1898                 case PC_TEMP:
1899                 }
1900                 return rc;
1901 #endif
1902         }
1903
1904         switch( c->type ) {
1905         case PC_MAIN:
1906                 if ( cm->numattrsets > 0 ) {
1907                         snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1908                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1909                         return( 1 );
1910                 }
1911
1912                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1913                         snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1914                                 c->argv[3] );
1915                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1916                         return( 1 );
1917                 }
1918                 if ( cm->numattrsets <= 0 ) {
1919                         snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1920                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1921                         return( 1 );
1922                 }
1923                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1924                         snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1925                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1926                         return( 1 );
1927                 }
1928
1929                 if ( !backend_db_init( c->argv[1], &cm->db, -1 )) {
1930                         snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1931                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1932                         return( 1 );
1933                 }
1934
1935                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1936                         snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1937                                 c->argv[2] );
1938                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1939                         return( 1 );
1940                 }
1941                 if ( cm->max_entries <= 0 ) {
1942                         snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1943                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1944                         return( 1 );
1945                 }
1946
1947                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1948                         snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1949                                 c->argv[4] );
1950                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1951                         return( 1 );
1952                 }
1953                 if ( cm->num_entries_limit <= 0 ) {
1954                         snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1955                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1956                         return( 1 );
1957                 }
1958                 if ( cm->num_entries_limit > cm->max_entries ) {
1959                         snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1960                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1961                         return( 1 );
1962                 }
1963
1964                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1965                         snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1966                                 c->argv[5] );
1967                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1968                         return( 1 );
1969                 }
1970                 cm->cc_period = (time_t)t;
1971                 Debug( pcache_debug,
1972                                 "Total # of attribute sets to be cached = %d.\n",
1973                                 cm->numattrsets, 0, 0 );
1974                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1975                                                 sizeof( struct attr_set ) );
1976                 break;
1977         case PC_ATTR:
1978                 if ( cm->numattrsets == 0 ) {
1979                         snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1980                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1981                         return( 1 );
1982                 }
1983                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1984                         snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1985                                 c->argv[1] );
1986                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1987                         return( 1 );
1988                 }
1989
1990                 if ( num < 0 || num >= cm->numattrsets ) {
1991                         snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
1992                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1993                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1994                         return 1;
1995                 }
1996                 qm->attr_sets[num].flags |= PC_CONFIGURED;
1997                 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
1998                         qm->attr_sets[num].count = c->argc - 2;
1999                         qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
2000                                                 (c->argc-1) * sizeof( AttributeName ));
2001                         attr_name = qm->attr_sets[num].attrs;
2002                         for ( i = 2; i < c->argc; i++ ) {
2003                                 attr_name->an_desc = NULL;
2004                                 if ( slap_str2ad( c->argv[i], 
2005                                                 &attr_name->an_desc, &text ) )
2006                                 {
2007                                         strcpy( c->msg, text );
2008                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2009                                         ch_free( qm->attr_sets[num].attrs );
2010                                         qm->attr_sets[num].attrs = NULL;
2011                                         qm->attr_sets[num].count = 0;
2012                                         return 1;
2013                                 }
2014                                 attr_name->an_name = attr_name->an_desc->ad_cname;
2015                                 attr_name->an_oc = NULL;
2016                                 attr_name->an_oc_exclude = 0;
2017                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2018                                         qm->attr_sets[num].flags |= PC_GOT_OC;
2019                                 attr_name++;
2020                                 BER_BVZERO( &attr_name->an_name );
2021                         }
2022                 }
2023                 break;
2024         case PC_TEMP:
2025                 if ( cm->numattrsets == 0 ) {
2026                         snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
2027                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2028                         return( 1 );
2029                 }
2030                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2031                         snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
2032                                 c->argv[2] );
2033                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2034                         return( 1 );
2035                 }
2036
2037                 if ( i < 0 || i >= cm->numattrsets || 
2038                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2039                         snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
2040                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2041                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2042                         return 1;
2043                 }
2044                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2045                 temp->qmnext = qm->templates;
2046                 qm->templates = temp;
2047                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2048                 temp->query = temp->query_last = NULL;
2049                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2050                         snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
2051                                 c->argv[3] );
2052                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2053                         return( 1 );
2054                 }
2055                 temp->ttl = (time_t)t;
2056                 if ( c->argc == 5 ) {
2057                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2058                                 snprintf( c->msg, sizeof( c->msg ),
2059                                         "unable to parse template negttl=\"%s\"",
2060                                         c->argv[4] );
2061                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2062                                         return( 1 );
2063                         }
2064                         temp->negttl = (time_t)t;
2065                 } else {
2066                         temp->negttl = 0;
2067                 }
2068
2069                 temp->no_of_queries = 0;
2070
2071                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2072                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2073                 Debug( pcache_debug, "  query template: %s\n",
2074                                 temp->querystr.bv_val, 0, 0 );
2075                 temp->attr_set_index = i;
2076                 qm->attr_sets[i].flags |= PC_REFERENCED;
2077                 temp->qtnext = qm->attr_sets[i].templates;
2078                 qm->attr_sets[i].templates = temp;
2079                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
2080                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2081                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
2082                                 Debug( pcache_debug, "\t%s\n",
2083                                         attrarray[i].an_name.bv_val, 0, 0 );
2084                 }
2085                 break;
2086         case PC_RESP:
2087                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2088                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2089
2090                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2091                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2092
2093                 } else {
2094                         snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
2095                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2096                         return 1;
2097                 }
2098                 break;
2099         case PC_QUERIES:
2100                 if ( c->value_int <= 0 ) {
2101                         snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
2102                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2103                         return( 1 );
2104                 }
2105                 cm->max_queries = c->value_int;
2106                 break;
2107         }
2108         return rc;
2109 }
2110
2111 static int
2112 pcache_db_config(
2113         BackendDB       *be,
2114         const char      *fname,
2115         int             lineno,
2116         int             argc,
2117         char            **argv
2118 )
2119 {
2120         slap_overinst   *on = (slap_overinst *)be->bd_info;
2121         cache_manager*  cm = on->on_bi.bi_private;
2122
2123         /* Something for the cache database? */
2124         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2125                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2126                         argc, argv );
2127         return SLAP_CONF_UNKNOWN;
2128 }
2129
2130 static int
2131 pcache_db_init(
2132         BackendDB *be )
2133 {
2134         slap_overinst *on = (slap_overinst *)be->bd_info;
2135         cache_manager *cm;
2136         query_manager *qm;
2137
2138         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2139         on->on_bi.bi_private = cm;
2140
2141         qm = (query_manager*)ch_malloc(sizeof(query_manager));
2142
2143         cm->db = *be;
2144         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2145         cm->db.be_private = NULL;
2146         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2147         cm->qm = qm;
2148         cm->numattrsets = 0;
2149         cm->num_entries_limit = 5;
2150         cm->num_cached_queries = 0;
2151         cm->max_entries = 0;
2152         cm->cur_entries = 0;
2153         cm->max_queries = 10000;
2154         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2155         cm->cc_period = 1000;
2156         cm->cc_paused = 0;
2157
2158         qm->attr_sets = NULL;
2159         qm->templates = NULL;
2160         qm->lru_top = NULL;
2161         qm->lru_bottom = NULL;
2162
2163         qm->qcfunc = query_containment;
2164         qm->crfunc = cache_replacement;
2165         qm->addfunc = add_query;
2166         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2167
2168         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2169         return 0;
2170 }
2171
2172 static int
2173 pcache_db_open(
2174         BackendDB *be )
2175 {
2176         slap_overinst   *on = (slap_overinst *)be->bd_info;
2177         cache_manager   *cm = on->on_bi.bi_private;
2178         query_manager*  qm = cm->qm;
2179         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2180
2181         /* check attr sets */
2182         for ( i = 0; i < cm->numattrsets; i++) {
2183                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2184                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2185                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2186                                 rf++;
2187
2188                         } else {
2189                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2190                         }
2191                         ncf++;
2192
2193                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2194                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2195                         nrf++;
2196                 }
2197         }
2198
2199         if ( ncf || rf || nrf ) {
2200                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2201                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2202                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2203
2204                 if ( rf > 0 ) {
2205                         return 1;
2206                 }
2207         }
2208
2209         /* need to inherit something from the original database... */
2210         cm->db.be_def_limit = be->be_def_limit;
2211         cm->db.be_limits = be->be_limits;
2212         cm->db.be_acl = be->be_acl;
2213         cm->db.be_dfltaccess = be->be_dfltaccess;
2214
2215         if ( SLAP_DBMONITORING( be ) ) {
2216                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2217
2218         } else {
2219                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2220         }
2221
2222         rc = backend_startup_one( &cm->db );
2223
2224         /* There is no runqueue in TOOL mode */
2225         if ( slapMode & SLAP_SERVER_MODE ) {
2226                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2227                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2228                         consistency_check, on,
2229                         "pcache_consistency", be->be_suffix[0].bv_val );
2230                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2231
2232                 /* Cached database must have the rootdn */
2233                 if ( BER_BVISNULL( &cm->db.be_rootndn )
2234                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2235                 {
2236                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2237                                 "underlying database of type \"%s\"\n"
2238                                 "    serving naming context \"%s\"\n"
2239                                 "    has no \"rootdn\", required by \"proxycache\".\n",
2240                                 on->on_info->oi_orig->bi_type,
2241                                 cm->db.be_suffix[0].bv_val, 0 );
2242                         return 1;
2243                 }
2244         }
2245
2246         return rc;
2247 }
2248
2249 static void
2250 pcache_free_qbase( void *v )
2251 {
2252         Qbase *qb = v;
2253         int i;
2254
2255         for (i=0; i<3; i++)
2256                 tavl_free( qb->scopes[i], NULL );
2257         ch_free( qb );
2258 }
2259
2260 static int
2261 pcache_db_close(
2262         BackendDB *be
2263 )
2264 {
2265         slap_overinst *on = (slap_overinst *)be->bd_info;
2266         cache_manager *cm = on->on_bi.bi_private;
2267         query_manager *qm = cm->qm;
2268         QueryTemplate *tm;
2269         int i, rc = 0;
2270
2271         /* cleanup stuff inherited from the original database... */
2272         cm->db.be_limits = NULL;
2273         cm->db.be_acl = NULL;
2274
2275         if ( cm->db.bd_info->bi_db_close ) {
2276                 rc = cm->db.bd_info->bi_db_close( &cm->db );
2277         }
2278         while ( (tm = qm->templates) != NULL ) {
2279                 CachedQuery *qc, *qn;
2280                 qm->templates = tm->qmnext;
2281                 for ( qc = tm->query; qc; qc = qn ) {
2282                         qn = qc->next;
2283                         free_query( qc );
2284                 }
2285                 avl_free( tm->qbase, pcache_free_qbase );
2286                 free( tm->querystr.bv_val );
2287                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
2288                 free( tm->t_attrs.attrs );
2289                 free( tm );
2290         }
2291
2292         for ( i=0; i<cm->numattrsets; i++ ) {
2293                 free( qm->attr_sets[i].attrs );
2294         }
2295         free( qm->attr_sets );
2296         qm->attr_sets = NULL;
2297
2298         return rc;
2299 }
2300
2301 static int
2302 pcache_db_destroy(
2303         BackendDB *be
2304 )
2305 {
2306         slap_overinst *on = (slap_overinst *)be->bd_info;
2307         cache_manager *cm = on->on_bi.bi_private;
2308         query_manager *qm = cm->qm;
2309
2310         if ( cm->db.be_private != NULL ) {
2311                 backend_stopdown_one( &cm->db );
2312         }
2313
2314         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2315         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2316         free( qm );
2317         free( cm );
2318
2319         return 0;
2320 }
2321
2322 static slap_overinst pcache;
2323
2324 static char *obsolete_names[] = {
2325         "proxycache",
2326         NULL
2327 };
2328
2329 int pcache_initialize()
2330 {
2331         int code;
2332         struct berval debugbv = BER_BVC("pcache");
2333
2334         if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2335                 return code;
2336
2337         code = register_at( queryid_schema, &ad_queryid, 0 );
2338         if ( code ) {
2339                 Debug( LDAP_DEBUG_ANY,
2340                         "pcache_initialize: register_at failed\n", 0, 0, 0 );
2341                 return code;
2342         }
2343
2344         pcache.on_bi.bi_type = "pcache";
2345         pcache.on_bi.bi_obsolete_names = obsolete_names;
2346         pcache.on_bi.bi_db_init = pcache_db_init;
2347         pcache.on_bi.bi_db_config = pcache_db_config;
2348         pcache.on_bi.bi_db_open = pcache_db_open;
2349         pcache.on_bi.bi_db_close = pcache_db_close;
2350         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2351
2352         pcache.on_bi.bi_op_search = pcache_op_search;
2353
2354         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2355
2356         pcache.on_bi.bi_cf_ocs = pcocs;
2357
2358         code = config_register_schema( pccfg, pcocs );
2359         if ( code ) return code;
2360
2361         return overlay_register( &pcache );
2362 }
2363
2364 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2365 int init_module(int argc, char *argv[]) {
2366         return pcache_initialize();
2367 }
2368 #endif
2369
2370 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */