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