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