]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
0ffb615d09860499eaaf60bf4b52bdb0e9e9be32
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003 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 = { 0, NULL };
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 berval*          uuid;
807         int                     deleted;
808 };
809
810 static int
811 remove_func (
812         Operation       *op,
813         SlapReply       *rs
814 )
815 {
816         struct query_info       *info = op->o_callback->sc_private;
817         int                     count = 0;
818         Modifications           mod;
819         struct berval vals[2];
820
821         Attribute               *attr;
822         Operation               op_tmp = *op;
823
824         SlapReply               sreply = {REP_RESULT};
825
826         if (rs->sr_type == REP_RESULT)
827                 return 0;
828
829         for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
830                 if (attr->a_desc == ad_queryid) {
831                         for (count=0; attr->a_vals[count].bv_val; count++)
832                                 ;
833                         break;
834                 }
835         }
836
837         if (count == 0) {
838                 return 0;
839         }
840         if (count == 1) {
841 #ifdef NEW_LOGGING
842                 LDAP_LOG( BACK_META, DETAIL1,
843                                 "DELETING ENTRY TEMPLATE=%s\n",
844                                 attr->a_vals[0].bv_val, 0, 0 );
845 #else
846                 Debug( LDAP_DEBUG_ANY, "DELETING ENTRY TEMPLATE=%s\n",
847                                 attr->a_vals[0].bv_val, 0, 0 );
848 #endif
849
850                 op_tmp.o_req_dn = rs->sr_entry->e_name;
851                 op_tmp.o_req_ndn = rs->sr_entry->e_nname;
852
853                 if (op->o_bd->be_delete(&op_tmp, rs) == LDAP_SUCCESS) {
854                         info->deleted++;
855                 }
856                 return 0;
857         }
858
859         vals[0] = *info->uuid;
860         vals[1].bv_val = NULL;
861         vals[1].bv_len = 0;
862         mod.sml_op = LDAP_MOD_DELETE;
863         mod.sml_desc = ad_queryid;
864         mod.sml_type = ad_queryid->ad_cname;
865         mod.sml_bvalues = vals;
866         mod.sml_next = NULL;
867 #ifdef NEW_LOGGING
868         LDAP_LOG( BACK_META, DETAIL1,
869                         "REMOVING TEMP ATTR : TEMPLATE=%s\n",
870                         attr->a_vals[0].bv_val, 0, 0 );
871 #else
872         Debug( LDAP_DEBUG_ANY, "REMOVING TEMP ATTR : TEMPLATE=%s\n",
873                         attr->a_vals[0].bv_val, 0, 0 );
874 #endif
875
876         op_tmp.o_req_dn = rs->sr_entry->e_name;
877         op_tmp.o_req_ndn = rs->sr_entry->e_nname;
878         op_tmp.orm_modlist = &mod;
879
880         op->o_bd->be_modify( &op_tmp, &sreply );
881
882         return 0;
883 }
884
885 static int
886 remove_query_data (
887         Operation       *op,
888         SlapReply       *rs,
889         struct berval* query_uuid)
890 {
891         struct query_info       info;
892         char                    filter_str[64];
893         Filter                  filter = {LDAP_FILTER_EQUALITY};
894         SlapReply               sreply = {REP_RESULT};
895         slap_callback cb = { NULL, remove_func, NULL, NULL };
896
897         sreply.sr_entry = NULL;
898         sreply.sr_nentries = 0;
899         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
900                 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
901         filter.f_av_desc = ad_queryid;
902         filter.f_av_value = *query_uuid;
903         info.uuid = query_uuid;
904         info.deleted = 0;
905         cb.sc_private = &info;
906
907         op->o_tag = LDAP_REQ_SEARCH;
908         op->o_protocol = LDAP_VERSION3;
909         op->o_callback = &cb;
910         op->o_time = slap_get_time();
911         op->o_do_not_cache = 1;
912
913         op->o_req_dn = op->o_bd->be_suffix[0];
914         op->o_req_ndn = op->o_bd->be_nsuffix[0];
915         op->ors_scope = LDAP_SCOPE_SUBTREE;
916         op->ors_deref = LDAP_DEREF_NEVER;
917         op->ors_slimit = 0;
918         op->ors_tlimit = 0;
919         op->ors_filter = &filter;
920         op->ors_filterstr.bv_val = filter_str;
921         op->ors_filterstr.bv_len = strlen(filter_str);
922         op->ors_attrs = NULL;
923         op->ors_attrsonly = 0;
924
925         op->o_bd->be_search( op, &sreply );
926
927         return info.deleted;
928 }
929
930 static int
931 get_attr_set(
932         AttributeName* attrs,
933         query_manager* qm,
934         int num
935 );
936
937 static int
938 attrscmp(
939         AttributeName* attrs_in,
940         AttributeName* attrs
941 );
942
943 static int
944 is_temp_answerable(
945         int attr_set,
946         struct berval* tempstr,
947         query_manager* qm,
948         int template_id )
949 {
950         QueryTemplate *qt = qm->templates + template_id;
951
952         if (attr_set != qt->attr_set_index) {
953                 int* id_array = qm->attr_sets[attr_set].ID_array;
954
955                 while (*id_array != -1) {
956                         if (*id_array == qt->attr_set_index)
957                                 break;
958                         id_array++;
959                 }
960                 if (*id_array == -1)
961                         return 0;
962         }
963         return (qt->querystr.bv_len == tempstr->bv_len &&
964                 strcasecmp(qt->querystr.bv_val, tempstr->bv_val) == 0);
965 }
966
967 static int
968 filter2template(
969         Filter                  *f,
970         struct                  berval *fstr,
971         AttributeName**         filter_attrs,
972         int*                    filter_cnt )
973 {
974         AttributeDescription *ad;
975
976         switch ( f->f_choice ) {
977         case LDAP_FILTER_EQUALITY:
978                 ad = f->f_av_desc;
979                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
980                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
981                 break;
982
983         case LDAP_FILTER_GE:
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_LE:
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_APPROX:
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_SUBSTRINGS:
1002                 ad = f->f_sub_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_PRESENT:
1008                 ad = f->f_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_AND:
1014         case LDAP_FILTER_OR:
1015         case LDAP_FILTER_NOT: {
1016                 int rc = 0;
1017                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1018                         f->f_choice == LDAP_FILTER_AND ? '&' :
1019                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1020                 fstr->bv_len += sizeof("(%") - 1;
1021
1022                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1023                         rc = filter2template( f, fstr, filter_attrs, filter_cnt );
1024                         if ( rc ) break;
1025                 }
1026                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1027                 fstr->bv_len += sizeof(")") - 1;
1028
1029                 return rc;
1030                 }
1031
1032         default:
1033                 strcpy( fstr->bv_val, "(?=?)" );
1034                 fstr->bv_len += sizeof("(?=?)")-1;
1035                 return -1;
1036         }
1037
1038         *filter_attrs = (AttributeName *)ch_realloc(*filter_attrs,
1039                                 (*filter_cnt + 2)*sizeof(AttributeName));
1040
1041         (*filter_attrs)[*filter_cnt].an_desc = ad;
1042         (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1043         (*filter_attrs)[*filter_cnt+1].an_name.bv_val = NULL;
1044         (*filter_attrs)[*filter_cnt+1].an_name.bv_len = 0;
1045         (*filter_cnt)++;
1046         return 0;
1047 }
1048
1049 struct search_info {
1050         slap_overinst *on;
1051         Query query;
1052         int template_id;
1053         int max;
1054         int over;
1055         int count;
1056         Entry *head, *tail;
1057 };
1058
1059 static int
1060 cache_entries(
1061         Operation       *op,
1062         SlapReply       *rs,
1063         struct berval *query_uuid)
1064 {
1065         struct search_info *si = op->o_callback->sc_private;
1066         slap_overinst *on = si->on;
1067         cache_manager *cm = on->on_bi.bi_private;
1068         query_manager*          qm = cm->qm;
1069         int             i;
1070         int             return_val;
1071         Entry           *e;
1072         struct berval   crp_uuid;
1073         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1074         Operation op_tmp = *op;
1075
1076         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1077         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1078
1079         op_tmp.o_bd = &cm->db;
1080         op_tmp.o_dn = cm->db.be_rootdn;
1081         op_tmp.o_ndn = cm->db.be_rootndn;
1082
1083 #ifdef NEW_LOGGING
1084         LDAP_LOG( BACK_META, DETAIL1, "UUID for query being added = %s\n",
1085                         uuidbuf, 0, 0 );
1086 #else /* !NEW_LOGGING */
1087         Debug( LDAP_DEBUG_ANY, "UUID for query being added = %s\n",
1088                         uuidbuf, 0, 0 );
1089 #endif /* !NEW_LOGGING */
1090
1091         for ( e=si->head; e; e=si->head ) {
1092                 si->head = e->e_private;
1093                 e->e_private = NULL;
1094 #ifdef NEW_LOGGING
1095                 LDAP_LOG( BACK_META, DETAIL2, "LOCKING REMOVE MUTEX\n",
1096                                 0, 0, 0 );
1097 #else /* !NEW_LOGGING */
1098                 Debug( LDAP_DEBUG_NONE, "LOCKING REMOVE MUTEX\n", 0, 0, 0 );
1099 #endif /* !NEW_LOGGING */
1100                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1101 #ifdef NEW_LOGGING
1102                 LDAP_LOG( BACK_META, DETAIL2, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1103 #else /* !NEW_LOGGING */
1104                 Debug( LDAP_DEBUG_NONE, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1105 #endif /* !NEW_LOGGING */
1106                 while ( cm->cur_entries > (cm->max_entries) ) {
1107                                 qm->crfunc(qm, &crp_uuid);
1108                                 if (crp_uuid.bv_val) {
1109 #ifdef NEW_LOGGING
1110                                         LDAP_LOG( BACK_META, DETAIL1,
1111                                                 "Removing query UUID %s\n",
1112                                                 crp_uuid.bv_val, 0, 0 );
1113 #else /* !NEW_LOGGING */
1114                                         Debug( LDAP_DEBUG_ANY,
1115                                                 "Removing query UUID %s\n",
1116                                                 crp_uuid.bv_val, 0, 0 );
1117 #endif /* !NEW_LOGGING */
1118                                         return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1119 #ifdef NEW_LOGGING
1120                                         LDAP_LOG( BACK_META, DETAIL1,
1121                                                 "QUERY REMOVED, SIZE=%d\n",
1122                                                 return_val, 0, 0);
1123 #else /* !NEW_LOGGING */
1124                                         Debug( LDAP_DEBUG_ANY,
1125                                                 "QUERY REMOVED, SIZE=%d\n",
1126                                                 return_val, 0, 0);
1127 #endif /* !NEW_LOGGING */
1128                                         ldap_pvt_thread_mutex_lock(
1129                                                         &cm->cache_mutex );
1130                                         cm->cur_entries -= return_val;
1131                                         cm->num_cached_queries--;
1132 #ifdef NEW_LOGGING
1133                                         LDAP_LOG( BACK_META, DETAIL1,
1134                                                 "STORED QUERIES = %lu\n",
1135                                                 cm->num_cached_queries, 0, 0 );
1136 #else /* !NEW_LOGGING */
1137                                         Debug( LDAP_DEBUG_ANY,
1138                                                 "STORED QUERIES = %lu\n",
1139                                                 cm->num_cached_queries, 0, 0 );
1140 #endif /* !NEW_LOGGING */
1141                                         ldap_pvt_thread_mutex_unlock(
1142                                                         &cm->cache_mutex );
1143 #ifdef NEW_LOGGING
1144                                         LDAP_LOG( BACK_META, DETAIL1,
1145                                                 "QUERY REMOVED, CACHE ="
1146                                                 "%d entries\n",
1147                                                 cm->cur_entries, 0, 0 );
1148 #else /* !NEW_LOGGING */
1149                                         Debug( LDAP_DEBUG_ANY,
1150                                                 "QUERY REMOVED, CACHE ="
1151                                                 "%d entries\n",
1152                                                 cm->cur_entries, 0, 0 );
1153 #endif /* !NEW_LOGGING */
1154                                 }
1155                 }
1156
1157                 return_val = merge_entry(&op_tmp, e, query_uuid);
1158                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1159                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1160                 cm->cur_entries += return_val;
1161 #ifdef NEW_LOGGING
1162                 LDAP_LOG( BACK_META, DETAIL1,
1163                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1164                         cm->cur_entries, 0, 0 );
1165 #else /* !NEW_LOGGING */
1166                 Debug( LDAP_DEBUG_ANY,
1167                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1168                         cm->cur_entries, 0, 0 );
1169 #endif /* !NEW_LOGGING */
1170                 return_val = 0;
1171                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1172         }
1173         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1174         cm->num_cached_queries++;
1175 #ifdef NEW_LOGGING
1176         LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1177                         cm->num_cached_queries, 0, 0 );
1178 #else /* !NEW_LOGGING */
1179         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1180                         cm->num_cached_queries, 0, 0 );
1181 #endif /* !NEW_LOGGING */
1182         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1183
1184         return return_val;
1185 }
1186
1187 static int
1188 proxy_cache_response(
1189         Operation       *op,
1190         SlapReply       *rs )
1191 {
1192         struct search_info *si = op->o_callback->sc_private;
1193         slap_overinst *on = si->on;
1194         cache_manager *cm = on->on_bi.bi_private;
1195         query_manager*          qm = cm->qm;
1196         struct berval uuid;
1197
1198         if ( rs->sr_type == REP_SEARCH ) {
1199                 Entry *e;
1200                 /* If we haven't exceeded the limit for this query,
1201                  * build a chain of answers to store. If we hit the
1202                  * limit, empty the chain and ignore the rest.
1203                  */
1204                 if ( !si->over ) {
1205                         if ( si->count < si->max ) {
1206                                 si->count++;
1207                                 e = entry_dup( rs->sr_entry );
1208                                 if ( !si->head ) si->head = e;
1209                                 if ( si->tail ) si->tail->e_private = e;
1210                                 si->tail = e;
1211                         } else {
1212                                 si->over = 1;
1213                                 si->count = 0;
1214                                 for (;si->head; si->head=e) {
1215                                         e = si->head->e_private;
1216                                         si->head->e_private = NULL;
1217                                         entry_free(si->head);
1218                                 }
1219                                 si->tail = NULL;
1220                         }
1221                 }
1222         } else if ( rs->sr_type == REP_RESULT && !si->over ) {
1223                 if ( cache_entries( op, rs, &uuid ) == 0) {
1224                         qm->addfunc(qm, &si->query, si->template_id, &uuid);
1225                         /* If the consistency checker suspended itself,
1226                          * wake it back up
1227                          */
1228                         if ( cm->cc_paused ) {
1229                                 ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
1230                                 if ( cm->cc_paused ) {
1231                                         cm->cc_paused = 0;
1232                                         ldap_pvt_runqueue_resched( &syncrepl_rq, cm->cc_arg, 0 );
1233                                 }
1234                                 ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
1235                         }
1236                 }
1237         }
1238         return SLAP_CB_CONTINUE;
1239 }
1240
1241 static void
1242 add_filter_attrs(
1243         Operation *op,
1244         AttributeName** new_attrs,
1245         AttributeName* attrs,
1246         AttributeName* filter_attrs )
1247 {
1248         int alluser = 0;
1249         int allop = 0;
1250         int i;
1251         int count;
1252
1253         /* duplicate attrs */
1254         if (attrs == NULL) {
1255                 count = 1;
1256         } else {
1257                 for (count=0; attrs[count].an_name.bv_val; count++)
1258                         ;
1259         }
1260         *new_attrs = (AttributeName*)(op->o_tmpalloc((count+1)*
1261                 sizeof(AttributeName), op->o_tmpmemctx));
1262         if (attrs == NULL) {
1263                 (*new_attrs)[0].an_name.bv_val = "*";
1264                 (*new_attrs)[0].an_name.bv_len = 1;
1265                 (*new_attrs)[1].an_name.bv_val = NULL;
1266                 (*new_attrs)[1].an_name.bv_len = 0;
1267                 alluser = 1;
1268                 allop = 0;
1269         } else {
1270                 for (i=0; i<count; i++) {
1271                         (*new_attrs)[i].an_name = attrs[i].an_name;
1272                         (*new_attrs)[i].an_desc = attrs[i].an_desc;
1273                 }
1274                 (*new_attrs)[count].an_name.bv_val = NULL;
1275                 (*new_attrs)[count].an_name.bv_len = 0;
1276                 alluser = an_find(*new_attrs, &AllUser);
1277                 allop = an_find(*new_attrs, &AllOper);
1278         }
1279
1280         for ( i=0; filter_attrs[i].an_name.bv_val; i++ ) {
1281                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1282                         continue;
1283                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1284                         if (allop)
1285                                 continue;
1286                 } else if (alluser)
1287                         continue;
1288                 *new_attrs = (AttributeName*)(op->o_tmprealloc(*new_attrs,
1289                                         (count+2)*sizeof(AttributeName), op->o_tmpmemctx));
1290                 (*new_attrs)[count].an_name = filter_attrs[i].an_name;
1291                 (*new_attrs)[count].an_desc = filter_attrs[i].an_desc;
1292                 count++;
1293                 (*new_attrs)[count].an_name.bv_val = NULL;
1294                 (*new_attrs)[count].an_name.bv_len = 0;
1295         }
1296 }
1297
1298 static int
1299 proxy_cache_search(
1300         Operation       *op,
1301         SlapReply       *rs )
1302 {
1303         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1304         cache_manager *cm = on->on_bi.bi_private;
1305         query_manager*          qm = cm->qm;
1306
1307         int count;
1308
1309         int i = -1;
1310
1311         AttributeName   *filter_attrs = NULL;
1312         AttributeName   *new_attrs = NULL;
1313
1314         Query           query;
1315
1316         int             attr_set = -1;
1317         int             template_id = -1;
1318         int             answerable = 0;
1319         int             cacheable = 0;
1320         int             fattr_cnt=0;
1321         int             oc_attr_absent = 1;
1322
1323         struct berval tempstr;
1324
1325         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1326         tempstr.bv_len = 0;
1327         if (filter2template(op->ors_filter, &tempstr, &filter_attrs, &fattr_cnt)) {
1328                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1329                 return SLAP_CB_CONTINUE;
1330         }
1331
1332 #ifdef NEW_LOGGING
1333         LDAP_LOG( BACK_META, DETAIL1, "query template of incoming query = %s\n",
1334                                         tempstr.bv_val, 0, 0 );
1335 #else /* !NEW_LOGGING */
1336         Debug( LDAP_DEBUG_ANY, "query template of incoming query = %s\n",
1337                                         tempstr.bv_val, 0, 0 );
1338 #endif /* !NEW_LOGGING */
1339
1340         /* find attr set */
1341         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1342
1343         query.filter = op->ors_filter;
1344         query.attrs = op->ors_attrs;
1345         query.base = op->o_req_ndn;
1346         query.scope = op->ors_scope;
1347
1348         /* check for query containment */
1349         if (attr_set > -1) {
1350                 for (i=0; i<cm->numtemplates; i++) {
1351                         /* find if template i can potentially answer tempstr */
1352                         if (!is_temp_answerable(attr_set, &tempstr, qm, i))
1353                                 continue;
1354                         if (attr_set == qm->templates[i].attr_set_index) {
1355                                 cacheable = 1;
1356                                 template_id = i;
1357                         }
1358 #ifdef NEW_LOGGING
1359                         LDAP_LOG( BACK_META, DETAIL2,
1360                                         "Entering QC, querystr = %s\n",
1361                                         op->ors_filterstr.bv_val, 0, 0 );
1362 #else /* !NEW_LOGGING */
1363                         Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1364                                         op->ors_filterstr.bv_val, 0, 0 );
1365 #endif /* !NEW_LOGGING */
1366                         answerable = (*(qm->qcfunc))(qm, &query, i);
1367
1368                         if (answerable)
1369                                 break;
1370                 }
1371         }
1372         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1373
1374         if (answerable) {
1375                 BackendDB *be = op->o_bd;
1376 #ifdef NEW_LOGGING
1377                 LDAP_LOG( BACK_META, DETAIL1, "QUERY ANSWERABLE\n", 0, 0, 0 );
1378 #else /* !NEW_LOGGING */
1379                 Debug( LDAP_DEBUG_ANY, "QUERY ANSWERABLE\n", 0, 0, 0 );
1380 #endif /* !NEW_LOGGING */
1381                 free(filter_attrs);
1382                 ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock);
1383                 op->o_bd = &cm->db;
1384                 i = cm->db.bd_info->bi_op_search( op, rs );
1385                 op->o_bd = be;
1386                 return i;
1387         }
1388
1389 #ifdef NEW_LOGGING
1390         LDAP_LOG( BACK_META, DETAIL1, "QUERY NOT ANSWERABLE\n",
1391                                 0, 0, 0 );
1392 #else /* !NEW_LOGGING */
1393         Debug( LDAP_DEBUG_ANY, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1394 #endif /* !NEW_LOGGING */
1395
1396         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1397         if (cm->num_cached_queries >= cm->max_queries) {
1398                 cacheable = 0;
1399         }
1400         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1401
1402         if (cacheable) {
1403                 slap_callback *cb;
1404                 struct search_info *si;
1405 #ifdef NEW_LOGGING
1406                 LDAP_LOG( BACK_META, DETAIL1,
1407                         "QUERY CACHEABLE\n", 0, 0, 0 );
1408 #else /* !NEW_LOGGING */
1409                 Debug( LDAP_DEBUG_ANY, "QUERY CACHEABLE\n", 0, 0, 0 );
1410 #endif /* !NEW_LOGGING */
1411                 query.filter = str2filter(op->ors_filterstr.bv_val);
1412                 if (op->ors_attrs) {
1413                         for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ ) {
1414                                 if ( op->ors_attrs[count].an_desc == slap_schema.si_ad_objectClass )
1415                                         oc_attr_absent = 0;
1416                         }
1417                         query.attrs = (AttributeName*)ch_malloc( ( count + 1 + oc_attr_absent )
1418                                                                         *sizeof(AttributeName));
1419                         for ( count=0; op->ors_attrs[ count ].an_name.bv_val; count++ ) {
1420                                 ber_dupbv( &query.attrs[count].an_name, &op->ors_attrs[count].an_name );
1421                                 query.attrs[count].an_desc = op->ors_attrs[count].an_desc;
1422                         }
1423                         if ( oc_attr_absent ) {
1424                                 query.attrs[ count ].an_desc = slap_schema.si_ad_objectClass;
1425                                 ber_dupbv( &query.attrs[count].an_name,
1426                                         &slap_schema.si_ad_objectClass->ad_cname );
1427                                 count++;
1428                         }
1429                         query.attrs[ count ].an_name.bv_val = NULL;
1430                         query.attrs[ count ].an_name.bv_len = 0;
1431                 }
1432                 op->o_tmpfree(op->ors_attrs, op->o_tmpmemctx);
1433                 add_filter_attrs(op, &op->ors_attrs, query.attrs, filter_attrs);
1434                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1435                 cb->sc_next = op->o_callback;
1436                 cb->sc_response = proxy_cache_response;
1437                 cb->sc_cleanup = NULL;
1438                 cb->sc_private = (cb+1);
1439                 si = cb->sc_private;
1440                 si->on = on;
1441                 si->query = query;
1442                 si->template_id = template_id;
1443                 si->max = cm->num_entries_limit ;
1444                 si->over = 0;
1445                 si->count = 0;
1446                 si->head = NULL;
1447                 si->tail = NULL;
1448                 op->o_callback = cb;
1449         } else {
1450 #ifdef NEW_LOGGING
1451                 LDAP_LOG( BACK_META, DETAIL1,
1452                                         "QUERY NOT CACHEABLE\n",
1453                                         0, 0, 0);
1454 #else /* !NEW_LOGGING */
1455                 Debug( LDAP_DEBUG_ANY, "QUERY NOT CACHEABLE\n",
1456                                         0, 0, 0);
1457 #endif /* !NEW_LOGGING */
1458         }
1459
1460         free(filter_attrs);
1461
1462         return SLAP_CB_CONTINUE;
1463 }
1464
1465 static int
1466 attrscmp(
1467         AttributeName* attrs_in,
1468         AttributeName* attrs)
1469 {
1470         int i, count1, count2;
1471         if ( attrs_in == NULL ) {
1472                 return (attrs ? 0 : 1);
1473         }
1474         if ( attrs == NULL )
1475                 return 0;
1476
1477         for ( count1=0;
1478               attrs_in && attrs_in[count1].an_name.bv_val != NULL;
1479               count1++ )
1480                 ;
1481         for ( count2=0;
1482               attrs && attrs[count2].an_name.bv_val != NULL;
1483               count2++)
1484                 ;
1485         if ( count1 != count2 )
1486                 return 0;
1487
1488         for ( i=0; i<count1; i++ ) {
1489                 if ( !an_find(attrs, &attrs_in[i].an_name ))
1490                         return 0;
1491         }
1492         return 1;
1493 }
1494
1495 static int
1496 get_attr_set(
1497         AttributeName* attrs,
1498         query_manager* qm,
1499         int num )
1500 {
1501         int i;
1502         for (i=0; i<num; i++) {
1503                 if (attrscmp(attrs, qm->attr_sets[i].attrs))
1504                         return i;
1505         }
1506         return -1;
1507 }
1508
1509 static void*
1510 consistency_check(
1511         void *ctx,
1512         void *arg )
1513 {
1514         struct re_s *rtask = arg;
1515         slap_overinst *on = rtask->arg;
1516         cache_manager *cm = on->on_bi.bi_private;
1517         query_manager *qm = cm->qm;
1518         Operation op = {0};
1519
1520         SlapReply rs = {REP_RESULT};
1521         CachedQuery* query, *query_prev;
1522         int i, return_val, pause = 1;
1523         QueryTemplate* templ;
1524
1525         op.o_bd = &cm->db;
1526         op.o_dn = cm->db.be_rootdn;
1527         op.o_ndn = cm->db.be_rootndn;
1528         op.o_threadctx = ctx;
1529
1530         op.o_tmpmemctx = sl_mem_create( SLMALLOC_SLAB_SIZE, ctx );
1531         op.o_tmpmfuncs = &sl_mfuncs;
1532
1533         cm->cc_arg = arg;
1534
1535         for (i=0; qm->templates[i].querystr.bv_val; i++) {
1536                 templ = qm->templates + i;
1537                 query = templ->query_last;
1538                 if ( query ) pause = 0;
1539                 op.o_time = slap_get_time();
1540                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1541                 while (query && (query->expiry_time < op.o_time)) {
1542                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1543                         remove_query(qm, query);
1544                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1545 #ifdef NEW_LOGGING
1546                         LDAP_LOG( BACK_META, DETAIL1, "Lock CR index = %d\n",
1547                                         i, 0, 0 );
1548 #else /* !NEW_LOGGING */
1549                         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n",
1550                                         i, 0, 0 );
1551 #endif /* !NEW_LOGGING */
1552                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1553                         remove_from_template(query, templ);
1554 #ifdef NEW_LOGGING
1555                         LDAP_LOG( BACK_META, DETAIL1,
1556                                         "TEMPLATE %d QUERIES-- %d\n",
1557                                         i, templ->no_of_queries, 0 );
1558 #else /* !NEW_LOGGING */
1559                         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
1560                                         i, templ->no_of_queries, 0 );
1561 #endif /* !NEW_LOGGING */
1562 #ifdef NEW_LOGGING
1563                         LDAP_LOG( BACK_META, DETAIL1, "Unlock CR index = %d\n",
1564                                         i, 0, 0 );
1565 #else /* !NEW_LOGGING */
1566                         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n",
1567                                         i, 0, 0 );
1568 #endif /* !NEW_LOGGING */
1569                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1570                         return_val = remove_query_data(&op, &rs, &query->q_uuid);
1571 #ifdef NEW_LOGGING
1572                         LDAP_LOG( BACK_META, DETAIL1,
1573                                         "STALE QUERY REMOVED, SIZE=%d\n",
1574                                         return_val, 0, 0 );
1575 #else /* !NEW_LOGGING */
1576                         Debug( LDAP_DEBUG_ANY, "STALE QUERY REMOVED, SIZE=%d\n",
1577                                                 return_val, 0, 0 );
1578 #endif /* !NEW_LOGGING */
1579                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1580                         cm->cur_entries -= return_val;
1581                         cm->num_cached_queries--;
1582 #ifdef NEW_LOGGING
1583                         LDAP_LOG( BACK_META, DETAIL1, "STORED QUERIES = %lu\n",
1584                                         cm->num_cached_queries, 0, 0 );
1585 #else /* !NEW_LOGGING */
1586                         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1587                                         cm->num_cached_queries, 0, 0 );
1588 #endif /* !NEW_LOGGING */
1589                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1590 #ifdef NEW_LOGGING
1591                         LDAP_LOG( BACK_META, DETAIL1,
1592                                 "STALE QUERY REMOVED, CACHE ="
1593                                 "%d entries\n",
1594                                 cm->cur_entries, 0, 0 );
1595 #else /* !NEW_LOGGING */
1596                         Debug( LDAP_DEBUG_ANY,
1597                                 "STALE QUERY REMOVED, CACHE ="
1598                                 "%d entries\n",
1599                                 cm->cur_entries, 0, 0 );
1600 #endif /* !NEW_LOGGING */
1601                         query_prev = query;
1602                         query = query->prev;
1603                         free_query(query_prev);
1604                 }
1605                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1606         }
1607         /* If there were no queries, defer processing for a while */
1608         if ( pause ) {
1609                 ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
1610                 cm->cc_paused = 1;
1611                 if ( ldap_pvt_runqueue_isrunning( &syncrepl_rq, rtask )) {
1612                         ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
1613                 }
1614                 ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, 1 );
1615                 ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
1616         }
1617         return NULL;
1618 }
1619
1620
1621 #define MAX_ATTR_SETS 500
1622 static void find_supersets( struct attr_set* attr_sets, int numsets );
1623 static int compare_sets( struct attr_set* setA, int, int );
1624
1625 static int
1626 proxy_cache_config(
1627         BackendDB       *be,
1628         const char      *fname,
1629         int             lineno,
1630         int             argc,
1631         char            **argv
1632 )
1633 {
1634         slap_overinst *on = (slap_overinst *)be->bd_info;
1635         cache_manager*  cm = on->on_bi.bi_private;
1636         query_manager*  qm = cm->qm;
1637         QueryTemplate*  temp;
1638         AttributeName*  attr_name;
1639         AttributeName*  attrarray;
1640         const char*     text=NULL;
1641
1642         int             index, i;
1643         int             num;
1644
1645         if ( strcasecmp( argv[0], "proxycache" ) == 0 ) {
1646                 if ( argc < 6 ) {
1647                         fprintf( stderr, "%s: line %d: missing arguments in \"proxycache"
1648                                 " <backend> <max_entries> <numattrsets> <entry limit> "
1649                                 "<cycle_time>\"\n", fname, lineno );
1650                         return( 1 );
1651                 }
1652
1653                 cm->db.bd_info = backend_info( argv[1] );
1654                 if ( !cm->db.bd_info ) {
1655                         fprintf( stderr, "%s: line %d: backend %s unknown\n",
1656                                 fname, lineno, argv[1] );
1657                         return( 1 );
1658                 }
1659                 if ( cm->db.bd_info->bi_db_init( &cm->db ) ) return( 1 );
1660
1661                 cm->max_entries = atoi( argv[2] );
1662
1663                 cm->numattrsets = atoi( argv[3] );
1664                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1665                         fprintf( stderr, "%s: line %d: numattrsets must be <= %d\n",
1666                                 fname, lineno, MAX_ATTR_SETS );
1667                         return( 1 );
1668                 }
1669
1670                 cm->num_entries_limit = atoi( argv[4] );
1671                 cm->cc_period = atoi( argv[5] );
1672 #ifdef NEW_LOGGING
1673                 LDAP_LOG( BACK_META, DETAIL1,
1674                                 "Total # of attribute sets to be cached = %d\n",
1675                                 cm->numattrsets, 0, 0 );
1676 #else
1677                 Debug( LDAP_DEBUG_ANY,
1678                                 "Total # of attribute sets to be cached = %d\n",
1679                                 cm->numattrsets, 0, 0 );
1680 #endif
1681                 qm->attr_sets = ( struct attr_set * )ch_malloc( cm->numattrsets *
1682                                                 sizeof( struct attr_set ));
1683                 for ( i = 0; i < cm->numattrsets; i++ ) {
1684                         qm->attr_sets[i].attrs = NULL;
1685                 }
1686
1687         } else if ( strcasecmp( argv[0], "proxyattrset" ) == 0 ) {
1688                 if ( argc < 3 ) {
1689                         fprintf( stderr, "%s: line %d: missing arguments in \"proxyattrset "
1690                                 "<index> <attributes>\"\n", fname, lineno );
1691                         return( 1 );
1692                 }
1693 #ifdef NEW_LOGGING
1694                 LDAP_LOG( BACK_META, DETAIL1, "Attribute Set # %d\n",
1695                                 atoi( argv[1] ), 0, 0 );
1696 #else
1697                 Debug( LDAP_DEBUG_ANY, "Attribute Set # %d\n",
1698                                 atoi( argv[1] ), 0, 0 );
1699 #endif
1700                 if (atoi(argv[1]) >= cm->numattrsets) {
1701                         fprintf( stderr, "%s; line %d index out of bounds \n",
1702                                         fname, lineno );
1703                         return 1;
1704                 }
1705                 index = atoi( argv[1] );
1706                 if ( argv[2] && strcmp( argv[2], "*" ) ) {
1707                         qm->attr_sets[index].count = argc - 2;
1708                         qm->attr_sets[index].attrs = (AttributeName*)ch_malloc(
1709                                                 (argc-1) * sizeof( AttributeName ));
1710                         attr_name = qm->attr_sets[index].attrs;
1711                         for ( i = 2; i < argc; i++ ) {
1712 #ifdef NEW_LOGGING
1713                                 LDAP_LOG( BACK_META, DETAIL1, "\t %s\n",
1714                                                 argv[i], 0, 0 );
1715 #else
1716                                 Debug( LDAP_DEBUG_ANY, "\t %s\n",
1717                                                 argv[i], 0, 0 );
1718 #endif
1719                                 ber_str2bv( argv[i], 0, 1,
1720                                                 &attr_name->an_name);
1721                                 attr_name->an_desc = NULL;
1722                                 slap_bv2ad( &attr_name->an_name,
1723                                                 &attr_name->an_desc, &text );
1724                                 attr_name++;
1725                                 attr_name->an_name.bv_val = NULL;
1726                                 attr_name->an_name.bv_len = 0;
1727                         }
1728                 }
1729         } else if ( strcasecmp( argv[0], "proxytemplate" ) == 0 ) {
1730                 if ( argc != 4 ) {
1731                         fprintf( stderr, "%s: line %d: missing argument(s) in "
1732                                 "\"proxytemplate <filter> <proj attr set> <TTL>\" line\n",
1733                                 fname, lineno );
1734                         return( 1 );
1735                 }
1736                 if (( i = atoi( argv[2] )) >= cm->numattrsets ) {
1737 #ifdef NEW_LOGGING
1738                         LDAP_LOG( BACK_META, DETAIL1,
1739                                         "%s: line %d, template index invalid\n",
1740                                         fname, lineno, 0 );
1741 #else
1742                         Debug( LDAP_DEBUG_ANY,
1743                                         "%s: line %d, template index invalid\n",
1744                                         fname, lineno, 0 );
1745 #endif
1746                         return 1;
1747                 }
1748                 num = cm->numtemplates;
1749                 if ( num == 0 )
1750                         find_supersets( qm->attr_sets, cm->numattrsets );
1751                 qm->templates = ( QueryTemplate* )ch_realloc( qm->templates,
1752                                 ( num + 2 ) * sizeof( QueryTemplate ));
1753                 temp = qm->templates + num;
1754                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
1755                 temp->query = temp->query_last = NULL;
1756                 temp->ttl = atoi( argv[3] );
1757                 temp->no_of_queries = 0;
1758                 if ( argv[1] == NULL ) {
1759 #ifdef NEW_LOGGING
1760                         LDAP_LOG( BACK_META, DETAIL1,
1761                                         "Templates string not specified "
1762                                         "for template %d\n", num, 0, 0 );
1763 #else
1764                         Debug( LDAP_DEBUG_ANY,
1765                                         "Templates string not specified "
1766                                         "for template %d\n", num, 0, 0 );
1767 #endif
1768                         return 1;
1769                 }
1770                 ber_str2bv( argv[1], 0, 1, &temp->querystr );
1771 #ifdef NEW_LOGGING
1772                 LDAP_LOG( BACK_META, DETAIL1, "Template:\n", 0, 0, 0 );
1773 #else
1774                 Debug( LDAP_DEBUG_ANY, "Template:\n", 0, 0, 0 );
1775 #endif
1776 #ifdef NEW_LOGGING
1777                 LDAP_LOG( BACK_META, DETAIL1, "  query template: %s\n",
1778                                 temp->querystr.bv_val, 0, 0 );
1779 #else
1780                 Debug( LDAP_DEBUG_ANY, "  query template: %s\n",
1781                                 temp->querystr.bv_val, 0, 0 );
1782 #endif
1783                 temp->attr_set_index = i;
1784 #ifdef NEW_LOGGING
1785                 LDAP_LOG( BACK_META, DETAIL1, "  attributes: \n", 0, 0, 0 );
1786 #else
1787                 Debug( LDAP_DEBUG_ANY, "  attributes: \n", 0, 0, 0 );
1788 #endif
1789                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
1790                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
1791 #ifdef NEW_LOGGING
1792                                 LDAP_LOG( BACK_META, DETAIL1, "\t%s\n",
1793                                         attrarray[i].an_name.bv_val, 0, 0 );
1794 #else
1795                                 Debug( LDAP_DEBUG_ANY, "\t%s\n",
1796                                         attrarray[i].an_name.bv_val, 0, 0 );
1797 #endif
1798                 }
1799                 temp++; 
1800                 temp->querystr.bv_val = NULL;
1801                 cm->numtemplates++;
1802         }
1803         /* anything else */
1804         else {
1805                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno, argc, argv );
1806         }
1807         return 0;
1808 }
1809
1810 static int
1811 proxy_cache_init(
1812         BackendDB *be
1813 )
1814 {
1815         slap_overinst *on = (slap_overinst *)be->bd_info;
1816         cache_manager *cm;
1817         query_manager *qm;
1818
1819         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
1820         on->on_bi.bi_private = cm;
1821
1822         qm = (query_manager*)ch_malloc(sizeof(query_manager));
1823
1824         cm->db = *be;
1825         cm->db.be_flags |= SLAP_BFLAG_NO_SCHEMA_CHECK;
1826         cm->db.be_private = NULL;
1827         cm->qm = qm;
1828         cm->numattrsets = 0;
1829         cm->numtemplates = 0; 
1830         cm->num_entries_limit = 5;
1831         cm->num_cached_queries = 0;
1832         cm->max_entries = 0;
1833         cm->cur_entries = 0;
1834         cm->max_queries = 10000;
1835         cm->cc_period = 1000;
1836         cm->cc_paused = 0;
1837
1838         qm->attr_sets = NULL;
1839         qm->templates = NULL;
1840         qm->lru_top = NULL;
1841         qm->lru_bottom = NULL;
1842
1843         qm->qcfunc = query_containment;
1844         qm->crfunc = cache_replacement;
1845         qm->addfunc = add_query;
1846         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
1847
1848         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
1849         ldap_pvt_thread_mutex_init(&cm->remove_mutex);
1850         return 0;
1851 }
1852
1853 static int
1854 proxy_cache_open(
1855         BackendDB *be
1856 )
1857 {
1858         slap_overinst *on = (slap_overinst *)be->bd_info;
1859         cache_manager *cm = on->on_bi.bi_private;
1860         int rc = 0;
1861
1862         if ( cm->db.bd_info->bi_db_open ) {
1863                 rc = cm->db.bd_info->bi_db_open( &cm->db );
1864         }
1865
1866         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
1867         ldap_pvt_runqueue_insert( &syncrepl_rq, cm->cc_period,
1868                 consistency_check, on );
1869         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
1870
1871         return rc;
1872 }
1873
1874 static int
1875 proxy_cache_close(
1876         BackendDB *be
1877 )
1878 {
1879         slap_overinst *on = (slap_overinst *)be->bd_info;
1880         cache_manager *cm = on->on_bi.bi_private;
1881         query_manager *qm = cm->qm;
1882         int i, j, rc = 0;
1883
1884         if ( cm->db.bd_info->bi_db_close ) {
1885                 rc = cm->db.bd_info->bi_db_close( &cm->db );
1886         }
1887         for ( i=0; i<cm->numtemplates; i++ ) {
1888                 CachedQuery *qc, *qn;
1889                 for ( qc = qm->templates[i].query; qc; qc = qn ) {
1890                         qn = qc->next;
1891                         free_query( qc );
1892                 }
1893                 free( qm->templates[i].querystr.bv_val );
1894                 ldap_pvt_thread_rdwr_destroy( &qm->templates[i].t_rwlock );
1895         }
1896         free( qm->templates );
1897         qm->templates = NULL;
1898
1899         for ( i=0; i<cm->numattrsets; i++ ) {
1900                 free( qm->attr_sets[i].ID_array );
1901                 for ( j=0; j<qm->attr_sets[i].count; j++ ) {
1902                         free( qm->attr_sets[i].attrs[j].an_name.bv_val );
1903                 }
1904                 free( qm->attr_sets[i].attrs );
1905         }
1906         free( qm->attr_sets );
1907         qm->attr_sets = NULL;
1908
1909         return rc;
1910 }
1911
1912 static int
1913 proxy_cache_destroy(
1914         BackendDB *be
1915 )
1916 {
1917         slap_overinst *on = (slap_overinst *)be->bd_info;
1918         cache_manager *cm = on->on_bi.bi_private;
1919         query_manager *qm = cm->qm;
1920         int rc = 0;
1921
1922         if ( cm->db.bd_info->bi_db_destroy ) {
1923                 rc = cm->db.bd_info->bi_db_destroy( &cm->db );
1924         }
1925         ldap_pvt_thread_mutex_destroy(&qm->lru_mutex);
1926         ldap_pvt_thread_mutex_destroy(&cm->cache_mutex);
1927         ldap_pvt_thread_mutex_destroy(&cm->remove_mutex);
1928         free( qm );
1929         free( cm );
1930         return rc;
1931 }
1932
1933 static void
1934 find_supersets ( struct attr_set* attr_sets, int numsets )
1935 {
1936         int num[MAX_ATTR_SETS];
1937         int i, j, res;
1938         int* id_array;
1939         for ( i = 0; i < MAX_ATTR_SETS; i++ )
1940                 num[i] = 0;
1941
1942         for ( i = 0; i < numsets; i++ ) {
1943                 attr_sets[i].ID_array = (int*) ch_malloc( sizeof( int ) );
1944                 attr_sets[i].ID_array[0] = -1;
1945         }
1946
1947         for ( i = 0; i < numsets; i++ ) {
1948                 for ( j=i+1; j < numsets; j++ ) {
1949                         res = compare_sets( attr_sets, i, j );
1950                         switch ( res ) {
1951                         case 0:
1952                                 break;
1953                         case 3:
1954                         case 1:
1955                                 id_array = attr_sets[i].ID_array;
1956                                 attr_sets[i].ID_array = (int *) ch_realloc( id_array,
1957                                                         ( num[i] + 2 ) * sizeof( int ));
1958                                 attr_sets[i].ID_array[num[i]] = j;
1959                                 attr_sets[i].ID_array[num[i]+1] = -1;
1960                                 num[i]++;
1961                                 if (res == 1)
1962                                         break;
1963                         case 2:
1964                                 id_array = attr_sets[j].ID_array;
1965                                 attr_sets[j].ID_array = (int *) ch_realloc( id_array,
1966                                                 ( num[j] + 2 ) * sizeof( int ));
1967                                 attr_sets[j].ID_array[num[j]] = i;
1968                                 attr_sets[j].ID_array[num[j]+1] = -1;
1969                                 num[j]++;
1970                                 break;
1971                         }
1972                 }
1973         }
1974 }
1975
1976 /*
1977  * compares two sets of attributes (indices i and j)
1978  * returns 0: if neither set is contained in the other set
1979  *         1: if set i is contained in set j
1980  *         2: if set j is contained in set i
1981  *         3: the sets are equivalent
1982  */
1983
1984 static int
1985 compare_sets(struct attr_set* set, int i, int j)
1986 {
1987         int k,l,numI,numJ;
1988         int common=0;
1989         int result=0;
1990
1991         if (( set[i].attrs == NULL ) && ( set[j].attrs == NULL ))
1992                 return 3;
1993
1994         if ( set[i].attrs == NULL )
1995                 return 2;
1996
1997         if ( set[j].attrs == NULL )
1998                 return 1;
1999
2000         numI = set[i].count;
2001         numJ = set[j].count;
2002
2003         for ( l=0; l < numI; l++ ) {
2004                 for ( k = 0; k < numJ; k++ ) {
2005                         if ( strcmp( set[i].attrs[l].an_name.bv_val,
2006                                      set[j].attrs[k].an_name.bv_val ) == 0 )
2007                                 common++;
2008                 }
2009         }
2010
2011         if ( common == numI )
2012                 result = 1;
2013
2014         if ( common == numJ )
2015                 result += 2;
2016
2017         return result;
2018 }
2019
2020 static slap_overinst proxy_cache;
2021
2022 int pcache_init()
2023 {
2024         LDAPAttributeType *at;
2025         int code;
2026         const char *err;
2027
2028         at = ldap_str2attributetype( queryid_schema, &code, &err,
2029                 LDAP_SCHEMA_ALLOW_ALL );
2030         if ( !at ) {
2031                 fprintf( stderr, "AttributeType Load failed %s %s\n",
2032                         ldap_scherr2str(code), err );
2033                 return code;
2034         }
2035         code = at_add( at, &err );
2036         if ( !code ) {
2037                 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2038         }
2039         ldap_memfree( at );
2040         if ( code ) {
2041                 fprintf( stderr, "AttributeType Load failed %s %s\n",
2042                         scherr2str(code), err );
2043                 return code;
2044         }
2045
2046         proxy_cache.on_bi.bi_type = "proxycache";
2047         proxy_cache.on_bi.bi_db_init = proxy_cache_init;
2048         proxy_cache.on_bi.bi_db_config = proxy_cache_config;
2049         proxy_cache.on_bi.bi_db_open = proxy_cache_open;
2050         proxy_cache.on_bi.bi_db_close = proxy_cache_close;
2051         proxy_cache.on_bi.bi_db_destroy = proxy_cache_destroy;
2052         proxy_cache.on_bi.bi_op_search = proxy_cache_search;
2053
2054         return overlay_register( &proxy_cache );
2055 }
2056
2057 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2058 int init_module(int argc, char *argv[]) {
2059         return pcache_init();
2060 }
2061 #endif
2062
2063 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */