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