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