]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
Sync with HEAD
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003-2005 The OpenLDAP Foundation.
5  * Portions Copyright 2003 IBM Corporation.
6  * Portions Copyright 2003 Symas Corporation.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by Apurva Kumar for inclusion
19  * in OpenLDAP Software and subsequently rewritten by Howard Chu.
20  */
21
22 #include "portable.h"
23
24 #ifdef SLAPD_OVER_PROXYCACHE
25
26 #include <stdio.h>
27
28 #include <ac/string.h>
29 #include <ac/time.h>
30
31 #include "slap.h"
32 #include "lutil.h"
33 #include "ldap_rq.h"
34
35 /* query cache structs */
36 /* query */
37
38 typedef struct Query_s {
39         Filter*         filter;         /* Search Filter */
40         AttributeName*  attrs;          /* Projected attributes */
41         AttributeName*  save_attrs;     /* original attributes, saved for response */
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         char    response_cb;                    /* install the response callback
121                                                  * at the tail of the callback list */
122 #define PCACHE_RESPONSE_CB_HEAD 0
123 #define PCACHE_RESPONSE_CB_TAIL 1
124
125         int     cc_period;              /* interval between successive consistency checks (sec) */
126         int     cc_paused;
127         void    *cc_arg;
128
129         ldap_pvt_thread_mutex_t         cache_mutex;
130         ldap_pvt_thread_mutex_t         remove_mutex;
131
132         query_manager*   qm;    /* query cache managed by the cache manager */
133 } cache_manager;
134
135 static AttributeDescription *ad_queryid;
136 static char *queryid_schema = "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
137                         "DESC 'list of queries the entry belongs to' "
138                         "EQUALITY octetStringMatch "
139                         "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
140                         "NO-USER-MODIFICATION USAGE directoryOperation )";
141
142 /* Return 1 for an added entry, else 0 */
143 static int
144 merge_entry(
145         Operation               *op,
146         Entry                   *e,
147         struct berval*          query_uuid )
148 {
149         int             rc;
150         Modifications* modlist = NULL;
151         const char*     text = NULL;
152         Attribute               *attr;
153         char                    textbuf[SLAP_TEXT_BUFLEN];
154         size_t                  textlen = sizeof(textbuf);
155
156         SlapReply sreply = {REP_RESULT};
157
158         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
159
160         attr = e->e_attrs;
161         e->e_attrs = NULL;
162
163         /* add queryid attribute */
164         attr_merge_one( e, ad_queryid, query_uuid, NULL );
165
166         /* append the attribute list from the fetched entry */
167         e->e_attrs->a_next = attr;
168
169         op->o_tag = LDAP_REQ_ADD;
170         op->o_protocol = LDAP_VERSION3;
171         op->o_callback = &cb;
172         op->o_time = slap_get_time();
173         op->o_do_not_cache = 1;
174
175         op->ora_e = e;
176         op->o_req_dn = e->e_name;
177         op->o_req_ndn = e->e_nname;
178         rc = op->o_bd->be_add( op, &sreply );
179
180         if ( rc != LDAP_SUCCESS ) {
181                 if ( rc == LDAP_ALREADY_EXISTS ) {
182                         slap_entry2mods( e, &modlist, &text, textbuf, textlen );
183                         modlist->sml_op = LDAP_MOD_ADD;
184                         op->o_tag = LDAP_REQ_MODIFY;
185                         op->orm_modlist = modlist;
186                         op->o_bd->be_modify( op, &sreply );
187                         slap_mods_free( modlist );
188                 } else if ( rc == LDAP_REFERRAL ||
189                                         rc == LDAP_NO_SUCH_OBJECT ) {
190                         syncrepl_add_glue( op, e );
191                         e = NULL;
192                         rc = 1;
193                 }
194                 if ( e ) {
195                         entry_free( e );
196                         rc = 0;
197                 }
198         } else {
199                 be_entry_release_w( op, e );
200                 rc = 1;
201         }
202
203         return rc;
204 }
205
206 /* compare base and scope of incoming and cached queries */
207 static int base_scope_compare(
208         struct berval* ndn_stored,
209         struct berval* ndn_incoming,
210         int scope_stored,
211         int scope_incoming      )
212 {
213         struct berval pdn_incoming = BER_BVNULL;
214
215         if (scope_stored < scope_incoming)
216                 return 0;
217
218         if ( !dnIsSuffix(ndn_incoming, ndn_stored))
219                 return 0;
220
221         switch(scope_stored) {
222         case LDAP_SCOPE_BASE:
223                 return (ndn_incoming->bv_len == ndn_stored->bv_len);
224
225         case LDAP_SCOPE_ONELEVEL:
226                 switch(scope_incoming){
227                 case LDAP_SCOPE_BASE:
228                         dnParent(ndn_incoming, &pdn_incoming);
229                         return (pdn_incoming.bv_len == ndn_stored->bv_len);
230
231                 case LDAP_SCOPE_ONELEVEL:
232                         return (ndn_incoming->bv_len == ndn_stored->bv_len);
233
234                 default:
235                         return 0;
236                 }
237         case LDAP_SCOPE_SUBTREE:
238                 return 1;
239                 break;
240         default:
241                 return 0;
242                 break;
243     }
244 }
245
246 /* add query on top of LRU list */
247 static void
248 add_query_on_top (query_manager* qm, CachedQuery* qc)
249 {
250         CachedQuery* top = qm->lru_top;
251         Query* q = (Query*)qc;
252
253         qm->lru_top = qc;
254
255         if (top)
256                 top->lru_up = qc;
257         else
258                 qm->lru_bottom = qc;
259
260         qc->lru_down = top;
261         qc->lru_up = NULL;
262         Debug( LDAP_DEBUG_ANY, "Base of added query = %s\n",
263                         q->base.bv_val, 0, 0 );
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                 Debug( LDAP_DEBUG_ANY, "Lock QC index = %d\n",
519                                 template_index, 0, 0 );
520                 ldap_pvt_thread_rdwr_rlock(&(templa[template_index].t_rwlock));
521                 for(qc=templa[template_index].query; qc != NULL; qc= qc->next) {
522                         q = (Query*)qc;
523                         if(base_scope_compare(&(q->base), base, q->scope, scope)) {
524                                 fi = inputf;
525                                 fs = q->filter;
526                                 do {
527                                         res=0;
528                                         switch (fs->f_choice) {
529                                         case LDAP_FILTER_EQUALITY:
530                                                 if (fi->f_choice == LDAP_FILTER_EQUALITY)
531                                                         mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
532                                                 else
533                                                         ret = 1;
534                                                 break;
535                                         case LDAP_FILTER_GE:
536                                         case LDAP_FILTER_LE:
537                                                 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
538                                                 break;
539                                         default:
540                                                 mrule = NULL; 
541                                         }
542                                         if (mrule) {
543                                                 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
544                                                         SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
545                                                         &(fi->f_ava->aa_value),
546                                                         &(fs->f_ava->aa_value), &text);
547                                                 if (rc != LDAP_SUCCESS) {
548                                                         ldap_pvt_thread_rdwr_runlock(&(templa[template_index].t_rwlock));
549                                                         Debug( LDAP_DEBUG_ANY,
550                                                         "Unlock: Exiting QC index=%d\n",
551                                                         template_index, 0, 0 );
552                                                         return 0;
553                                                 }
554                                         }
555                                         switch (fs->f_choice) {
556                                         case LDAP_FILTER_OR:
557                                         case LDAP_FILTER_AND:
558                                                 fs = fs->f_and;
559                                                 fi = fi->f_and;
560                                                 res=1;
561                                                 break;
562                                         case LDAP_FILTER_SUBSTRINGS:
563                                                 /* check if the equality query can be
564                                                 * answered with cached substring query */
565                                                 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
566                                                         && substr_containment_equality(
567                                                         fs, fi))
568                                                         res=1;
569                                                 /* check if the substring query can be
570                                                 * answered with cached substring query */
571                                                 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
572                                                         ) && substr_containment_substr(
573                                                         fs, fi))
574                                                         res= 1;
575                                                 fs=fs->f_next;
576                                                 fi=fi->f_next;
577                                                 break;
578                                         case LDAP_FILTER_PRESENT:
579                                                 res=1;
580                                                 fs=fs->f_next;
581                                                 fi=fi->f_next;
582                                                 break;
583                                         case LDAP_FILTER_EQUALITY:
584                                                 if (ret == 0)
585                                                         res = 1;
586                                                 fs=fs->f_next;
587                                                 fi=fi->f_next;
588                                                 break;
589                                         case LDAP_FILTER_GE:
590                                                 if (ret >= 0)
591                                                         res = 1;
592                                                 fs=fs->f_next;
593                                                 fi=fi->f_next;
594                                                 break;
595                                         case LDAP_FILTER_LE:
596                                                 if (ret <= 0)
597                                                         res = 1;
598                                                 fs=fs->f_next;
599                                                 fi=fi->f_next;
600                                                 break;
601                                         case LDAP_FILTER_NOT:
602                                                 res=0;
603                                                 break;
604                                         default:
605                                                 break;
606                                         }
607                                 } while((res) && (fi != NULL) && (fs != NULL));
608
609                                 if(res) {
610                                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
611                                         if (qm->lru_top != qc) {
612                                                 remove_query(qm, qc);
613                                                 add_query_on_top(qm, qc);
614                                         }
615                                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
616                                         return 1;
617                                 }
618                         }
619                 }
620                 Debug( LDAP_DEBUG_ANY,
621                         "Not answerable: Unlock QC index=%d\n",
622                         template_index, 0, 0 );
623                 ldap_pvt_thread_rdwr_runlock(&(templa[template_index].t_rwlock));
624         }
625         return 0;
626 }
627
628 static void
629 free_query (CachedQuery* qc)
630 {
631         Query* q = (Query*)qc;
632         int i;
633
634         free(qc->q_uuid.bv_val);
635         filter_free(q->filter);
636         free (q->base.bv_val);
637         for (i=0; q->attrs[i].an_name.bv_val; i++) {
638                 free(q->attrs[i].an_name.bv_val);
639         }
640         free(q->attrs);
641         free(qc);
642 }
643
644
645 /* Add query to query cache */
646 static void add_query(
647         query_manager* qm,
648         Query* query,
649         int template_index,
650         struct berval* uuid)
651 {
652         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
653         QueryTemplate* templ = (qm->templates)+template_index;
654         Query* new_query;
655         new_cached_query->template_id = template_index;
656         new_cached_query->q_uuid = *uuid;
657         new_cached_query->lru_up = NULL;
658         new_cached_query->lru_down = NULL;
659         new_cached_query->expiry_time = slap_get_time() + templ->ttl;
660         Debug( LDAP_DEBUG_ANY, "Added query expires at %ld\n",
661                         (long) new_cached_query->expiry_time, 0, 0 );
662         new_query = (Query*)new_cached_query;
663
664         ber_dupbv(&new_query->base, &query->base);
665         new_query->scope = query->scope;
666         new_query->filter = query->filter;
667         new_query->attrs = query->attrs;
668
669         /* Adding a query    */
670         Debug( LDAP_DEBUG_ANY, "Lock AQ index = %d\n",
671                         template_index, 0, 0 );
672         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
673         if (templ->query == NULL)
674                 templ->query_last = new_cached_query;
675         else
676                 templ->query->prev = new_cached_query;
677         new_cached_query->next = templ->query;
678         new_cached_query->prev = NULL;
679         templ->query = new_cached_query;
680         templ->no_of_queries++;
681         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES++ %d\n",
682                         template_index, templ->no_of_queries, 0 );
683
684         Debug( LDAP_DEBUG_ANY, "Unlock AQ index = %d \n",
685                         template_index, 0, 0 );
686         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
687
688         /* Adding on top of LRU list  */
689         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
690         add_query_on_top(qm, new_cached_query);
691         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
692 }
693
694 static void
695 remove_from_template (CachedQuery* qc, QueryTemplate* template)
696 {
697         if (!qc->prev && !qc->next) {
698                 template->query_last = template->query = NULL;
699         } else if (qc->prev == NULL) {
700                 qc->next->prev = NULL;
701                 template->query = qc->next;
702         } else if (qc->next == NULL) {
703                 qc->prev->next = NULL;
704                 template->query_last = qc->prev;
705         } else {
706                 qc->next->prev = qc->prev;
707                 qc->prev->next = qc->next;
708         }
709
710         template->no_of_queries--;
711 }
712
713 /* remove bottom query of LRU list from the query cache */
714 static void cache_replacement(query_manager* qm, struct berval *result)
715 {
716         CachedQuery* bottom;
717         int temp_id;
718
719         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
720         bottom = qm->lru_bottom;
721
722         result->bv_val = NULL;
723         result->bv_len = 0;
724
725         if (!bottom) {
726                 Debug ( LDAP_DEBUG_ANY,
727                         "Cache replacement invoked without "
728                         "any query in LRU list\n", 0, 0, 0 );
729                 return;
730         }
731
732         temp_id = bottom->template_id;
733         remove_query(qm, bottom);
734         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
735
736         *result = bottom->q_uuid;
737         bottom->q_uuid.bv_val = NULL;
738
739         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n", temp_id, 0, 0 );
740         ldap_pvt_thread_rdwr_wlock(&(qm->templates[temp_id].t_rwlock));
741         remove_from_template(bottom, (qm->templates+temp_id));
742         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
743                 temp_id, qm->templates[temp_id].no_of_queries, 0 );
744         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n", temp_id, 0, 0 );
745         ldap_pvt_thread_rdwr_wunlock(&(qm->templates[temp_id].t_rwlock));
746         free_query(bottom);
747 }
748
749 struct query_info {
750         struct query_info *next;
751         struct berval xdn;
752         int del;
753 };
754
755 static int
756 remove_func (
757         Operation       *op,
758         SlapReply       *rs
759 )
760 {
761         Attribute *attr;
762         struct query_info *qi;
763         int count = 0;
764
765         if ( rs->sr_type != REP_SEARCH ) return 0;
766
767         for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
768                 if (attr->a_desc == ad_queryid) {
769                         for (count=0; attr->a_vals[count].bv_val; count++)
770                                 ;
771                         break;
772                 }
773         }
774         if ( count == 0 ) return 0;
775         qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
776         qi->next = op->o_callback->sc_private;
777         op->o_callback->sc_private = qi;
778         ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
779         qi->del = ( count == 1 );
780
781         return 0;
782 }
783
784 static int
785 remove_query_data (
786         Operation       *op,
787         SlapReply       *rs,
788         struct berval* query_uuid)
789 {
790         struct query_info       *qi, *qnext;
791         char                    filter_str[64];
792         AttributeAssertion      ava;
793         Filter                  filter = {LDAP_FILTER_EQUALITY};
794         SlapReply               sreply = {REP_RESULT};
795         slap_callback cb = { NULL, remove_func, NULL, NULL };
796         int deleted = 0;
797
798         sreply.sr_entry = NULL;
799         sreply.sr_nentries = 0;
800         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
801                 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
802         filter.f_ava = &ava;
803         filter.f_av_desc = ad_queryid;
804         filter.f_av_value = *query_uuid;
805
806         op->o_tag = LDAP_REQ_SEARCH;
807         op->o_protocol = LDAP_VERSION3;
808         op->o_callback = &cb;
809         op->o_time = slap_get_time();
810         op->o_do_not_cache = 1;
811
812         op->o_req_dn = op->o_bd->be_suffix[0];
813         op->o_req_ndn = op->o_bd->be_nsuffix[0];
814         op->ors_scope = LDAP_SCOPE_SUBTREE;
815         op->ors_deref = LDAP_DEREF_NEVER;
816         op->ors_slimit = SLAP_NO_LIMIT;
817         op->ors_tlimit = SLAP_NO_LIMIT;
818         op->ors_filter = &filter;
819         op->ors_filterstr.bv_val = filter_str;
820         op->ors_filterstr.bv_len = strlen(filter_str);
821         op->ors_attrs = NULL;
822         op->ors_attrsonly = 0;
823
824         op->o_bd->be_search( op, &sreply );
825
826         for ( qi=cb.sc_private; qi; qi=qnext ) {
827                 qnext = qi->next;
828
829                 op->o_req_dn = qi->xdn;
830                 op->o_req_ndn = qi->xdn;
831
832                 if ( qi->del) {
833                         Debug( LDAP_DEBUG_ANY, "DELETING ENTRY TEMPLATE=%s\n",
834                                 query_uuid->bv_val, 0, 0 );
835
836                         op->o_tag = LDAP_REQ_DELETE;
837
838                         if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
839                                 deleted++;
840                         }
841                 } else {
842                         Modifications mod;
843                         struct berval vals[2];
844
845                         vals[0] = *query_uuid;
846                         vals[1].bv_val = NULL;
847                         vals[1].bv_len = 0;
848                         mod.sml_op = LDAP_MOD_DELETE;
849                         mod.sml_desc = ad_queryid;
850                         mod.sml_type = ad_queryid->ad_cname;
851                         mod.sml_values = vals;
852                         mod.sml_nvalues = NULL;
853                         mod.sml_next = NULL;
854                         Debug( LDAP_DEBUG_ANY,
855                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
856                                 query_uuid->bv_val, 0, 0 );
857
858                         op->orm_modlist = &mod;
859
860                         op->o_bd->be_modify( op, &sreply );
861                 }
862                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
863                 op->o_tmpfree( qi, op->o_tmpmemctx );
864         }
865         return deleted;
866 }
867
868 static int
869 get_attr_set(
870         AttributeName* attrs,
871         query_manager* qm,
872         int num
873 );
874
875 static int
876 attrscmp(
877         AttributeName* attrs_in,
878         AttributeName* attrs
879 );
880
881 static int
882 is_temp_answerable(
883         int attr_set,
884         struct berval* tempstr,
885         query_manager* qm,
886         int template_id )
887 {
888         QueryTemplate *qt = qm->templates + template_id;
889
890         if (attr_set != qt->attr_set_index) {
891                 int* id_array = qm->attr_sets[attr_set].ID_array;
892
893                 while (*id_array != -1) {
894                         if (*id_array == qt->attr_set_index)
895                                 break;
896                         id_array++;
897                 }
898                 if (*id_array == -1)
899                         return 0;
900         }
901         return (qt->querystr.bv_len == tempstr->bv_len &&
902                 strcasecmp(qt->querystr.bv_val, tempstr->bv_val) == 0);
903 }
904
905 static int
906 filter2template(
907         Filter                  *f,
908         struct                  berval *fstr,
909         AttributeName**         filter_attrs,
910         int*                    filter_cnt )
911 {
912         AttributeDescription *ad;
913
914         switch ( f->f_choice ) {
915         case LDAP_FILTER_EQUALITY:
916                 ad = f->f_av_desc;
917                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
918                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
919                 break;
920
921         case LDAP_FILTER_GE:
922                 ad = f->f_av_desc;
923                 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
924                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
925                 break;
926
927         case LDAP_FILTER_LE:
928                 ad = f->f_av_desc;
929                 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
930                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
931                 break;
932
933         case LDAP_FILTER_APPROX:
934                 ad = f->f_av_desc;
935                 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
936                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
937                 break;
938
939         case LDAP_FILTER_SUBSTRINGS:
940                 ad = f->f_sub_desc;
941                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
942                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
943                 break;
944
945         case LDAP_FILTER_PRESENT:
946                 ad = f->f_desc;
947                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
948                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
949                 break;
950
951         case LDAP_FILTER_AND:
952         case LDAP_FILTER_OR:
953         case LDAP_FILTER_NOT: {
954                 int rc = 0;
955                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
956                         f->f_choice == LDAP_FILTER_AND ? '&' :
957                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
958                 fstr->bv_len += sizeof("(%") - 1;
959
960                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
961                         rc = filter2template( f, fstr, filter_attrs, filter_cnt );
962                         if ( rc ) break;
963                 }
964                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
965                 fstr->bv_len += sizeof(")") - 1;
966
967                 return rc;
968                 }
969
970         default:
971                 strcpy( fstr->bv_val, "(?=?)" );
972                 fstr->bv_len += sizeof("(?=?)")-1;
973                 return -1;
974         }
975
976         *filter_attrs = (AttributeName *)ch_realloc(*filter_attrs,
977                                 (*filter_cnt + 2)*sizeof(AttributeName));
978
979         (*filter_attrs)[*filter_cnt].an_desc = ad;
980         (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
981         (*filter_attrs)[*filter_cnt+1].an_name.bv_val = NULL;
982         (*filter_attrs)[*filter_cnt+1].an_name.bv_len = 0;
983         (*filter_cnt)++;
984         return 0;
985 }
986
987 struct search_info {
988         slap_overinst *on;
989         Query query;
990         int template_id;
991         int max;
992         int over;
993         int count;
994         Entry *head, *tail;
995 };
996
997 static int
998 cache_entries(
999         Operation       *op,
1000         SlapReply       *rs,
1001         struct berval *query_uuid)
1002 {
1003         struct search_info *si = op->o_callback->sc_private;
1004         slap_overinst *on = si->on;
1005         cache_manager *cm = on->on_bi.bi_private;
1006         query_manager*          qm = cm->qm;
1007         int             i;
1008         int             return_val = 0;
1009         Entry           *e;
1010         struct berval   crp_uuid;
1011         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1012         Operation op_tmp = *op;
1013
1014         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1015         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1016
1017         op_tmp.o_bd = &cm->db;
1018         op_tmp.o_dn = cm->db.be_rootdn;
1019         op_tmp.o_ndn = cm->db.be_rootndn;
1020
1021         Debug( LDAP_DEBUG_ANY, "UUID for query being added = %s\n",
1022                         uuidbuf, 0, 0 );
1023
1024         for ( e=si->head; e; e=si->head ) {
1025                 si->head = e->e_private;
1026                 e->e_private = NULL;
1027                 Debug( LDAP_DEBUG_NONE, "LOCKING REMOVE MUTEX\n", 0, 0, 0 );
1028                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1029                 Debug( LDAP_DEBUG_NONE, "LOCKED REMOVE MUTEX\n", 0, 0, 0);
1030                 while ( cm->cur_entries > (cm->max_entries) ) {
1031                                 qm->crfunc(qm, &crp_uuid);
1032                                 if (crp_uuid.bv_val) {
1033                                         Debug( LDAP_DEBUG_ANY,
1034                                                 "Removing query UUID %s\n",
1035                                                 crp_uuid.bv_val, 0, 0 );
1036                                         return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1037                                         Debug( LDAP_DEBUG_ANY,
1038                                                 "QUERY REMOVED, SIZE=%d\n",
1039                                                 return_val, 0, 0);
1040                                         ldap_pvt_thread_mutex_lock(
1041                                                         &cm->cache_mutex );
1042                                         cm->cur_entries -= return_val;
1043                                         cm->num_cached_queries--;
1044                                         Debug( LDAP_DEBUG_ANY,
1045                                                 "STORED QUERIES = %lu\n",
1046                                                 cm->num_cached_queries, 0, 0 );
1047                                         ldap_pvt_thread_mutex_unlock(
1048                                                         &cm->cache_mutex );
1049                                         Debug( LDAP_DEBUG_ANY,
1050                                                 "QUERY REMOVED, CACHE ="
1051                                                 "%d entries\n",
1052                                                 cm->cur_entries, 0, 0 );
1053                                 }
1054                 }
1055
1056                 return_val = merge_entry(&op_tmp, e, query_uuid);
1057                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1058                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1059                 cm->cur_entries += return_val;
1060                 Debug( LDAP_DEBUG_ANY,
1061                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1062                         cm->cur_entries, 0, 0 );
1063                 return_val = 0;
1064                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1065         }
1066         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1067         cm->num_cached_queries++;
1068         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1069                         cm->num_cached_queries, 0, 0 );
1070         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1071
1072         return return_val;
1073 }
1074
1075 static int
1076 proxy_cache_response(
1077         Operation       *op,
1078         SlapReply       *rs )
1079 {
1080         struct search_info *si = op->o_callback->sc_private;
1081         slap_overinst *on = si->on;
1082         cache_manager *cm = on->on_bi.bi_private;
1083         query_manager*          qm = cm->qm;
1084         struct berval uuid;
1085
1086         if ( rs->sr_type == REP_SEARCH ) {
1087                 Entry *e;
1088                 /* If we haven't exceeded the limit for this query,
1089                  * build a chain of answers to store. If we hit the
1090                  * limit, empty the chain and ignore the rest.
1091                  */
1092                 if ( !si->over ) {
1093                         if ( si->count < si->max ) {
1094                                 si->count++;
1095                                 e = entry_dup( rs->sr_entry );
1096                                 if ( !si->head ) si->head = e;
1097                                 if ( si->tail ) si->tail->e_private = e;
1098                                 si->tail = e;
1099                         } else {
1100                                 si->over = 1;
1101                                 si->count = 0;
1102                                 for (;si->head; si->head=e) {
1103                                         e = si->head->e_private;
1104                                         si->head->e_private = NULL;
1105                                         entry_free(si->head);
1106                                 }
1107                                 si->tail = NULL;
1108                         }
1109                 }
1110
1111                 if (rs->sr_attrs != op->ors_attrs ) {
1112                         op->o_tmpfree( rs->sr_attrs, op->o_tmpmemctx );
1113                 }
1114                 rs->sr_attrs = si->query.save_attrs;
1115                 op->o_tmpfree( op->ors_attrs, op->o_tmpmemctx );
1116                 op->ors_attrs = si->query.save_attrs;
1117                 si->query.save_attrs = NULL;
1118
1119         } else if ( rs->sr_type == REP_RESULT ) {
1120                 if ( si->count && cache_entries( op, rs, &uuid ) == 0 ) {
1121                         qm->addfunc(qm, &si->query, si->template_id, &uuid);
1122                         /* If the consistency checker suspended itself,
1123                          * wake it back up
1124                          */
1125                         if ( cm->cc_paused ) {
1126                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1127                                 if ( cm->cc_paused ) {
1128                                         cm->cc_paused = 0;
1129                                         ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1130                                 }
1131                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1132                         }
1133                 }
1134
1135                 /* free self */
1136                 op->o_callback->sc_cleanup = slap_freeself_cb;
1137         }
1138         return SLAP_CB_CONTINUE;
1139 }
1140
1141 static void
1142 add_filter_attrs(
1143         Operation *op,
1144         AttributeName** new_attrs,
1145         AttributeName* attrs,
1146         AttributeName* filter_attrs )
1147 {
1148         int alluser = 0;
1149         int allop = 0;
1150         int i;
1151         int count;
1152
1153         /* duplicate attrs */
1154         if (attrs == NULL) {
1155                 count = 1;
1156         } else {
1157                 for (count=0; attrs[count].an_name.bv_val; count++)
1158                         ;
1159         }
1160         *new_attrs = (AttributeName*)(op->o_tmpalloc((count+1)*
1161                 sizeof(AttributeName), op->o_tmpmemctx));
1162         if (attrs == NULL) {
1163                 (*new_attrs)[0].an_name.bv_val = "*";
1164                 (*new_attrs)[0].an_name.bv_len = 1;
1165                 (*new_attrs)[1].an_name.bv_val = NULL;
1166                 (*new_attrs)[1].an_name.bv_len = 0;
1167                 alluser = 1;
1168                 allop = 0;
1169         } else {
1170                 for (i=0; i<count; i++) {
1171                         (*new_attrs)[i].an_name = attrs[i].an_name;
1172                         (*new_attrs)[i].an_desc = attrs[i].an_desc;
1173                 }
1174                 (*new_attrs)[count].an_name.bv_val = NULL;
1175                 (*new_attrs)[count].an_name.bv_len = 0;
1176                 alluser = an_find(*new_attrs, &AllUser);
1177                 allop = an_find(*new_attrs, &AllOper);
1178         }
1179
1180         for ( i=0; filter_attrs[i].an_name.bv_val; i++ ) {
1181                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1182                         continue;
1183                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1184                         if (allop)
1185                                 continue;
1186                 } else if (alluser)
1187                         continue;
1188                 *new_attrs = (AttributeName*)(op->o_tmprealloc(*new_attrs,
1189                                         (count+2)*sizeof(AttributeName), op->o_tmpmemctx));
1190                 (*new_attrs)[count].an_name = filter_attrs[i].an_name;
1191                 (*new_attrs)[count].an_desc = filter_attrs[i].an_desc;
1192                 count++;
1193                 (*new_attrs)[count].an_name.bv_val = NULL;
1194                 (*new_attrs)[count].an_name.bv_len = 0;
1195         }
1196 }
1197
1198 static int
1199 proxy_cache_search(
1200         Operation       *op,
1201         SlapReply       *rs )
1202 {
1203         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1204         cache_manager *cm = on->on_bi.bi_private;
1205         query_manager*          qm = cm->qm;
1206
1207         int count;
1208
1209         int i = -1;
1210
1211         AttributeName   *filter_attrs = NULL;
1212         AttributeName   *new_attrs = NULL;
1213
1214         Query           query;
1215
1216         int             attr_set = -1;
1217         int             template_id = -1;
1218         int             answerable = 0;
1219         int             cacheable = 0;
1220         int             fattr_cnt=0;
1221         int             oc_attr_absent = 1;
1222
1223         struct berval tempstr;
1224
1225         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1226         tempstr.bv_len = 0;
1227         if (filter2template(op->ors_filter, &tempstr, &filter_attrs, &fattr_cnt)) {
1228                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1229                 return SLAP_CB_CONTINUE;
1230         }
1231
1232         Debug( LDAP_DEBUG_ANY, "query template of incoming query = %s\n",
1233                                         tempstr.bv_val, 0, 0 );
1234
1235         /* find attr set */
1236         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1237
1238         query.filter = op->ors_filter;
1239         query.attrs = op->ors_attrs;
1240         query.save_attrs = NULL;
1241         query.base = op->o_req_ndn;
1242         query.scope = op->ors_scope;
1243
1244         /* check for query containment */
1245         if (attr_set > -1) {
1246                 for (i=0; i<cm->numtemplates; i++) {
1247                         /* find if template i can potentially answer tempstr */
1248                         if (!is_temp_answerable(attr_set, &tempstr, qm, i))
1249                                 continue;
1250                         if (attr_set == qm->templates[i].attr_set_index) {
1251                                 cacheable = 1;
1252                                 template_id = i;
1253                         }
1254                         Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1255                                         op->ors_filterstr.bv_val, 0, 0 );
1256                         answerable = (*(qm->qcfunc))(qm, &query, i);
1257
1258                         if (answerable)
1259                                 break;
1260                 }
1261         }
1262         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1263
1264         query.save_attrs = op->ors_attrs;
1265         query.attrs = NULL;
1266
1267         if (answerable) {
1268                 /* Need to clear the callbacks of the original operation,
1269                  * in case there are other overlays */
1270                 BackendDB       *save_bd = op->o_bd;
1271                 slap_callback   *save_cb = op->o_callback;
1272
1273                 Debug( LDAP_DEBUG_ANY, "QUERY ANSWERABLE\n", 0, 0, 0 );
1274                 free(filter_attrs);
1275                 ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock);
1276                 op->o_bd = &cm->db;
1277                 op->o_callback = NULL;
1278                 i = cm->db.bd_info->bi_op_search( op, rs );
1279                 op->o_bd = save_bd;
1280                 op->o_callback = save_cb;
1281                 return i;
1282         }
1283
1284         Debug( LDAP_DEBUG_ANY, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1285
1286         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1287         if (cm->num_cached_queries >= cm->max_queries) {
1288                 cacheable = 0;
1289         }
1290         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1291
1292         if (cacheable) {
1293                 slap_callback           *cb;
1294                 struct search_info      *si;
1295
1296                 Debug( LDAP_DEBUG_ANY, "QUERY CACHEABLE\n", 0, 0, 0 );
1297                 query.filter = str2filter(op->ors_filterstr.bv_val);
1298                 if (op->ors_attrs) {
1299                         for ( count = 0; !BER_BVISNULL( &op->ors_attrs[ count ].an_name ); count++ ) {
1300                                 if ( op->ors_attrs[count].an_desc == slap_schema.si_ad_objectClass ) {
1301                                         oc_attr_absent = 0;
1302                                 }
1303                         }
1304                         query.attrs = (AttributeName *)ch_malloc( ( count + 1 + oc_attr_absent )
1305                                                                         *sizeof(AttributeName) );
1306                         for ( count = 0; !BER_BVISNULL( &op->ors_attrs[ count ].an_name ); count++ ) {
1307                                 ber_dupbv( &query.attrs[count].an_name, &op->ors_attrs[count].an_name );
1308                                 query.attrs[count].an_desc = op->ors_attrs[count].an_desc;
1309                         }
1310                         if ( oc_attr_absent ) {
1311                                 query.attrs[ count ].an_desc = slap_schema.si_ad_objectClass;
1312                                 ber_dupbv( &query.attrs[count].an_name,
1313                                         &slap_schema.si_ad_objectClass->ad_cname );
1314                                 count++;
1315                         }
1316                         query.attrs[ count ].an_name.bv_val = NULL;
1317                         query.attrs[ count ].an_name.bv_len = 0;
1318                 }
1319                 add_filter_attrs(op, &op->ors_attrs, query.attrs, filter_attrs);
1320
1321                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1322                 cb->sc_response = proxy_cache_response;
1323                 cb->sc_cleanup = NULL;
1324                 cb->sc_private = (cb+1);
1325                 si = cb->sc_private;
1326                 si->on = on;
1327                 si->query = query;
1328                 si->template_id = template_id;
1329                 si->max = cm->num_entries_limit ;
1330                 si->over = 0;
1331                 si->count = 0;
1332                 si->head = NULL;
1333                 si->tail = NULL;
1334
1335                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1336                         cb->sc_next = op->o_callback;
1337                         op->o_callback = cb;
1338
1339                 } else {
1340                         slap_callback           **pcb;
1341
1342                         /* need to move the callback at the end, in case other
1343                          * overlays are present, so that the final entry is
1344                          * actually cached */
1345                         cb->sc_next = NULL;
1346                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1347                         *pcb = cb;
1348                 }
1349
1350         } else {
1351                 Debug( LDAP_DEBUG_ANY, "QUERY NOT CACHEABLE\n",
1352                                         0, 0, 0);
1353         }
1354
1355         free(filter_attrs);
1356
1357         return SLAP_CB_CONTINUE;
1358 }
1359
1360 static int
1361 attrscmp(
1362         AttributeName* attrs_in,
1363         AttributeName* attrs)
1364 {
1365         int i, count1, count2;
1366         if ( attrs_in == NULL ) {
1367                 return (attrs ? 0 : 1);
1368         }
1369         if ( attrs == NULL )
1370                 return 0;
1371
1372         for ( count1=0;
1373               attrs_in && attrs_in[count1].an_name.bv_val != NULL;
1374               count1++ )
1375                 ;
1376         for ( count2=0;
1377               attrs && attrs[count2].an_name.bv_val != NULL;
1378               count2++)
1379                 ;
1380         if ( count1 != count2 )
1381                 return 0;
1382
1383         for ( i=0; i<count1; i++ ) {
1384                 if ( !an_find(attrs, &attrs_in[i].an_name ))
1385                         return 0;
1386         }
1387         return 1;
1388 }
1389
1390 static int
1391 get_attr_set(
1392         AttributeName* attrs,
1393         query_manager* qm,
1394         int num )
1395 {
1396         int i;
1397         for (i=0; i<num; i++) {
1398                 if (attrscmp(attrs, qm->attr_sets[i].attrs))
1399                         return i;
1400         }
1401         return -1;
1402 }
1403
1404 static void*
1405 consistency_check(
1406         void *ctx,
1407         void *arg )
1408 {
1409         struct re_s *rtask = arg;
1410         slap_overinst *on = rtask->arg;
1411         cache_manager *cm = on->on_bi.bi_private;
1412         query_manager *qm = cm->qm;
1413         Connection conn = {0};
1414         char opbuf[OPERATION_BUFFER_SIZE];
1415         Operation *op;
1416
1417         SlapReply rs = {REP_RESULT};
1418         CachedQuery* query, *query_prev;
1419         int i, return_val, pause = 1;
1420         QueryTemplate* templ;
1421
1422         op = (Operation *)opbuf;
1423         connection_fake_init( &conn, op, ctx );
1424
1425         op->o_bd = &cm->db;
1426         op->o_dn = cm->db.be_rootdn;
1427         op->o_ndn = cm->db.be_rootndn;
1428
1429         cm->cc_arg = arg;
1430
1431         for (i=0; qm->templates[i].querystr.bv_val; i++) {
1432                 templ = qm->templates + i;
1433                 query = templ->query_last;
1434                 if ( query ) pause = 0;
1435                 op->o_time = slap_get_time();
1436                 ldap_pvt_thread_mutex_lock(&cm->remove_mutex);
1437                 while (query && (query->expiry_time < op->o_time)) {
1438                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1439                         remove_query(qm, query);
1440                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1441                         Debug( LDAP_DEBUG_ANY, "Lock CR index = %d\n",
1442                                         i, 0, 0 );
1443                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1444                         remove_from_template(query, templ);
1445                         Debug( LDAP_DEBUG_ANY, "TEMPLATE %d QUERIES-- %d\n",
1446                                         i, templ->no_of_queries, 0 );
1447                         Debug( LDAP_DEBUG_ANY, "Unlock CR index = %d\n",
1448                                         i, 0, 0 );
1449                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1450                         return_val = remove_query_data(op, &rs, &query->q_uuid);
1451                         Debug( LDAP_DEBUG_ANY, "STALE QUERY REMOVED, SIZE=%d\n",
1452                                                 return_val, 0, 0 );
1453                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1454                         cm->cur_entries -= return_val;
1455                         cm->num_cached_queries--;
1456                         Debug( LDAP_DEBUG_ANY, "STORED QUERIES = %lu\n",
1457                                         cm->num_cached_queries, 0, 0 );
1458                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1459                         Debug( LDAP_DEBUG_ANY,
1460                                 "STALE QUERY REMOVED, CACHE ="
1461                                 "%d entries\n",
1462                                 cm->cur_entries, 0, 0 );
1463                         query_prev = query;
1464                         query = query->prev;
1465                         free_query(query_prev);
1466                 }
1467                 ldap_pvt_thread_mutex_unlock(&cm->remove_mutex);
1468         }
1469         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1470         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1471                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1472         }
1473         /* If there were no queries, defer processing for a while */
1474         cm->cc_paused = pause;
1475         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1476
1477         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1478         return NULL;
1479 }
1480
1481
1482 #define MAX_ATTR_SETS 500
1483 static void find_supersets( struct attr_set* attr_sets, int numsets );
1484 static int compare_sets( struct attr_set* setA, int, int );
1485
1486 static int
1487 proxy_cache_config(
1488         BackendDB       *be,
1489         const char      *fname,
1490         int             lineno,
1491         int             argc,
1492         char            **argv
1493 )
1494 {
1495         slap_overinst   *on = (slap_overinst *)be->bd_info;
1496         cache_manager*  cm = on->on_bi.bi_private;
1497         query_manager*  qm = cm->qm;
1498         QueryTemplate*  temp;
1499         AttributeName*  attr_name;
1500         AttributeName*  attrarray;
1501         const char*     text=NULL;
1502         char            *save_argv0 = NULL;
1503
1504         int             index, i;
1505         int             num;
1506         int             rc = 0;
1507
1508         if ( strncasecmp( argv[0], "proxycache-", STRLENOF( "proxycache-" ) ) == 0 ) {
1509                 save_argv0 = argv[0];
1510                 argv[0] += STRLENOF( "proxycache-" );
1511         }
1512
1513         if ( strcasecmp( argv[0], "proxycache" ) == 0 ) {
1514                 if ( argc < 6 ) {
1515                         fprintf( stderr, "%s: line %d: missing arguments in \"proxycache"
1516                                 " <backend> <max_entries> <numattrsets> <entry limit> "
1517                                 "<cycle_time>\"\n", fname, lineno );
1518                         return( 1 );
1519                 }
1520
1521                 cm->db.bd_info = backend_info( argv[1] );
1522                 if ( !cm->db.bd_info ) {
1523                         fprintf( stderr, "%s: line %d: backend %s unknown\n",
1524                                 fname, lineno, argv[1] );
1525                         return( 1 );
1526                 }
1527                 if ( cm->db.bd_info->bi_db_init( &cm->db ) ) return( 1 );
1528
1529                 /* This type is in use, needs to be opened */
1530                 cm->db.bd_info->bi_nDB++;
1531
1532                 cm->max_entries = atoi( argv[2] );
1533
1534                 cm->numattrsets = atoi( argv[3] );
1535                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1536                         fprintf( stderr, "%s: line %d: numattrsets must be <= %d\n",
1537                                 fname, lineno, MAX_ATTR_SETS );
1538                         return( 1 );
1539                 }
1540
1541                 cm->num_entries_limit = atoi( argv[4] );
1542                 cm->cc_period = atoi( argv[5] );
1543                 Debug( LDAP_DEBUG_ANY,
1544                                 "Total # of attribute sets to be cached = %d\n",
1545                                 cm->numattrsets, 0, 0 );
1546                 qm->attr_sets = ( struct attr_set * )ch_malloc( cm->numattrsets *
1547                                                 sizeof( struct attr_set ));
1548                 for ( i = 0; i < cm->numattrsets; i++ ) {
1549                         qm->attr_sets[i].attrs = NULL;
1550                 }
1551
1552         } else if ( strcasecmp( argv[0], "proxyattrset" ) == 0 ) {
1553                 if ( argc < 3 ) {
1554                         fprintf( stderr, "%s: line %d: missing arguments in \"proxyattrset "
1555                                 "<index> <attributes>\"\n", fname, lineno );
1556                         return( 1 );
1557                 }
1558                 Debug( LDAP_DEBUG_ANY, "Attribute Set # %d\n",
1559                                 atoi( argv[1] ), 0, 0 );
1560                 if (atoi(argv[1]) >= cm->numattrsets) {
1561                         fprintf( stderr, "%s; line %d index out of bounds \n",
1562                                         fname, lineno );
1563                         return 1;
1564                 }
1565                 index = atoi( argv[1] );
1566                 if ( argv[2] && strcmp( argv[2], "*" ) ) {
1567                         qm->attr_sets[index].count = argc - 2;
1568                         qm->attr_sets[index].attrs = (AttributeName*)ch_malloc(
1569                                                 (argc-1) * sizeof( AttributeName ));
1570                         attr_name = qm->attr_sets[index].attrs;
1571                         for ( i = 2; i < argc; i++ ) {
1572                                 Debug( LDAP_DEBUG_ANY, "\t %s\n",
1573                                                 argv[i], 0, 0 );
1574                                 ber_str2bv( argv[i], 0, 1,
1575                                                 &attr_name->an_name);
1576                                 attr_name->an_desc = NULL;
1577                                 slap_bv2ad( &attr_name->an_name,
1578                                                 &attr_name->an_desc, &text );
1579                                 attr_name++;
1580                                 attr_name->an_name.bv_val = NULL;
1581                                 attr_name->an_name.bv_len = 0;
1582                         }
1583                 }
1584         } else if ( strcasecmp( argv[0], "proxytemplate" ) == 0 ) {
1585                 if ( argc != 4 ) {
1586                         fprintf( stderr, "%s: line %d: missing argument(s) in "
1587                                 "\"proxytemplate <filter> <proj attr set> <TTL>\" line\n",
1588                                 fname, lineno );
1589                         return( 1 );
1590                 }
1591                 if (( i = atoi( argv[2] )) >= cm->numattrsets ) {
1592                         Debug( LDAP_DEBUG_ANY,
1593                                         "%s: line %d, template index invalid\n",
1594                                         fname, lineno, 0 );
1595                         return 1;
1596                 }
1597                 num = cm->numtemplates;
1598                 if ( num == 0 )
1599                         find_supersets( qm->attr_sets, cm->numattrsets );
1600                 qm->templates = ( QueryTemplate* )ch_realloc( qm->templates,
1601                                 ( num + 2 ) * sizeof( QueryTemplate ));
1602                 temp = qm->templates + num;
1603                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
1604                 temp->query = temp->query_last = NULL;
1605                 temp->ttl = atoi( argv[3] );
1606                 temp->no_of_queries = 0;
1607                 if ( argv[1] == NULL ) {
1608                         Debug( LDAP_DEBUG_ANY,
1609                                         "Templates string not specified "
1610                                         "for template %d\n", num, 0, 0 );
1611                         return 1;
1612                 }
1613                 ber_str2bv( argv[1], 0, 1, &temp->querystr );
1614                 Debug( LDAP_DEBUG_ANY, "Template:\n", 0, 0, 0 );
1615                 Debug( LDAP_DEBUG_ANY, "  query template: %s\n",
1616                                 temp->querystr.bv_val, 0, 0 );
1617                 temp->attr_set_index = i;
1618                 Debug( LDAP_DEBUG_ANY, "  attributes: \n", 0, 0, 0 );
1619                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
1620                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
1621                                 Debug( LDAP_DEBUG_ANY, "\t%s\n",
1622                                         attrarray[i].an_name.bv_val, 0, 0 );
1623                 }
1624                 temp++; 
1625                 temp->querystr.bv_val = NULL;
1626                 cm->numtemplates++;
1627
1628         } else if ( strcasecmp( argv[0], "response-callback" ) == 0 ) {
1629                 /* set to "tail" to put the response callback
1630                  * at the end of the callback list; this is required
1631                  * in case other overlays are present, so that the
1632                  * final entry is cached. */
1633
1634                 if ( argc < 2 ) {
1635                         Debug( LDAP_DEBUG_ANY,
1636                                         "missing specifier for \"response-callback {head(default)|tail}\" "
1637                                         "callback position\n", 0, 0, 0 );
1638                         return 1;
1639                 }
1640
1641                 if ( strcasecmp( argv[1], "head" ) == 0 ) {
1642                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
1643
1644                 } else if ( strcasecmp( argv[1], "tail" ) == 0 ) {
1645                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1646
1647                 } else {
1648                         Debug( LDAP_DEBUG_ANY,
1649                                         "unknown specifier %s for \"response-callback {head(default)|tail}\" "
1650                                         "callback position\n", argv[1], 0, 0 );
1651                         return 1;
1652                 }
1653         }
1654         /* anything else */
1655         else {
1656                 rc = cm->db.bd_info->bi_db_config( &cm->db, fname, lineno, argc, argv );
1657         }
1658
1659         if ( save_argv0 ) {
1660                 argv[0] = save_argv0;
1661         }
1662
1663         return rc;
1664 }
1665
1666 static int
1667 proxy_cache_init(
1668         BackendDB *be
1669 )
1670 {
1671         slap_overinst *on = (slap_overinst *)be->bd_info;
1672         cache_manager *cm;
1673         query_manager *qm;
1674
1675         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
1676         on->on_bi.bi_private = cm;
1677
1678         qm = (query_manager*)ch_malloc(sizeof(query_manager));
1679
1680         cm->db = *be;
1681         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
1682         cm->db.be_private = NULL;
1683         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
1684         cm->qm = qm;
1685         cm->numattrsets = 0;
1686         cm->numtemplates = 0; 
1687         cm->num_entries_limit = 5;
1688         cm->num_cached_queries = 0;
1689         cm->max_entries = 0;
1690         cm->cur_entries = 0;
1691         cm->max_queries = 10000;
1692         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1693         cm->cc_period = 1000;
1694         cm->cc_paused = 0;
1695
1696         qm->attr_sets = NULL;
1697         qm->templates = NULL;
1698         qm->lru_top = NULL;
1699         qm->lru_bottom = NULL;
1700
1701         qm->qcfunc = query_containment;
1702         qm->crfunc = cache_replacement;
1703         qm->addfunc = add_query;
1704         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
1705
1706         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
1707         ldap_pvt_thread_mutex_init(&cm->remove_mutex);
1708         return 0;
1709 }
1710
1711 static int
1712 proxy_cache_open(
1713         BackendDB *be
1714 )
1715 {
1716         slap_overinst   *on = (slap_overinst *)be->bd_info;
1717         cache_manager   *cm = on->on_bi.bi_private;
1718         int             rc = 0;
1719         int             i;
1720
1721         /* consistency check (add more...) */
1722         for ( i = 0; i < cm->numattrsets; i++ ) {
1723                 if ( cm->qm->attr_sets[i].attrs == NULL ) {
1724                         fprintf( stderr, "proxy_cache_open(): "
1725                                 "attr set %d (of %d) missing\n",
1726                                 i, cm->numattrsets );
1727                         return 1;
1728                 }
1729         }
1730
1731         /* need to inherit something from the original database... */
1732         cm->db.be_def_limit = be->be_def_limit;
1733         cm->db.be_limits = be->be_limits;
1734         cm->db.be_acl = be->be_acl;
1735         cm->db.be_dfltaccess = be->be_dfltaccess;
1736
1737         rc = backend_startup_one( &cm->db );
1738
1739         /* There is no runqueue in TOOL mode */
1740         if ( slapMode & SLAP_SERVER_MODE ) {
1741                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1742                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
1743                         consistency_check, on );
1744                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1745
1746                 /* Cached database must have the rootdn */
1747                 if ( BER_BVISNULL( &cm->db.be_rootndn )
1748                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
1749                 {
1750                         fprintf( stderr, "proxy_cache_open(): "
1751                                 "underlying database of type \"%s\"\n"
1752                                 "    serving naming context \"%s\"\n"
1753                                 "    has no \"rootdn\", required by \"proxycache\".\n",
1754                                 on->on_info->oi_orig->bi_type,
1755                                 cm->db.be_suffix[0].bv_val );
1756                         return 1;
1757                 }
1758         }
1759
1760         return rc;
1761 }
1762
1763 static int
1764 proxy_cache_close(
1765         BackendDB *be
1766 )
1767 {
1768         slap_overinst *on = (slap_overinst *)be->bd_info;
1769         cache_manager *cm = on->on_bi.bi_private;
1770         query_manager *qm = cm->qm;
1771         int i, j, rc = 0;
1772
1773         /* cleanup stuff inherited from the original database... */
1774         cm->db.be_limits = NULL;
1775         cm->db.be_acl = NULL;
1776
1777         if ( cm->db.bd_info->bi_db_close ) {
1778                 rc = cm->db.bd_info->bi_db_close( &cm->db );
1779         }
1780         for ( i=0; i<cm->numtemplates; i++ ) {
1781                 CachedQuery *qc, *qn;
1782                 for ( qc = qm->templates[i].query; qc; qc = qn ) {
1783                         qn = qc->next;
1784                         free_query( qc );
1785                 }
1786                 free( qm->templates[i].querystr.bv_val );
1787                 ldap_pvt_thread_rdwr_destroy( &qm->templates[i].t_rwlock );
1788         }
1789         free( qm->templates );
1790         qm->templates = NULL;
1791
1792         for ( i=0; i<cm->numattrsets; i++ ) {
1793                 free( qm->attr_sets[i].ID_array );
1794                 for ( j=0; j<qm->attr_sets[i].count; j++ ) {
1795                         free( qm->attr_sets[i].attrs[j].an_name.bv_val );
1796                 }
1797                 free( qm->attr_sets[i].attrs );
1798         }
1799         free( qm->attr_sets );
1800         qm->attr_sets = NULL;
1801
1802         return rc;
1803 }
1804
1805 static int
1806 proxy_cache_destroy(
1807         BackendDB *be
1808 )
1809 {
1810         slap_overinst *on = (slap_overinst *)be->bd_info;
1811         cache_manager *cm = on->on_bi.bi_private;
1812         query_manager *qm = cm->qm;
1813         int rc = 0;
1814
1815         if ( cm->db.bd_info->bi_db_destroy ) {
1816                 rc = cm->db.bd_info->bi_db_destroy( &cm->db );
1817         }
1818         ldap_pvt_thread_mutex_destroy(&qm->lru_mutex);
1819         ldap_pvt_thread_mutex_destroy(&cm->cache_mutex);
1820         ldap_pvt_thread_mutex_destroy(&cm->remove_mutex);
1821         free( qm );
1822         free( cm );
1823         return rc;
1824 }
1825
1826 static void
1827 find_supersets ( struct attr_set* attr_sets, int numsets )
1828 {
1829         int num[MAX_ATTR_SETS];
1830         int i, j, res;
1831         int* id_array;
1832         for ( i = 0; i < MAX_ATTR_SETS; i++ )
1833                 num[i] = 0;
1834
1835         for ( i = 0; i < numsets; i++ ) {
1836                 attr_sets[i].ID_array = (int*) ch_malloc( sizeof( int ) );
1837                 attr_sets[i].ID_array[0] = -1;
1838         }
1839
1840         for ( i = 0; i < numsets; i++ ) {
1841                 for ( j=i+1; j < numsets; j++ ) {
1842                         res = compare_sets( attr_sets, i, j );
1843                         switch ( res ) {
1844                         case 0:
1845                                 break;
1846                         case 3:
1847                         case 1:
1848                                 id_array = attr_sets[i].ID_array;
1849                                 attr_sets[i].ID_array = (int *) ch_realloc( id_array,
1850                                                         ( num[i] + 2 ) * sizeof( int ));
1851                                 attr_sets[i].ID_array[num[i]] = j;
1852                                 attr_sets[i].ID_array[num[i]+1] = -1;
1853                                 num[i]++;
1854                                 if (res == 1)
1855                                         break;
1856                         case 2:
1857                                 id_array = attr_sets[j].ID_array;
1858                                 attr_sets[j].ID_array = (int *) ch_realloc( id_array,
1859                                                 ( num[j] + 2 ) * sizeof( int ));
1860                                 attr_sets[j].ID_array[num[j]] = i;
1861                                 attr_sets[j].ID_array[num[j]+1] = -1;
1862                                 num[j]++;
1863                                 break;
1864                         }
1865                 }
1866         }
1867 }
1868
1869 /*
1870  * compares two sets of attributes (indices i and j)
1871  * returns 0: if neither set is contained in the other set
1872  *         1: if set i is contained in set j
1873  *         2: if set j is contained in set i
1874  *         3: the sets are equivalent
1875  */
1876
1877 static int
1878 compare_sets(struct attr_set* set, int i, int j)
1879 {
1880         int k,l,numI,numJ;
1881         int common=0;
1882         int result=0;
1883
1884         if (( set[i].attrs == NULL ) && ( set[j].attrs == NULL ))
1885                 return 3;
1886
1887         if ( set[i].attrs == NULL )
1888                 return 2;
1889
1890         if ( set[j].attrs == NULL )
1891                 return 1;
1892
1893         numI = set[i].count;
1894         numJ = set[j].count;
1895
1896         for ( l=0; l < numI; l++ ) {
1897                 for ( k = 0; k < numJ; k++ ) {
1898                         if ( strcmp( set[i].attrs[l].an_name.bv_val,
1899                                      set[j].attrs[k].an_name.bv_val ) == 0 )
1900                                 common++;
1901                 }
1902         }
1903
1904         if ( common == numI )
1905                 result = 1;
1906
1907         if ( common == numJ )
1908                 result += 2;
1909
1910         return result;
1911 }
1912
1913 static slap_overinst proxy_cache;
1914
1915 int pcache_init()
1916 {
1917         LDAPAttributeType *at;
1918         int code;
1919         const char *err;
1920
1921         at = ldap_str2attributetype( queryid_schema, &code, &err,
1922                 LDAP_SCHEMA_ALLOW_ALL );
1923         if ( !at ) {
1924                 fprintf( stderr, "AttributeType Load failed %s %s\n",
1925                         ldap_scherr2str(code), err );
1926                 return code;
1927         }
1928         code = at_add( at, &err );
1929         if ( !code ) {
1930                 slap_str2ad( at->at_names[0], &ad_queryid, &err );
1931         }
1932         ldap_memfree( at );
1933         if ( code ) {
1934                 fprintf( stderr, "AttributeType Load failed %s %s\n",
1935                         scherr2str(code), err );
1936                 return code;
1937         }
1938
1939         proxy_cache.on_bi.bi_type = "proxycache";
1940         proxy_cache.on_bi.bi_db_init = proxy_cache_init;
1941         proxy_cache.on_bi.bi_db_config = proxy_cache_config;
1942         proxy_cache.on_bi.bi_db_open = proxy_cache_open;
1943         proxy_cache.on_bi.bi_db_close = proxy_cache_close;
1944         proxy_cache.on_bi.bi_db_destroy = proxy_cache_destroy;
1945         proxy_cache.on_bi.bi_op_search = proxy_cache_search;
1946
1947         return overlay_register( &proxy_cache );
1948 }
1949
1950 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
1951 int init_module(int argc, char *argv[]) {
1952         return pcache_init();
1953 }
1954 #endif
1955
1956 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */