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