]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
s/orb_tmp_mech/orb_mech/
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003-2007 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 #include "avl.h"
35
36 #include "config.h"
37
38 /* query cache structs */
39 /* query */
40
41 typedef struct Query_s {
42         Filter*         filter;         /* Search Filter */
43         struct berval   base;           /* Search Base */
44         int             scope;          /* Search scope */
45 } Query;
46
47 struct query_template_s;
48
49 typedef struct Qbase_s {
50         Avlnode *scopes[4];             /* threaded AVL trees of cached queries */
51         struct berval base;
52         int queries;
53 } Qbase;
54
55 /* struct representing a cached query */
56 typedef struct cached_query_s {
57         Filter                                  *filter;
58         Filter                                  *first;
59         Qbase                                   *qbase;
60         int                                             scope;
61         struct berval                   q_uuid;         /* query identifier */
62         struct query_template_s         *qtemp; /* template of the query */
63         time_t                          expiry_time;    /* time till the query is considered valid */
64         struct cached_query_s           *next;          /* next query in the template */
65         struct cached_query_s           *prev;          /* previous query in the template */
66         struct cached_query_s           *lru_up;        /* previous query in the LRU list */
67         struct cached_query_s           *lru_down;      /* next query in the LRU list */
68 } CachedQuery;
69
70 /*
71  * URL representation:
72  *
73  * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
74  *
75  * <base> ::= CachedQuery.qbase->base
76  * <scope> ::= CachedQuery.scope
77  * <filter> ::= filter2bv(CachedQuery.filter)
78  * <uuid> ::= CachedQuery.q_uuid
79  * <template> ::= CachedQuery.qtemp->querystr           [FIXME: better give it an ID?]
80  * <attrset> ::= CachedQuery.qtemp->attr_set_index      [FIXME: better give it an ID?]
81  * <expiry> ::= CachedQuery.expiry_time
82  *
83  * quick hack: parse URI, call add_query() and then fix
84  * CachedQuery.expiry_time and CachedQuery.q_uuid
85  */
86
87 /*
88  * Represents a set of projected attributes.
89  */
90
91 struct attr_set {
92         struct query_template_s *templates;
93         AttributeName*  attrs;          /* specifies the set */
94         unsigned        flags;
95 #define PC_CONFIGURED   (0x1)
96 #define PC_REFERENCED   (0x2)
97 #define PC_GOT_OC               (0x4)
98         int             count;          /* number of attributes */
99 };
100
101 /* struct representing a query template
102  * e.g. template string = &(cn=)(mail=)
103  */
104 typedef struct query_template_s {
105         struct query_template_s *qtnext;
106         struct query_template_s *qmnext;
107
108         Avlnode*                qbase;
109         CachedQuery*    query;          /* most recent query cached for the template */
110         CachedQuery*    query_last;     /* oldest query cached for the template */
111         ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
112         struct berval   querystr;       /* Filter string corresponding to the QT */
113
114         int             attr_set_index; /* determines the projected attributes */
115         int             no_of_queries;  /* Total number of queries in the template */
116         time_t          ttl;            /* TTL for the queries of this template */
117         time_t          negttl;         /* TTL for negative results */
118         struct attr_set t_attrs;        /* filter attrs + attr_set */
119 } QueryTemplate;
120
121 struct query_manager_s;
122
123 /* prototypes for functions for 1) query containment
124  * 2) query addition, 3) cache replacement
125  */
126 typedef CachedQuery *   (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
127 typedef CachedQuery *   (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
128 typedef void    (CRfunc)(struct query_manager_s*, struct berval * );
129
130 /* LDAP query cache */
131 typedef struct query_manager_s {
132         struct attr_set*        attr_sets;              /* possible sets of projected attributes */
133         QueryTemplate*          templates;              /* cacheable templates */
134
135         CachedQuery*            lru_top;                /* top and bottom of LRU list */
136         CachedQuery*            lru_bottom;
137
138         ldap_pvt_thread_mutex_t         lru_mutex;      /* mutex for accessing LRU list */
139
140         /* Query cache methods */
141         QCfunc                  *qcfunc;                        /* Query containment*/
142         CRfunc                  *crfunc;                        /* cache replacement */
143         AddQueryfunc    *addfunc;                       /* add query */
144 } query_manager;
145
146 /* LDAP query cache manager */
147 typedef struct cache_manager_s {
148         BackendDB       db;     /* underlying database */
149         unsigned long   num_cached_queries;             /* total number of cached queries */
150         unsigned long   max_queries;                    /* upper bound on # of cached queries */
151         int             save_queries;                   /* save cached queries across restarts */
152         int     numattrsets;                    /* number of attribute sets */
153         int     cur_entries;                    /* current number of entries cached */
154         int     max_entries;                    /* max number of entries cached */
155         int     num_entries_limit;              /* max # of entries in a cacheable query */
156
157         char    response_cb;                    /* install the response callback
158                                                  * at the tail of the callback list */
159 #define PCACHE_RESPONSE_CB_HEAD 0
160 #define PCACHE_RESPONSE_CB_TAIL 1
161
162         time_t  cc_period;              /* interval between successive consistency checks (sec) */
163         int     cc_paused;
164         void    *cc_arg;
165
166         ldap_pvt_thread_mutex_t         cache_mutex;
167
168         query_manager*   qm;    /* query cache managed by the cache manager */
169 } cache_manager;
170
171 static int pcache_debug;
172
173 static AttributeDescription *ad_queryid, *ad_cachedQueryURL;
174 static struct {
175         char    *desc;
176         AttributeDescription **adp;
177 } as[] = {
178         { "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
179                 "DESC 'list of queries the entry belongs to' "
180                 "EQUALITY octetStringMatch "
181                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
182                 "NO-USER-MODIFICATION USAGE directoryOperation )",
183                 &ad_queryid },
184         { "(1.3.6.1.4.1.4203.666.1.999999 NAME 'cachedQueryURL' "
185                 "DESC 'URI describing a cached query' "
186                 "EQUALITY caseExactMatch "
187                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
188                 "NO-USER-MODIFICATION USAGE directoryOperation )",
189                 &ad_cachedQueryURL },
190         { NULL }
191 };
192
193 static int
194 filter2template(
195         Operation               *op,
196         Filter                  *f,
197         struct                  berval *fstr,
198         AttributeName**         filter_attrs,
199         int*                    filter_cnt,
200         int*                    filter_got_oc );
201
202 static CachedQuery *
203 add_query(
204         Operation *op,
205         query_manager* qm,
206         Query* query,
207         QueryTemplate *templ,
208         int positive);
209
210 /*
211  * Turn a cached query into its URL representation
212  */
213 static int
214 query2url( CachedQuery *q, struct berval *urlbv )
215 {
216         struct berval   bv_scope,
217                         bv_filter;
218         char            attrset_buf[ 32 ],
219                         expiry_buf[ 32 ],
220                         *ptr;
221         ber_len_t       attrset_len,
222                         expiry_len;
223
224         ldap_pvt_scope2bv( q->scope, &bv_scope );
225         filter2bv( q->filter, &bv_filter );
226         attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
227                 "%lu", (unsigned long)q->qtemp->attr_set_index );
228         expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
229                 "%lu", (unsigned long)q->expiry_time );
230
231         urlbv->bv_len = STRLENOF( "ldap:///" )
232                 + q->qbase->base.bv_len
233                 + STRLENOF( "??" )
234                 + bv_scope.bv_len
235                 + STRLENOF( "?" )
236                 + bv_filter.bv_len
237                 + STRLENOF( "?x-uuid=" )
238                 + q->q_uuid.bv_len
239                 + STRLENOF( ",x-attrset=" )
240                 + attrset_len
241                 + STRLENOF( ",x-expiry=" )
242                 + expiry_len;
243         ptr = urlbv->bv_val = ch_malloc( urlbv->bv_len + 1 );
244         ptr = lutil_strcopy( ptr, "ldap:///" );
245         ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
246         ptr = lutil_strcopy( ptr, "??" );
247         ptr = lutil_strcopy( ptr, bv_scope.bv_val );
248         ptr = lutil_strcopy( ptr, "?" );
249         ptr = lutil_strcopy( ptr, bv_filter.bv_val );
250         ptr = lutil_strcopy( ptr, "?x-uuid=" );
251         ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
252         ptr = lutil_strcopy( ptr, ",x-attrset=" );
253         ptr = lutil_strcopy( ptr, attrset_buf );
254         ptr = lutil_strcopy( ptr, ",x-expiry=" );
255         ptr = lutil_strcopy( ptr, expiry_buf );
256
257         ber_memfree( bv_filter.bv_val );
258
259         return 0;
260 }
261
262 /*
263  * Turn an URL representing a formerly cached query into a cached query,
264  * and try to cache it
265  */
266 static int
267 url2query(
268         char            *url,
269         Operation       *op,
270         query_manager   *qm )
271 {
272         Query           query = { 0 };
273         QueryTemplate   *qt;
274         CachedQuery     *cq;
275         LDAPURLDesc     *lud = NULL;
276         struct berval   base,
277                         tempstr = BER_BVNULL,
278                         uuid;
279         int             attrset;
280         time_t          expiry_time;
281         int             i,
282                         got_uuid = 0,
283                         got_attrset = 0,
284                         got_expiry = 0,
285                         rc = 0;
286
287         rc = ldap_url_parse( url, &lud );
288         if ( rc != LDAP_URL_SUCCESS ) {
289                 return -1;
290         }
291
292         /* non-allowed fields */
293         if ( lud->lud_host != NULL ) {
294                 rc = 1;
295                 goto error;
296         }
297
298         if ( lud->lud_attrs != NULL ) {
299                 rc = 1;
300                 goto error;
301         }
302
303         /* be pedantic */
304         if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
305                 rc = 1;
306                 goto error;
307         }
308
309         /* required fields */
310         if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
311                 rc = 1;
312                 goto error;
313         }
314
315         switch ( lud->lud_scope ) {
316         case LDAP_SCOPE_BASE:
317         case LDAP_SCOPE_ONELEVEL:
318         case LDAP_SCOPE_SUBTREE:
319         case LDAP_SCOPE_SUBORDINATE:
320                 break;
321
322         default:
323                 rc = 1;
324                 goto error;
325         }
326
327         if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
328                 rc = 1;
329                 goto error;
330         }
331
332         if ( lud->lud_exts == NULL ) {
333                 rc = 1;
334                 goto error;
335         }
336
337         for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
338                 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
339                         ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &uuid );
340                         if ( rc ) {
341                                 goto error;
342                         }
343                         got_uuid = 1;
344
345                 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
346                         rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
347                         if ( rc ) {
348                                 goto error;
349                         }
350                         got_attrset = 1;
351
352                 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
353                         unsigned long l;
354
355                         rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
356                         if ( rc ) {
357                                 goto error;
358                         }
359                         expiry_time = (time_t)l;
360                         got_expiry = 1;
361
362                         /* ignore expired queries */
363                         if ( expiry_time <= slap_get_time()) {
364                                 rc = 0;
365                                 goto error;
366                         }
367
368                 } else {
369                         rc = -1;
370                         goto error;
371                 }
372         }
373
374         if ( !got_uuid ) {
375                 rc = 1;
376                 goto error;
377         }
378
379         if ( !got_attrset ) {
380                 rc = 1;
381                 goto error;
382         }
383
384         if ( !got_expiry ) {
385                 rc = 1;
386                 goto error;
387         }
388
389         ber_str2bv( lud->lud_dn, 0, 0, &base );
390         rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
391         if ( rc != LDAP_SUCCESS ) {
392                 goto error;
393         }
394         query.scope = lud->lud_scope;
395         query.filter = str2filter( lud->lud_filter );
396
397         tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
398         tempstr.bv_len = 0;
399         if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
400                 ch_free( tempstr.bv_val );
401                 rc = -1;
402                 goto error;
403         }
404
405         /* check for query containment */
406         qt = qm->attr_sets[attrset].templates;
407         for ( ; qt; qt = qt->qtnext ) {
408                 /* find if template i can potentially answer tempstr */
409                 if ( bvmatch( &qt->querystr, &tempstr ) ) {
410                         break;
411                 }
412         }
413
414         if ( qt == NULL ) {
415                 rc = 1;
416                 goto error;
417         }
418
419
420         cq = add_query( op, qm, &query, qt, 1 );
421         if ( cq != NULL ) {
422                 cq->expiry_time = expiry_time;
423                 ber_dupbv( &cq->q_uuid, &uuid );
424                 /* it's now into cq->filter */
425                 query.filter = NULL;
426
427         } else {
428                 rc = 1;
429         }
430
431 error:;
432         if ( query.filter != NULL ) filter_free( query.filter );
433         if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
434         if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
435         if ( lud != NULL ) ldap_free_urldesc( lud );
436
437         return rc;
438 }
439
440 /* Return 1 for an added entry, else 0 */
441 static int
442 merge_entry(
443         Operation               *op,
444         Entry                   *e,
445         struct berval*          query_uuid )
446 {
447         int             rc;
448         Modifications* modlist = NULL;
449         const char*     text = NULL;
450         Attribute               *attr;
451         char                    textbuf[SLAP_TEXT_BUFLEN];
452         size_t                  textlen = sizeof(textbuf);
453
454         SlapReply sreply = {REP_RESULT};
455
456         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
457
458         attr = e->e_attrs;
459         e->e_attrs = NULL;
460
461         /* add queryid attribute */
462         attr_merge_one( e, ad_queryid, query_uuid, NULL );
463
464         /* append the attribute list from the fetched entry */
465         e->e_attrs->a_next = attr;
466
467         op->o_tag = LDAP_REQ_ADD;
468         op->o_protocol = LDAP_VERSION3;
469         op->o_callback = &cb;
470         op->o_time = slap_get_time();
471         op->o_do_not_cache = 1;
472
473         op->ora_e = e;
474         op->o_req_dn = e->e_name;
475         op->o_req_ndn = e->e_nname;
476         rc = op->o_bd->be_add( op, &sreply );
477
478         if ( rc != LDAP_SUCCESS ) {
479                 if ( rc == LDAP_ALREADY_EXISTS ) {
480                         slap_entry2mods( e, &modlist, &text, textbuf, textlen );
481                         modlist->sml_op = LDAP_MOD_ADD;
482                         op->o_tag = LDAP_REQ_MODIFY;
483                         op->orm_modlist = modlist;
484                         op->o_bd->be_modify( op, &sreply );
485                         slap_mods_free( modlist, 1 );
486                 } else if ( rc == LDAP_REFERRAL ||
487                                         rc == LDAP_NO_SUCH_OBJECT ) {
488                         syncrepl_add_glue( op, e );
489                         e = NULL;
490                         rc = 1;
491                 }
492                 if ( e ) {
493                         entry_free( e );
494                         rc = 0;
495                 }
496         } else {
497                 if ( op->ora_e == e )
498                         be_entry_release_w( op, e );
499                 rc = 1;
500         }
501
502         return rc;
503 }
504
505 /* Length-ordered sort on normalized DNs */
506 static int pcache_dn_cmp( const void *v1, const void *v2 )
507 {
508         const Qbase *q1 = v1, *q2 = v2;
509
510         int rc = q1->base.bv_len - q2->base.bv_len;
511         if ( rc == 0 )
512                 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
513         return rc;
514 }
515
516 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
517 {
518         int len, dif;
519         dif = bv1->bv_len - bv2->bv_len;
520         len = bv1->bv_len;
521         if ( dif > 0 ) len -= dif;
522         len = memcmp( bv1->bv_val, bv2->bv_val, len );
523         if ( !len )
524                 len = dif;
525         return len;
526 }
527
528 /* compare the first value in each filter */
529 static int pcache_filter_cmp( const void *v1, const void *v2 )
530 {
531         const CachedQuery *q1 = v1, *q2 =v2;
532         int rc, weight1, weight2;
533
534         switch( q1->first->f_choice ) {
535         case LDAP_FILTER_PRESENT:
536                 weight1 = 0;
537                 break;
538         case LDAP_FILTER_EQUALITY:
539         case LDAP_FILTER_GE:
540         case LDAP_FILTER_LE:
541                 weight1 = 1;
542                 break;
543         default:
544                 weight1 = 2;
545         }
546         switch( q2->first->f_choice ) {
547         case LDAP_FILTER_PRESENT:
548                 weight2 = 0;
549                 break;
550         case LDAP_FILTER_EQUALITY:
551         case LDAP_FILTER_GE:
552         case LDAP_FILTER_LE:
553                 weight2 = 1;
554                 break;
555         default:
556                 weight2 = 2;
557         }
558         rc = weight1 - weight2;
559         if ( !rc ) {
560                 switch( weight1 ) {
561                 case 0: return 0;
562                 case 1:
563                         rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
564                         break;
565                 case 2:
566                         if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
567                                 rc = 0;
568                                 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
569                                         if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
570                                                 rc = lex_bvcmp( &q1->first->f_sub_initial,
571                                                         &q2->first->f_sub_initial );
572                                         } else {
573                                                 rc = 1;
574                                         }
575                                 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
576                                         rc = -1;
577                                 }
578                                 if ( rc ) break;
579                                 if ( q1->first->f_sub_any ) {
580                                         if ( q2->first->f_sub_any ) {
581                                                 rc = lex_bvcmp( q1->first->f_sub_any,
582                                                         q2->first->f_sub_any );
583                                         } else {
584                                                 rc = 1;
585                                         }
586                                 } else if ( q2->first->f_sub_any ) {
587                                         rc = -1;
588                                 }
589                                 if ( rc ) break;
590                                 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
591                                         if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
592                                                 rc = lex_bvcmp( &q1->first->f_sub_final,
593                                                         &q2->first->f_sub_final );
594                                         } else {
595                                                 rc = 1;
596                                         }
597                                 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
598                                         rc = -1;
599                                 }
600                         } else {
601                                 rc = lex_bvcmp( &q1->first->f_mr_value,
602                                         &q2->first->f_mr_value );
603                         }
604                         break;
605                 }
606         }
607
608         return rc;
609 }
610
611 /* add query on top of LRU list */
612 static void
613 add_query_on_top (query_manager* qm, CachedQuery* qc)
614 {
615         CachedQuery* top = qm->lru_top;
616
617         qm->lru_top = qc;
618
619         if (top)
620                 top->lru_up = qc;
621         else
622                 qm->lru_bottom = qc;
623
624         qc->lru_down = top;
625         qc->lru_up = NULL;
626         Debug( pcache_debug, "Base of added query = %s\n",
627                         qc->qbase->base.bv_val, 0, 0 );
628 }
629
630 /* remove_query from LRU list */
631
632 static void
633 remove_query (query_manager* qm, CachedQuery* qc)
634 {
635         CachedQuery* up;
636         CachedQuery* down;
637
638         if (!qc)
639                 return;
640
641         up = qc->lru_up;
642         down = qc->lru_down;
643
644         if (!up)
645                 qm->lru_top = down;
646
647         if (!down)
648                 qm->lru_bottom = up;
649
650         if (down)
651                 down->lru_up = up;
652
653         if (up)
654                 up->lru_down = down;
655
656         qc->lru_up = qc->lru_down = NULL;
657 }
658
659 /* find and remove string2 from string1
660  * from start if position = 1,
661  * from end if position = 3,
662  * from anywhere if position = 2
663  * string1 is overwritten if position = 2.
664  */
665
666 static int
667 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
668 {
669         int ret=0;
670
671         if ( !ber2->bv_val )
672                 return 1;
673         if ( !ber1->bv_val )
674                 return 0;
675
676         switch( position ) {
677         case 1:
678                 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
679                         ber2->bv_val, ber2->bv_len )) {
680                         ret = 1;
681                         ber1->bv_val += ber2->bv_len;
682                         ber1->bv_len -= ber2->bv_len;
683                 }
684                 break;
685         case 2: {
686                 char *temp;
687                 ber1->bv_val[ber1->bv_len] = '\0';
688                 temp = strstr( ber1->bv_val, ber2->bv_val );
689                 if ( temp ) {
690                         strcpy( temp, temp+ber2->bv_len );
691                         ber1->bv_len -= ber2->bv_len;
692                         ret = 1;
693                 }
694                 break;
695                 }
696         case 3:
697                 if ( ber1->bv_len >= ber2->bv_len &&
698                         !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
699                                 ber2->bv_len )) {
700                         ret = 1;
701                         ber1->bv_len -= ber2->bv_len;
702                 }
703                 break;
704         }
705         return ret;
706 }
707
708
709 static struct berval*
710 merge_init_final(Operation *op, struct berval* init, struct berval* any,
711         struct berval* final)
712 {
713         struct berval* merged, *temp;
714         int i, any_count, count;
715
716         for (any_count=0; any && any[any_count].bv_val; any_count++)
717                 ;
718
719         count = any_count;
720
721         if (init->bv_val)
722                 count++;
723         if (final->bv_val)
724                 count++;
725
726         merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
727                 op->o_tmpmemctx );
728         temp = merged;
729
730         if (init->bv_val) {
731                 ber_dupbv_x( temp, init, op->o_tmpmemctx );
732                 temp++;
733         }
734
735         for (i=0; i<any_count; i++) {
736                 ber_dupbv_x( temp, any, op->o_tmpmemctx );
737                 temp++; any++;
738         }
739
740         if (final->bv_val){
741                 ber_dupbv_x( temp, final, op->o_tmpmemctx );
742                 temp++;
743         }
744         BER_BVZERO( temp );
745         return merged;
746 }
747
748 /* Each element in stored must be found in incoming. Incoming is overwritten.
749  */
750 static int
751 strings_containment(struct berval* stored, struct berval* incoming)
752 {
753         struct berval* element;
754         int k=0;
755         int j, rc = 0;
756
757         for ( element=stored; element->bv_val != NULL; element++ ) {
758                 for (j = k; incoming[j].bv_val != NULL; j++) {
759                         if (find_and_remove(&(incoming[j]), element, 2)) {
760                                 k = j;
761                                 rc = 1;
762                                 break;
763                         }
764                         rc = 0;
765                 }
766                 if ( rc ) {
767                         continue;
768                 } else {
769                         return 0;
770                 }
771         }
772         return 1;
773 }
774
775 static int
776 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
777 {
778         int rc = 0;
779
780         struct berval init_incoming;
781         struct berval final_incoming;
782         struct berval *remaining_incoming = NULL;
783
784         if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
785            || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
786                 return 0;
787
788         init_incoming = incoming->f_sub_initial;
789         final_incoming =  incoming->f_sub_final;
790
791         if (find_and_remove(&init_incoming,
792                         &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
793                         &(stored->f_sub_final), 3))
794         {
795                 if (stored->f_sub_any == NULL) {
796                         rc = 1;
797                         goto final;
798                 }
799                 remaining_incoming = merge_init_final(op, &init_incoming,
800                                                 incoming->f_sub_any, &final_incoming);
801                 rc = strings_containment(stored->f_sub_any, remaining_incoming);
802                 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
803         }
804 final:
805         return rc;
806 }
807
808 static int
809 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
810 {
811         struct berval incoming_val[2];
812         int rc = 0;
813
814         incoming_val[1] = incoming->f_av_value;
815
816         if (find_and_remove(incoming_val+1,
817                         &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
818                         &(stored->f_sub_final), 3)) {
819                 if (stored->f_sub_any == NULL){
820                         rc = 1;
821                         goto final;
822                 }
823                 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
824                 BER_BVZERO( incoming_val+1 );
825                 rc = strings_containment(stored->f_sub_any, incoming_val);
826                 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
827         }
828 final:
829         return rc;
830 }
831
832 static Filter *
833 filter_first( Filter *f )
834 {
835         while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
836                 f = f->f_and;
837         return f;
838 }
839
840
841 static CachedQuery *
842 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
843 {
844         Filter* fs;
845         Filter* fi;
846         MatchingRule* mrule = NULL;
847         int res=0, eqpass= 0;
848         int ret, rc, dir;
849         Avlnode *ptr;
850         CachedQuery cq, *qc;
851
852         cq.filter = inputf;
853         cq.first = first;
854
855         /* substring matches sort to the end, and we just have to
856          * walk the entire list.
857          */
858         if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
859                 ptr = tavl_end( root, 1 );
860                 dir = TAVL_DIR_LEFT;
861         } else {
862                 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
863                 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
864                         TAVL_DIR_RIGHT;
865         }
866
867         while (ptr) {
868                 qc = ptr->avl_data;
869                 fi = inputf;
870                 fs = qc->filter;
871
872                 /* an incoming substr query can only be satisfied by a cached
873                  * substr query.
874                  */
875                 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
876                         qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
877                         break;
878
879                 /* an incoming eq query can be satisfied by a cached eq or substr
880                  * query
881                  */
882                 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
883                         if ( eqpass == 0 ) {
884                                 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
885 nextpass:                       eqpass = 1;
886                                         ptr = tavl_end( root, 1 );
887                                         dir = TAVL_DIR_LEFT;
888                                         continue;
889                                 }
890                         } else {
891                                 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
892                                         break;
893                         }
894                 }
895                 do {
896                         res=0;
897                         switch (fs->f_choice) {
898                         case LDAP_FILTER_EQUALITY:
899                                 if (fi->f_choice == LDAP_FILTER_EQUALITY)
900                                         mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
901                                 else
902                                         ret = 1;
903                                 break;
904                         case LDAP_FILTER_GE:
905                         case LDAP_FILTER_LE:
906                                 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
907                                 break;
908                         default:
909                                 mrule = NULL; 
910                         }
911                         if (mrule) {
912                                 const char *text;
913                                 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
914                                         SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
915                                         &(fi->f_ava->aa_value),
916                                         &(fs->f_ava->aa_value), &text);
917                                 if (rc != LDAP_SUCCESS) {
918                                         return NULL;
919                                 }
920                                 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
921                                         goto nextpass;
922                         }
923                         switch (fs->f_choice) {
924                         case LDAP_FILTER_OR:
925                         case LDAP_FILTER_AND:
926                                 fs = fs->f_and;
927                                 fi = fi->f_and;
928                                 res=1;
929                                 break;
930                         case LDAP_FILTER_SUBSTRINGS:
931                                 /* check if the equality query can be
932                                 * answered with cached substring query */
933                                 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
934                                         && substr_containment_equality( op,
935                                         fs, fi))
936                                         res=1;
937                                 /* check if the substring query can be
938                                 * answered with cached substring query */
939                                 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
940                                         ) && substr_containment_substr( op,
941                                         fs, fi))
942                                         res= 1;
943                                 fs=fs->f_next;
944                                 fi=fi->f_next;
945                                 break;
946                         case LDAP_FILTER_PRESENT:
947                                 res=1;
948                                 fs=fs->f_next;
949                                 fi=fi->f_next;
950                                 break;
951                         case LDAP_FILTER_EQUALITY:
952                                 if (ret == 0)
953                                         res = 1;
954                                 fs=fs->f_next;
955                                 fi=fi->f_next;
956                                 break;
957                         case LDAP_FILTER_GE:
958                                 if (mrule && ret >= 0)
959                                         res = 1;
960                                 fs=fs->f_next;
961                                 fi=fi->f_next;
962                                 break;
963                         case LDAP_FILTER_LE:
964                                 if (mrule && ret <= 0)
965                                         res = 1;
966                                 fs=fs->f_next;
967                                 fi=fi->f_next;
968                                 break;
969                         case LDAP_FILTER_NOT:
970                                 res=0;
971                                 break;
972                         default:
973                                 break;
974                         }
975                 } while((res) && (fi != NULL) && (fs != NULL));
976
977                 if ( res )
978                         return qc;
979                 ptr = tavl_next( ptr, dir );
980         }
981         return NULL;
982 }
983
984 /* check whether query is contained in any of
985  * the cached queries in template
986  */
987 static CachedQuery *
988 query_containment(Operation *op, query_manager *qm,
989                   Query *query,
990                   QueryTemplate *templa)
991 {
992         CachedQuery* qc;
993         int depth = 0, tscope;
994         Qbase qbase, *qbptr = NULL;
995         struct berval pdn;
996
997         if (query->filter != NULL) {
998                 Filter *first;
999
1000                 Debug( pcache_debug, "Lock QC index = %p\n",
1001                                 (void *) templa, 0, 0 );
1002                 qbase.base = query->base;
1003
1004                 first = filter_first( query->filter );
1005
1006                 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1007                 for( ;; ) {
1008                         /* Find the base */
1009                         qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1010                         if ( qbptr ) {
1011                                 tscope = query->scope;
1012                                 /* Find a matching scope:
1013                                  * match at depth 0 OK
1014                                  * scope is BASE,
1015                                  *      one at depth 1 OK
1016                                  *  subord at depth > 0 OK
1017                                  *      subtree at any depth OK
1018                                  * scope is ONE,
1019                                  *  subtree or subord at any depth OK
1020                                  * scope is SUBORD,
1021                                  *  subtree or subord at any depth OK
1022                                  * scope is SUBTREE,
1023                                  *  subord at depth > 0 OK
1024                                  *  subtree at any depth OK
1025                                  */
1026                                 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1027                                         switch ( query->scope ) {
1028                                         case LDAP_SCOPE_BASE:
1029                                                 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1030                                                 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1031                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1032                                                 break;
1033                                         case LDAP_SCOPE_ONE:
1034                                                 if ( tscope == LDAP_SCOPE_BASE )
1035                                                         tscope = LDAP_SCOPE_ONE;
1036                                                 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1037                                                 if ( !depth ) break;
1038                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1039                                                         tscope = LDAP_SCOPE_SUBTREE;
1040                                                 break;
1041                                         case LDAP_SCOPE_SUBTREE:
1042                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1043                                                         tscope = LDAP_SCOPE_SUBTREE;
1044                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1045                                                 break;
1046                                         case LDAP_SCOPE_CHILDREN:
1047                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1048                                                         tscope = LDAP_SCOPE_SUBTREE;
1049                                                 break;
1050                                         }
1051                                         if ( !qbptr->scopes[tscope] ) continue;
1052
1053                                         /* Find filter */
1054                                         qc = find_filter( op, qbptr->scopes[tscope],
1055                                                         query->filter, first );
1056                                         if ( qc ) {
1057                                                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1058                                                 if (qm->lru_top != qc) {
1059                                                         remove_query(qm, qc);
1060                                                         add_query_on_top(qm, qc);
1061                                                 }
1062                                                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1063                                                 return qc;
1064                                         }
1065                                 }
1066                         }
1067                         if ( be_issuffix( op->o_bd, &qbase.base ))
1068                                 break;
1069                         /* Up a level */
1070                         dnParent( &qbase.base, &pdn );
1071                         qbase.base = pdn;
1072                         depth++;
1073                 }
1074
1075                 Debug( pcache_debug,
1076                         "Not answerable: Unlock QC index=%p\n",
1077                         (void *) templa, 0, 0 );
1078                 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1079         }
1080         return NULL;
1081 }
1082
1083 static void
1084 free_query (CachedQuery* qc)
1085 {
1086         free(qc->q_uuid.bv_val);
1087         filter_free(qc->filter);
1088         free(qc);
1089 }
1090
1091
1092 /* Add query to query cache */
1093 static CachedQuery *
1094 add_query(
1095         Operation *op,
1096         query_manager* qm,
1097         Query* query,
1098         QueryTemplate *templ,
1099         int positive)
1100 {
1101         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1102         Qbase *qbase, qb;
1103         Filter *first;
1104         int rc;
1105
1106         new_cached_query->qtemp = templ;
1107         BER_BVZERO( &new_cached_query->q_uuid );
1108         if ( positive ) {
1109                 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1110         } else {
1111                 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1112         }
1113         new_cached_query->lru_up = NULL;
1114         new_cached_query->lru_down = NULL;
1115         Debug( pcache_debug, "Added query expires at %ld\n",
1116                         (long) new_cached_query->expiry_time, 0, 0 );
1117
1118         new_cached_query->scope = query->scope;
1119         new_cached_query->filter = query->filter;
1120         new_cached_query->first = first = filter_first( query->filter );
1121
1122         qb.base = query->base;
1123
1124         /* Adding a query    */
1125         Debug( pcache_debug, "Lock AQ index = %p\n",
1126                         (void *) templ, 0, 0 );
1127         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1128         qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1129         if ( !qbase ) {
1130                 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1131                 qbase->base.bv_len = qb.base.bv_len;
1132                 qbase->base.bv_val = (char *)(qbase+1);
1133                 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1134                 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1135                 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1136         }
1137         new_cached_query->next = templ->query;
1138         new_cached_query->prev = NULL;
1139         new_cached_query->qbase = qbase;
1140         rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1141                 pcache_filter_cmp, avl_dup_error );
1142         if ( rc == 0 ) {
1143                 qbase->queries++;
1144                 if (templ->query == NULL)
1145                         templ->query_last = new_cached_query;
1146                 else
1147                         templ->query->prev = new_cached_query;
1148                 templ->query = new_cached_query;
1149                 templ->no_of_queries++;
1150         } else {
1151                 ch_free( new_cached_query );
1152                 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1153                                                         query->filter, first );
1154                 filter_free( query->filter );
1155         }
1156         Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1157                         (void *) templ, templ->no_of_queries, 0 );
1158
1159         Debug( pcache_debug, "Unlock AQ index = %p \n",
1160                         (void *) templ, 0, 0 );
1161         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1162
1163         /* Adding on top of LRU list  */
1164         if ( rc == 0 ) {
1165                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1166                 add_query_on_top(qm, new_cached_query);
1167                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1168         }
1169         return rc == 0 ? new_cached_query : NULL;
1170 }
1171
1172 static void
1173 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1174 {
1175         if (!qc->prev && !qc->next) {
1176                 template->query_last = template->query = NULL;
1177         } else if (qc->prev == NULL) {
1178                 qc->next->prev = NULL;
1179                 template->query = qc->next;
1180         } else if (qc->next == NULL) {
1181                 qc->prev->next = NULL;
1182                 template->query_last = qc->prev;
1183         } else {
1184                 qc->next->prev = qc->prev;
1185                 qc->prev->next = qc->next;
1186         }
1187         tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1188         qc->qbase->queries--;
1189         if ( qc->qbase->queries == 0 ) {
1190                 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1191                 ch_free( qc->qbase );
1192                 qc->qbase = NULL;
1193         }
1194
1195         template->no_of_queries--;
1196 }
1197
1198 /* remove bottom query of LRU list from the query cache */
1199 /*
1200  * NOTE: slight change in functionality.
1201  *
1202  * - if result->bv_val is NULL, the query at the bottom of the LRU
1203  *   is removed
1204  * - otherwise, the query whose UUID is *result is removed
1205  *      - if not found, result->bv_val is zeroed
1206  */
1207 static void
1208 cache_replacement(query_manager* qm, struct berval *result)
1209 {
1210         CachedQuery* bottom;
1211         QueryTemplate *temp;
1212
1213         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1214         if ( BER_BVISNULL( result ) ) {
1215                 bottom = qm->lru_bottom;
1216
1217                 if (!bottom) {
1218                         Debug ( pcache_debug,
1219                                 "Cache replacement invoked without "
1220                                 "any query in LRU list\n", 0, 0, 0 );
1221                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1222                         return;
1223                 }
1224
1225         } else {
1226                 for ( bottom = qm->lru_bottom;
1227                         bottom != NULL;
1228                         bottom = bottom->lru_up )
1229                 {
1230                         if ( bvmatch( result, &bottom->q_uuid ) ) {
1231                                 break;
1232                         }
1233                 }
1234
1235                 if ( !bottom ) {
1236                         Debug ( pcache_debug,
1237                                 "Could not find query with uuid=\"%s\""
1238                                 "in LRU list\n", result->bv_val, 0, 0 );
1239                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1240                         BER_BVZERO( result );
1241                         return;
1242                 }
1243         }
1244
1245         temp = bottom->qtemp;
1246         remove_query(qm, bottom);
1247         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1248
1249         *result = bottom->q_uuid;
1250         bottom->q_uuid.bv_val = NULL;
1251
1252         Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1253         ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1254         remove_from_template(bottom, temp);
1255         Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1256                 (void *) temp, temp->no_of_queries, 0 );
1257         Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1258         ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1259         free_query(bottom);
1260 }
1261
1262 struct query_info {
1263         struct query_info *next;
1264         struct berval xdn;
1265         int del;
1266 };
1267
1268 static int
1269 remove_func (
1270         Operation       *op,
1271         SlapReply       *rs
1272 )
1273 {
1274         Attribute *attr;
1275         struct query_info *qi;
1276         int count = 0;
1277
1278         if ( rs->sr_type != REP_SEARCH ) return 0;
1279
1280         attr = attr_find( rs->sr_entry->e_attrs,  ad_queryid );
1281         if ( attr == NULL ) return 0;
1282
1283         for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1284                 ;
1285         assert( count > 0 );
1286         qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1287         qi->next = op->o_callback->sc_private;
1288         op->o_callback->sc_private = qi;
1289         ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1290         qi->del = ( count == 1 );
1291
1292         return 0;
1293 }
1294
1295 static int
1296 remove_query_data (
1297         Operation       *op,
1298         SlapReply       *rs,
1299         struct berval* query_uuid)
1300 {
1301         struct query_info       *qi, *qnext;
1302         char                    filter_str[64];
1303 #ifdef LDAP_COMP_MATCH
1304         AttributeAssertion      ava = { NULL, BER_BVNULL, NULL };
1305 #else
1306         AttributeAssertion      ava = { NULL, BER_BVNULL };
1307 #endif
1308         Filter                  filter = {LDAP_FILTER_EQUALITY};
1309         SlapReply               sreply = {REP_RESULT};
1310         slap_callback cb = { NULL, remove_func, NULL, NULL };
1311         int deleted = 0;
1312
1313         sreply.sr_entry = NULL;
1314         sreply.sr_nentries = 0;
1315         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1316                 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
1317         filter.f_ava = &ava;
1318         filter.f_av_desc = ad_queryid;
1319         filter.f_av_value = *query_uuid;
1320
1321         op->o_tag = LDAP_REQ_SEARCH;
1322         op->o_protocol = LDAP_VERSION3;
1323         op->o_callback = &cb;
1324         op->o_time = slap_get_time();
1325         op->o_do_not_cache = 1;
1326
1327         op->o_req_dn = op->o_bd->be_suffix[0];
1328         op->o_req_ndn = op->o_bd->be_nsuffix[0];
1329         op->ors_scope = LDAP_SCOPE_SUBTREE;
1330         op->ors_deref = LDAP_DEREF_NEVER;
1331         op->ors_slimit = SLAP_NO_LIMIT;
1332         op->ors_tlimit = SLAP_NO_LIMIT;
1333         op->ors_filter = &filter;
1334         op->ors_filterstr.bv_val = filter_str;
1335         op->ors_filterstr.bv_len = strlen(filter_str);
1336         op->ors_attrs = NULL;
1337         op->ors_attrsonly = 0;
1338
1339         op->o_bd->be_search( op, &sreply );
1340
1341         for ( qi=cb.sc_private; qi; qi=qnext ) {
1342                 qnext = qi->next;
1343
1344                 op->o_req_dn = qi->xdn;
1345                 op->o_req_ndn = qi->xdn;
1346
1347                 if ( qi->del) {
1348                         Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1349                                 query_uuid->bv_val, 0, 0 );
1350
1351                         op->o_tag = LDAP_REQ_DELETE;
1352
1353                         if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1354                                 deleted++;
1355                         }
1356                 } else {
1357                         Modifications mod;
1358                         struct berval vals[2];
1359
1360                         vals[0] = *query_uuid;
1361                         vals[1].bv_val = NULL;
1362                         vals[1].bv_len = 0;
1363                         mod.sml_op = LDAP_MOD_DELETE;
1364                         mod.sml_flags = 0;
1365                         mod.sml_desc = ad_queryid;
1366                         mod.sml_type = ad_queryid->ad_cname;
1367                         mod.sml_values = vals;
1368                         mod.sml_nvalues = NULL;
1369                         mod.sml_next = NULL;
1370                         Debug( pcache_debug,
1371                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1372                                 query_uuid->bv_val, 0, 0 );
1373
1374                         op->orm_modlist = &mod;
1375
1376                         op->o_bd->be_modify( op, &sreply );
1377                 }
1378                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1379                 op->o_tmpfree( qi, op->o_tmpmemctx );
1380         }
1381         return deleted;
1382 }
1383
1384 static int
1385 get_attr_set(
1386         AttributeName* attrs,
1387         query_manager* qm,
1388         int num
1389 );
1390
1391 static int
1392 filter2template(
1393         Operation               *op,
1394         Filter                  *f,
1395         struct                  berval *fstr,
1396         AttributeName**         filter_attrs,
1397         int*                    filter_cnt,
1398         int*                    filter_got_oc )
1399 {
1400         AttributeDescription *ad;
1401
1402         switch ( f->f_choice ) {
1403         case LDAP_FILTER_EQUALITY:
1404                 ad = f->f_av_desc;
1405                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1406                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1407                 break;
1408
1409         case LDAP_FILTER_GE:
1410                 ad = f->f_av_desc;
1411                 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1412                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1413                 break;
1414
1415         case LDAP_FILTER_LE:
1416                 ad = f->f_av_desc;
1417                 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1418                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1419                 break;
1420
1421         case LDAP_FILTER_APPROX:
1422                 ad = f->f_av_desc;
1423                 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1424                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1425                 break;
1426
1427         case LDAP_FILTER_SUBSTRINGS:
1428                 ad = f->f_sub_desc;
1429                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1430                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1431                 break;
1432
1433         case LDAP_FILTER_PRESENT:
1434                 ad = f->f_desc;
1435                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1436                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1437                 break;
1438
1439         case LDAP_FILTER_AND:
1440         case LDAP_FILTER_OR:
1441         case LDAP_FILTER_NOT: {
1442                 int rc = 0;
1443                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1444                         f->f_choice == LDAP_FILTER_AND ? '&' :
1445                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1446                 fstr->bv_len += sizeof("(%") - 1;
1447
1448                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1449                         rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1450                                 filter_got_oc );
1451                         if ( rc ) break;
1452                 }
1453                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1454                 fstr->bv_len += sizeof(")") - 1;
1455
1456                 return rc;
1457                 }
1458
1459         default:
1460                 strcpy( fstr->bv_val, "(?=?)" );
1461                 fstr->bv_len += sizeof("(?=?)")-1;
1462                 return -1;
1463         }
1464
1465         if ( filter_attrs != NULL ) {
1466                 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1467                                 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1468
1469                 (*filter_attrs)[*filter_cnt].an_desc = ad;
1470                 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1471                 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1472                 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1473                 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1474                 (*filter_cnt)++;
1475                 if ( ad == slap_schema.si_ad_objectClass )
1476                         *filter_got_oc = 1;
1477         }
1478
1479         return 0;
1480 }
1481
1482 struct search_info {
1483         slap_overinst *on;
1484         Query query;
1485         QueryTemplate *qtemp;
1486         AttributeName*  save_attrs;     /* original attributes, saved for response */
1487         int max;
1488         int over;
1489         int count;
1490         Entry *head, *tail;
1491 };
1492
1493 static int
1494 remove_query_and_data(
1495         Operation       *op,
1496         SlapReply       *rs,
1497         cache_manager   *cm,
1498         struct berval   *uuid )
1499 {
1500         query_manager*          qm = cm->qm;
1501
1502         qm->crfunc( qm, uuid );
1503         if ( !BER_BVISNULL( uuid ) ) {
1504                 int     return_val;
1505
1506                 Debug( pcache_debug,
1507                         "Removing query UUID %s\n",
1508                         uuid->bv_val, 0, 0 );
1509                 return_val = remove_query_data( op, rs, uuid );
1510                 Debug( pcache_debug,
1511                         "QUERY REMOVED, SIZE=%d\n",
1512                         return_val, 0, 0);
1513                 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1514                 cm->cur_entries -= return_val;
1515                 cm->num_cached_queries--;
1516                 Debug( pcache_debug,
1517                         "STORED QUERIES = %lu\n",
1518                         cm->num_cached_queries, 0, 0 );
1519                 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1520                 Debug( pcache_debug,
1521                         "QUERY REMOVED, CACHE ="
1522                         "%d entries\n",
1523                         cm->cur_entries, 0, 0 );
1524         }
1525 }
1526
1527 /*
1528  * Callback used to fetch queryid values based on entryUUID;
1529  * used by pcache_remove_entries_from_cache()
1530  */
1531 static int
1532 fetch_queryid_cb( Operation *op, SlapReply *rs )
1533 {
1534         int             rc = 0;
1535
1536         /* only care about searchEntry responses */
1537         if ( rs->sr_type != REP_SEARCH ) {
1538                 return 0;
1539         }
1540
1541         /* allow only one response per entryUUID */
1542         if ( op->o_callback->sc_private != NULL ) {
1543                 rc = 1;
1544
1545         } else {
1546                 Attribute       *a;
1547
1548                 /* copy all queryid values into callback's private data */
1549                 a = attr_find( rs->sr_entry->e_attrs, ad_queryid );
1550                 if ( a != NULL ) {
1551                         BerVarray       vals = NULL;
1552
1553                         ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1554                         op->o_callback->sc_private = (void *)vals;
1555                 }
1556         }
1557
1558         /* clear entry if required */
1559         if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1560                 entry_free( rs->sr_entry );
1561                 rs->sr_entry = NULL;
1562                 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1563         }
1564
1565         return rc;
1566 }
1567
1568 /*
1569  * Call that allows to remove an entry from the cache, by forcing
1570  * the removal of all the related queries.
1571  */
1572 int
1573 pcache_remove_entries_from_cache(
1574         cache_manager           *cm,
1575         BerVarray               UUIDs )
1576 {
1577         void            *thrctx = ldap_pvt_thread_pool_context();
1578
1579         Connection      conn = { 0 };
1580         OperationBuffer opbuf;
1581         Operation       *op;
1582         slap_callback   sc = { 0 };
1583         SlapReply       rs = { REP_RESULT };
1584         Filter          f = { 0 };
1585         char            filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1586 #ifdef LDAP_COMP_MATCH
1587         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1588 #else
1589         AttributeAssertion ava = { NULL, BER_BVNULL };
1590 #endif
1591         AttributeName   attrs[ 2 ] = { 0 };
1592         int             s, rc;
1593
1594         connection_fake_init( &conn, &opbuf, thrctx );
1595         op = &opbuf.ob_op;
1596
1597         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1598         op->ors_scope = LDAP_SCOPE_SUBTREE;
1599         op->ors_deref = LDAP_DEREF_NEVER;
1600         f.f_choice = LDAP_FILTER_EQUALITY;
1601         f.f_ava = &ava;
1602         ava.aa_desc = slap_schema.si_ad_entryUUID;
1603         op->ors_filter = &f;
1604         op->ors_slimit = 1;
1605         op->ors_tlimit = SLAP_NO_LIMIT;
1606         attrs[ 0 ].an_desc = ad_queryid;
1607         attrs[ 0 ].an_name = ad_queryid->ad_cname;
1608         op->ors_attrs = attrs;
1609         op->ors_attrsonly = 0;
1610
1611         op->o_req_dn = cm->db.be_suffix[ 0 ];
1612         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1613
1614         op->o_tag = LDAP_REQ_SEARCH;
1615         op->o_protocol = LDAP_VERSION3;
1616         op->o_managedsait = SLAP_CONTROL_CRITICAL;
1617         op->o_bd = &cm->db;
1618         op->o_dn = op->o_bd->be_rootdn;
1619         op->o_ndn = op->o_bd->be_rootndn;
1620         sc.sc_response = fetch_queryid_cb;
1621         op->o_callback = &sc;
1622
1623         for ( s = 0; !BER_BVISNULL( &UUIDs[ s ] ); s++ ) {
1624                 BerVarray       vals = NULL;
1625                 int             i;
1626
1627                 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1628                         "(entryUUID=%s)", UUIDs[ s ].bv_val );
1629                 op->ors_filterstr.bv_val = filtbuf;
1630                 ava.aa_value = UUIDs[ s ];
1631
1632                 rc = op->o_bd->be_search( op, &rs );
1633                 if ( rc != LDAP_SUCCESS ) {
1634                         continue;
1635                 }
1636
1637                 vals = (BerVarray)op->o_callback->sc_private;
1638                 if ( vals != NULL ) {
1639                         for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1640                                 struct berval   val = vals[ i ];
1641
1642                                 remove_query_and_data( op, &rs, cm, &val );
1643
1644                                 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1645                                         ch_free( val.bv_val );
1646                                 }
1647                         }
1648
1649                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1650                         op->o_callback->sc_private = NULL;
1651                 }
1652         }
1653
1654         return 0;
1655 }
1656
1657 static int
1658 cache_entries(
1659         Operation       *op,
1660         SlapReply       *rs,
1661         struct berval *query_uuid)
1662 {
1663         struct search_info *si = op->o_callback->sc_private;
1664         slap_overinst *on = si->on;
1665         cache_manager *cm = on->on_bi.bi_private;
1666         query_manager*          qm = cm->qm;
1667         int             return_val = 0;
1668         Entry           *e;
1669         struct berval   crp_uuid;
1670         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1671         Operation op_tmp = *op;
1672
1673         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1674         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1675
1676         op_tmp.o_bd = &cm->db;
1677         op_tmp.o_dn = cm->db.be_rootdn;
1678         op_tmp.o_ndn = cm->db.be_rootndn;
1679
1680         Debug( pcache_debug, "UUID for query being added = %s\n",
1681                         uuidbuf, 0, 0 );
1682
1683         for ( e=si->head; e; e=si->head ) {
1684                 si->head = e->e_private;
1685                 e->e_private = NULL;
1686                 while ( cm->cur_entries > (cm->max_entries) ) {
1687                         BER_BVZERO( &crp_uuid );
1688                         remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1689                 }
1690
1691                 return_val = merge_entry(&op_tmp, e, query_uuid);
1692                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1693                 cm->cur_entries += return_val;
1694                 Debug( pcache_debug,
1695                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1696                         cm->cur_entries, 0, 0 );
1697                 return_val = 0;
1698                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1699         }
1700
1701         return return_val;
1702 }
1703
1704 static int
1705 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1706         slap_callback   *cb = op->o_callback;
1707         struct search_info *si = cb->sc_private;
1708         if ( si->save_attrs != NULL ) {
1709                 rs->sr_attrs = si->save_attrs;
1710                 op->ors_attrs = si->save_attrs;
1711         }
1712         op->o_callback = op->o_callback->sc_next;
1713         op->o_tmpfree( cb, op->o_tmpmemctx );
1714         return SLAP_CB_CONTINUE;
1715 }
1716
1717 static int
1718 pcache_response(
1719         Operation       *op,
1720         SlapReply       *rs )
1721 {
1722         struct search_info *si = op->o_callback->sc_private;
1723         slap_overinst *on = si->on;
1724         cache_manager *cm = on->on_bi.bi_private;
1725         query_manager*          qm = cm->qm;
1726
1727         if ( si->save_attrs != NULL ) {
1728                 rs->sr_attrs = si->save_attrs;
1729                 op->ors_attrs = si->save_attrs;
1730         }
1731
1732         if ( rs->sr_type == REP_SEARCH ) {
1733                 Entry *e;
1734                 /* If we haven't exceeded the limit for this query,
1735                  * build a chain of answers to store. If we hit the
1736                  * limit, empty the chain and ignore the rest.
1737                  */
1738                 if ( !si->over ) {
1739                         if ( si->count < si->max ) {
1740                                 si->count++;
1741                                 e = entry_dup( rs->sr_entry );
1742                                 if ( !si->head ) si->head = e;
1743                                 if ( si->tail ) si->tail->e_private = e;
1744                                 si->tail = e;
1745                         } else {
1746                                 si->over = 1;
1747                                 si->count = 0;
1748                                 for (;si->head; si->head=e) {
1749                                         e = si->head->e_private;
1750                                         si->head->e_private = NULL;
1751                                         entry_free(si->head);
1752                                 }
1753                                 si->tail = NULL;
1754                         }
1755                 }
1756
1757         } else if ( rs->sr_type == REP_RESULT ) {
1758                 if ( si->count ||
1759                         ( si->qtemp->negttl && !si->count && !si->over &&
1760                                 rs->sr_err == LDAP_SUCCESS )) {
1761                         CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1762                                 si->count);
1763
1764                         if ( qc != NULL ) {
1765                                 if ( si->count )
1766                                         cache_entries( op, rs, &qc->q_uuid );
1767                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1768                                 cm->num_cached_queries++;
1769                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1770                                                 cm->num_cached_queries, 0, 0 );
1771                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1772
1773                                 /* If the consistency checker suspended itself,
1774                                  * wake it back up
1775                                  */
1776                                 if ( cm->cc_paused ) {
1777                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1778                                         if ( cm->cc_paused ) {
1779                                                 cm->cc_paused = 0;
1780                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1781                                         }
1782                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1783                                 }
1784                         } else if ( si->count ) {
1785                                 /* duplicate query, free it */
1786                                 Entry *e;
1787                                 for (;si->head; si->head=e) {
1788                                         e = si->head->e_private;
1789                                         si->head->e_private = NULL;
1790                                         entry_free(si->head);
1791                                 }
1792                         }
1793                 } else {
1794                         filter_free( si->query.filter );
1795                 }
1796
1797                 op->o_callback->sc_cleanup = pcache_op_cleanup;
1798         }
1799         return SLAP_CB_CONTINUE;
1800 }
1801
1802 static int
1803 add_filter_attrs(
1804         Operation *op,
1805         AttributeName** new_attrs,
1806         struct attr_set *attrs,
1807         AttributeName* filter_attrs,
1808         int fattr_cnt,
1809         int fattr_got_oc)
1810 {
1811         int alluser = 0;
1812         int allop = 0;
1813         int i, j;
1814         int count;
1815         int addoc = 0;
1816
1817         /* duplicate attrs */
1818         count = attrs->count + fattr_cnt;
1819         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1820                 addoc = 1;
1821                 count++;
1822         }
1823
1824         *new_attrs = (AttributeName*)ch_calloc( count + 1,
1825                 sizeof(AttributeName) );
1826         for (i=0; i<attrs->count; i++) {
1827                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1828                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1829         }
1830         BER_BVZERO( &(*new_attrs)[i].an_name );
1831         alluser = an_find(*new_attrs, &AllUser);
1832         allop = an_find(*new_attrs, &AllOper);
1833
1834         j = i;
1835         for ( i=0; i<fattr_cnt; i++ ) {
1836                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
1837                         continue;
1838                 }
1839                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1840                         if ( allop ) {
1841                                 continue;
1842                         }
1843                 } else if ( alluser ) {
1844                         continue;
1845                 }
1846                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1847                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1848                 (*new_attrs)[j].an_oc = NULL;
1849                 (*new_attrs)[j].an_oc_exclude = 0;
1850                 j++;
1851         }
1852         if ( addoc ) {
1853                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1854                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1855                 (*new_attrs)[j].an_oc = NULL;
1856                 (*new_attrs)[j].an_oc_exclude = 0;
1857                 j++;
1858         }
1859         BER_BVZERO( &(*new_attrs)[j].an_name );
1860
1861         return count;
1862 }
1863
1864 /* NOTE: this is a quick workaround to let pcache minimally interact
1865  * with pagedResults.  A more articulated solutions would be to
1866  * perform the remote query without control and cache all results,
1867  * performing the pagedResults search only within the client
1868  * and the proxy.  This requires pcache to understand pagedResults. */
1869 static int
1870 pcache_chk_controls(
1871         Operation       *op,
1872         SlapReply       *rs )
1873 {
1874         const char      *non = "";
1875         const char      *stripped = "";
1876
1877         switch( op->o_pagedresults ) {
1878         case SLAP_CONTROL_NONCRITICAL:
1879                 non = "non-";
1880                 stripped = "; stripped";
1881                 /* fallthru */
1882
1883         case SLAP_CONTROL_CRITICAL:
1884                 Debug( pcache_debug, "%s: "
1885                         "%scritical pagedResults control "
1886                         "disabled with proxy cache%s.\n",
1887                         op->o_log_prefix, non, stripped );
1888                 
1889                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1890                 break;
1891
1892         default:
1893                 rs->sr_err = SLAP_CB_CONTINUE;
1894                 break;
1895         }
1896
1897         return rs->sr_err;
1898 }
1899
1900 static int
1901 pcache_op_search(
1902         Operation       *op,
1903         SlapReply       *rs )
1904 {
1905         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1906         cache_manager *cm = on->on_bi.bi_private;
1907         query_manager*          qm = cm->qm;
1908
1909         int i = -1;
1910
1911         AttributeName   *filter_attrs = NULL;
1912
1913         Query           query;
1914         QueryTemplate   *qtemp = NULL;
1915
1916         int             attr_set = -1;
1917         CachedQuery     *answerable = NULL;
1918         int             cacheable = 0;
1919         int             fattr_cnt=0;
1920         int             fattr_got_oc = 0;
1921
1922         struct berval tempstr;
1923
1924         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1925         tempstr.bv_len = 0;
1926         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1927                 &fattr_cnt, &fattr_got_oc )) {
1928                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1929                 return SLAP_CB_CONTINUE;
1930         }
1931
1932         Debug( pcache_debug, "query template of incoming query = %s\n",
1933                                         tempstr.bv_val, 0, 0 );
1934
1935         /* FIXME: cannot cache/answer requests with pagedResults control */
1936
1937         /* find attr set */
1938         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1939
1940         query.filter = op->ors_filter;
1941         query.base = op->o_req_ndn;
1942         query.scope = op->ors_scope;
1943
1944         /* check for query containment */
1945         if (attr_set > -1) {
1946                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1947                 for (; qt; qt = qt->qtnext ) {
1948                         /* find if template i can potentially answer tempstr */
1949                         if (qt->querystr.bv_len != tempstr.bv_len ||
1950                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1951                                 continue;
1952                         cacheable = 1;
1953                         qtemp = qt;
1954                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
1955                                         op->ors_filterstr.bv_val, 0, 0 );
1956                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1957
1958                         if (answerable)
1959                                 break;
1960                 }
1961         }
1962         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1963
1964         if (answerable) {
1965                 /* Need to clear the callbacks of the original operation,
1966                  * in case there are other overlays */
1967                 BackendDB       *save_bd = op->o_bd;
1968                 slap_callback   *save_cb = op->o_callback;
1969
1970                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1971                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1972                 if ( BER_BVISNULL( &answerable->q_uuid )) {
1973                         /* No entries cached, just an empty result set */
1974                         i = rs->sr_err = 0;
1975                         send_ldap_result( op, rs );
1976                 } else {
1977                         op->o_bd = &cm->db;
1978                         op->o_callback = NULL;
1979                         i = cm->db.bd_info->bi_op_search( op, rs );
1980                 }
1981                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1982                 op->o_bd = save_bd;
1983                 op->o_callback = save_cb;
1984                 return i;
1985         }
1986
1987         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1988
1989         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1990         if (cm->num_cached_queries >= cm->max_queries) {
1991                 cacheable = 0;
1992         }
1993         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1994
1995         if (op->ors_attrsonly)
1996                 cacheable = 0;
1997
1998         if (cacheable) {
1999                 slap_callback           *cb;
2000                 struct search_info      *si;
2001
2002                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2003                 query.filter = filter_dup(op->ors_filter, NULL);
2004                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2005                 if ( !qtemp->t_attrs.count ) {
2006                         qtemp->t_attrs.count = add_filter_attrs(op,
2007                                 &qtemp->t_attrs.attrs,
2008                                 &qm->attr_sets[attr_set],
2009                                 filter_attrs, fattr_cnt, fattr_got_oc);
2010                 }
2011                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2012
2013                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2014                 cb->sc_response = pcache_response;
2015                 cb->sc_cleanup = NULL;
2016                 cb->sc_private = (cb+1);
2017                 si = cb->sc_private;
2018                 si->on = on;
2019                 si->query = query;
2020                 si->qtemp = qtemp;
2021                 si->max = cm->num_entries_limit ;
2022                 si->over = 0;
2023                 si->count = 0;
2024                 si->head = NULL;
2025                 si->tail = NULL;
2026                 si->save_attrs = op->ors_attrs;
2027
2028                 op->ors_attrs = qtemp->t_attrs.attrs;
2029
2030                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2031                         cb->sc_next = op->o_callback;
2032                         op->o_callback = cb;
2033
2034                 } else {
2035                         slap_callback           **pcb;
2036
2037                         /* need to move the callback at the end, in case other
2038                          * overlays are present, so that the final entry is
2039                          * actually cached */
2040                         cb->sc_next = NULL;
2041                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2042                         *pcb = cb;
2043                 }
2044
2045         } else {
2046                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2047                                         0, 0, 0);
2048         }
2049
2050         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2051
2052         return SLAP_CB_CONTINUE;
2053 }
2054
2055 static int
2056 get_attr_set(
2057         AttributeName* attrs,
2058         query_manager* qm,
2059         int num )
2060 {
2061         int i;
2062         int count = 0;
2063
2064         if ( attrs ) {
2065                 for ( ; attrs[count].an_name.bv_val; count++ );
2066         }
2067
2068         /* recognize a single "*" or a "1.1" */
2069         if ( count == 0 ) {
2070                 count = 1;
2071                 attrs = slap_anlist_all_user_attributes;
2072
2073         } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2074                 count = 0;
2075                 attrs = NULL;
2076         }
2077
2078         for ( i = 0; i < num; i++ ) {
2079                 AttributeName *a2;
2080                 int found = 1;
2081
2082                 if ( count > qm->attr_sets[i].count ) {
2083                         continue;
2084                 }
2085
2086                 if ( !count ) {
2087                         if ( !qm->attr_sets[i].count ) {
2088                                 break;
2089                         }
2090                         continue;
2091                 }
2092
2093                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2094                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2095                                 found = 0;
2096                                 break;
2097                         }
2098                 }
2099
2100                 if ( found ) {
2101                         break;
2102                 }
2103         }
2104
2105         if ( i == num ) {
2106                 i = -1;
2107         }
2108
2109         return i;
2110 }
2111
2112 static void*
2113 consistency_check(
2114         void *ctx,
2115         void *arg )
2116 {
2117         struct re_s *rtask = arg;
2118         slap_overinst *on = rtask->arg;
2119         cache_manager *cm = on->on_bi.bi_private;
2120         query_manager *qm = cm->qm;
2121         Connection conn = {0};
2122         OperationBuffer opbuf;
2123         Operation *op;
2124
2125         SlapReply rs = {REP_RESULT};
2126         CachedQuery* query;
2127         int return_val, pause = 1;
2128         QueryTemplate* templ;
2129
2130         connection_fake_init( &conn, &opbuf, ctx );
2131         op = &opbuf.ob_op;
2132
2133         op->o_bd = &cm->db;
2134         op->o_dn = cm->db.be_rootdn;
2135         op->o_ndn = cm->db.be_rootndn;
2136
2137         cm->cc_arg = arg;
2138
2139         for (templ = qm->templates; templ; templ=templ->qmnext) {
2140                 query = templ->query_last;
2141                 if ( query ) pause = 0;
2142                 op->o_time = slap_get_time();
2143                 while (query && (query->expiry_time < op->o_time)) {
2144                         int rem = 0;
2145                         Debug( pcache_debug, "Lock CR index = %p\n",
2146                                         (void *) templ, 0, 0 );
2147                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2148                         if ( query == templ->query_last ) {
2149                                 rem = 1;
2150                                 remove_from_template(query, templ);
2151                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2152                                                 (void *) templ, templ->no_of_queries, 0 );
2153                                 Debug( pcache_debug, "Unlock CR index = %p\n",
2154                                                 (void *) templ, 0, 0 );
2155                         }
2156                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2157                         if ( !rem ) {
2158                                 query = templ->query_last;
2159                                 continue;
2160                         }
2161                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2162                         remove_query(qm, query);
2163                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2164                         if ( BER_BVISNULL( &query->q_uuid ))
2165                                 return_val = 0;
2166                         else
2167                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
2168                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2169                                                 return_val, 0, 0 );
2170                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2171                         cm->cur_entries -= return_val;
2172                         cm->num_cached_queries--;
2173                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
2174                                         cm->num_cached_queries, 0, 0 );
2175                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2176                         Debug( pcache_debug,
2177                                 "STALE QUERY REMOVED, CACHE ="
2178                                 "%d entries\n",
2179                                 cm->cur_entries, 0, 0 );
2180                         free_query(query);
2181                         query = templ->query_last;
2182                 }
2183         }
2184         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2185         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2186                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2187         }
2188         /* If there were no queries, defer processing for a while */
2189         cm->cc_paused = pause;
2190         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2191
2192         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2193         return NULL;
2194 }
2195
2196
2197 #define MAX_ATTR_SETS 500
2198
2199 enum {
2200         PC_MAIN = 1,
2201         PC_ATTR,
2202         PC_TEMP,
2203         PC_RESP,
2204         PC_QUERIES
2205 };
2206
2207 static ConfigDriver pc_cf_gen;
2208 static ConfigLDAPadd pc_ldadd;
2209 static ConfigCfAdd pc_cfadd;
2210
2211 static ConfigTable pccfg[] = {
2212         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2213                                 "<cycle_time",
2214                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2215                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2216                         "DESC 'ProxyCache basic parameters' "
2217                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2218         { "proxyattrset", "index> <attributes...",
2219                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2220                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2221                         "DESC 'A set of attributes to cache' "
2222                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2223         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2224                 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2225                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2226                         "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2227                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2228         { "response-callback", "head|tail(default)",
2229                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2230                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2231                         "DESC 'Response callback position in overlay stack' "
2232                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2233         { "proxyCacheQueries", "queries",
2234                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2235                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2236                         "DESC 'Maximum number of queries to cache' "
2237                         "SYNTAX OMsInteger )", NULL, NULL },
2238         { "proxySaveQueries", "TRUE|FALSE",
2239                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2240                 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2241                         "DESC 'Save cached queries for hot restart' "
2242                         "SYNTAX OMsBoolean )", NULL, NULL },
2243
2244         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2245 };
2246
2247 static ConfigOCs pcocs[] = {
2248         { "( OLcfgOvOc:2.1 "
2249                 "NAME 'olcPcacheConfig' "
2250                 "DESC 'ProxyCache configuration' "
2251                 "SUP olcOverlayConfig "
2252                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2253                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2254                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2255         { "( OLcfgOvOc:2.2 "
2256                 "NAME 'olcPcacheDatabase' "
2257                 "DESC 'Cache database configuration' "
2258                 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2259         { NULL, 0, NULL }
2260 };
2261
2262 static int
2263 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2264 {
2265         slap_overinst *on;
2266         cache_manager *cm;
2267
2268         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2269                 p->ce_bi->bi_cf_ocs != pcocs )
2270                 return LDAP_CONSTRAINT_VIOLATION;
2271
2272         on = (slap_overinst *)p->ce_bi;
2273         cm = on->on_bi.bi_private;
2274         ca->be = &cm->db;
2275         return LDAP_SUCCESS;
2276 }
2277
2278 static int
2279 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2280 {
2281         CfEntryInfo *pe = p->e_private;
2282         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2283         cache_manager *cm = on->on_bi.bi_private;
2284         struct berval bv;
2285
2286         /* FIXME: should not hardcode "olcDatabase" here */
2287         bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2288         bv.bv_val = ca->cr_msg;
2289         ca->be = &cm->db;
2290
2291         /* We can only create this entry if the database is table-driven
2292          */
2293         if ( cm->db.bd_info->bi_cf_ocs )
2294                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2295                         &pcocs[1] );
2296
2297         return 0;
2298 }
2299
2300 static int
2301 pc_cf_gen( ConfigArgs *c )
2302 {
2303         slap_overinst   *on = (slap_overinst *)c->bi;
2304         cache_manager*  cm = on->on_bi.bi_private;
2305         query_manager*  qm = cm->qm;
2306         QueryTemplate*  temp;
2307         AttributeName*  attr_name;
2308         AttributeName*  attrarray;
2309         const char*     text=NULL;
2310         int             i, num, rc = 0;
2311         char            *ptr;
2312         unsigned long   t;
2313
2314         if ( c->op == SLAP_CONFIG_EMIT ) {
2315                 struct berval bv;
2316                 switch( c->type ) {
2317                 case PC_MAIN:
2318                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2319                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2320                                 cm->num_entries_limit, cm->cc_period );
2321                         bv.bv_val = c->cr_msg;
2322                         value_add_one( &c->rvalue_vals, &bv );
2323                         break;
2324                 case PC_ATTR:
2325                         for (i=0; i<cm->numattrsets; i++) {
2326                                 if ( !qm->attr_sets[i].count ) continue;
2327
2328                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2329
2330                                 /* count the attr length */
2331                                 for ( attr_name = qm->attr_sets[i].attrs;
2332                                         attr_name->an_name.bv_val; attr_name++ )
2333                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2334
2335                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2336                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2337                                 for ( attr_name = qm->attr_sets[i].attrs;
2338                                         attr_name->an_name.bv_val; attr_name++ ) {
2339                                         *ptr++ = ' ';
2340                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2341                                 }
2342                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2343                         }
2344                         if ( !c->rvalue_vals )
2345                                 rc = 1;
2346                         break;
2347                 case PC_TEMP:
2348                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2349                                 if ( temp->negttl ) {
2350                                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2351                                                 " %d %ld %ld",
2352                                                 temp->attr_set_index,
2353                                                 temp->ttl,
2354                                                 temp->negttl );
2355                                 } else {
2356                                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2357                                                 temp->attr_set_index,
2358                                                 temp->ttl );
2359                                 }
2360                                 bv.bv_len += temp->querystr.bv_len + 2;
2361                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2362                                 ptr = bv.bv_val;
2363                                 *ptr++ = '"';
2364                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2365                                 *ptr++ = '"';
2366                                 strcpy( ptr, c->cr_msg );
2367                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2368                         }
2369                         if ( !c->rvalue_vals )
2370                                 rc = 1;
2371                         break;
2372                 case PC_RESP:
2373                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2374                                 BER_BVSTR( &bv, "head" );
2375                         } else {
2376                                 BER_BVSTR( &bv, "tail" );
2377                         }
2378                         value_add_one( &c->rvalue_vals, &bv );
2379                         break;
2380                 case PC_QUERIES:
2381                         c->value_int = cm->max_queries;
2382                         break;
2383                 }
2384                 return rc;
2385         } else if ( c->op == LDAP_MOD_DELETE ) {
2386                 return 1;       /* FIXME */
2387 #if 0
2388                 switch( c->type ) {
2389                 case PC_ATTR:
2390                 case PC_TEMP:
2391                 }
2392                 return rc;
2393 #endif
2394         }
2395
2396         switch( c->type ) {
2397         case PC_MAIN:
2398                 if ( cm->numattrsets > 0 ) {
2399                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2400                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2401                         return( 1 );
2402                 }
2403
2404                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2405                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2406                                 c->argv[3] );
2407                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2408                         return( 1 );
2409                 }
2410                 if ( cm->numattrsets <= 0 ) {
2411                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2412                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2413                         return( 1 );
2414                 }
2415                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2416                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2417                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2418                         return( 1 );
2419                 }
2420
2421                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2422                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2423                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2424                         return( 1 );
2425                 }
2426
2427                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2428                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2429                                 c->argv[2] );
2430                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2431                         return( 1 );
2432                 }
2433                 if ( cm->max_entries <= 0 ) {
2434                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2435                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2436                         return( 1 );
2437                 }
2438
2439                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2440                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2441                                 c->argv[4] );
2442                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2443                         return( 1 );
2444                 }
2445                 if ( cm->num_entries_limit <= 0 ) {
2446                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2447                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2448                         return( 1 );
2449                 }
2450                 if ( cm->num_entries_limit > cm->max_entries ) {
2451                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2452                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2453                         return( 1 );
2454                 }
2455
2456                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2457                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2458                                 c->argv[5] );
2459                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2460                         return( 1 );
2461                 }
2462                 cm->cc_period = (time_t)t;
2463                 Debug( pcache_debug,
2464                                 "Total # of attribute sets to be cached = %d.\n",
2465                                 cm->numattrsets, 0, 0 );
2466                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2467                                                 sizeof( struct attr_set ) );
2468                 break;
2469         case PC_ATTR:
2470                 if ( cm->numattrsets == 0 ) {
2471                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2472                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2473                         return( 1 );
2474                 }
2475                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2476                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2477                                 c->argv[1] );
2478                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2479                         return( 1 );
2480                 }
2481
2482                 if ( num < 0 || num >= cm->numattrsets ) {
2483                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2484                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2485                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2486                         return 1;
2487                 }
2488                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2489                 if ( c->argc == 2 ) {
2490                         /* assume "1.1" */
2491                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2492                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2493                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2494                         return 1;
2495
2496                 } else if ( c->argc == 3 ) {
2497                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2498                                 qm->attr_sets[num].count = 1;
2499                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2500                                         sizeof( AttributeName ) );
2501                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2502                                 break;
2503
2504                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2505                                 qm->attr_sets[num].count = 1;
2506                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2507                                         sizeof( AttributeName ) );
2508                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2509                                 break;
2510
2511                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2512                                 break;
2513                         }
2514                         /* else: fallthru */
2515
2516                 } else if ( c->argc == 4 ) {
2517                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2518                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2519                         {
2520                                 qm->attr_sets[num].count = 2;
2521                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2522                                         sizeof( AttributeName ) );
2523                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2524                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2525                                 break;
2526                         }
2527                         /* else: fallthru */
2528                 }
2529
2530                 if ( c->argc > 2 ) {
2531                         int all_user = 0, all_op = 0;
2532
2533                         qm->attr_sets[num].count = c->argc - 2;
2534                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2535                                 sizeof( AttributeName ) );
2536                         attr_name = qm->attr_sets[num].attrs;
2537                         for ( i = 2; i < c->argc; i++ ) {
2538                                 attr_name->an_desc = NULL;
2539                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2540                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2541                                                 "invalid attr #%d \"%s\" in attrlist",
2542                                                 i - 2, c->argv[i] );
2543                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2544                                         ch_free( qm->attr_sets[num].attrs );
2545                                         qm->attr_sets[num].attrs = NULL;
2546                                         qm->attr_sets[num].count = 0;
2547                                         return 1;
2548                                 }
2549                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2550                                         all_user = 1;
2551                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2552                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2553                                         all_op = 1;
2554                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2555                                 } else {
2556                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2557                                                 strcpy( c->cr_msg, text );
2558                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2559                                                 ch_free( qm->attr_sets[num].attrs );
2560                                                 qm->attr_sets[num].attrs = NULL;
2561                                                 qm->attr_sets[num].count = 0;
2562                                                 return 1;
2563                                         }
2564                                         attr_name->an_name = attr_name->an_desc->ad_cname;
2565                                 }
2566                                 attr_name->an_oc = NULL;
2567                                 attr_name->an_oc_exclude = 0;
2568                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2569                                         qm->attr_sets[num].flags |= PC_GOT_OC;
2570                                 attr_name++;
2571                                 BER_BVZERO( &attr_name->an_name );
2572                         }
2573
2574                         /* warn if list contains both "*" and "+" */
2575                         if ( i > 4 && all_user && all_op ) {
2576                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2577                                         "warning: attribute list contains \"*\" and \"+\"" );
2578                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2579                         }
2580                 }
2581                 break;
2582         case PC_TEMP:
2583                 if ( cm->numattrsets == 0 ) {
2584                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2585                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2586                         return( 1 );
2587                 }
2588                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2589                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2590                                 c->argv[2] );
2591                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2592                         return( 1 );
2593                 }
2594
2595                 if ( i < 0 || i >= cm->numattrsets || 
2596                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2597                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2598                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2599                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2600                         return 1;
2601                 }
2602                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2603                 temp->qmnext = qm->templates;
2604                 qm->templates = temp;
2605                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2606                 temp->query = temp->query_last = NULL;
2607                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2608                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2609                                 c->argv[3] );
2610                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2611                         return( 1 );
2612                 }
2613                 temp->ttl = (time_t)t;
2614                 if ( c->argc == 5 ) {
2615                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2616                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2617                                         "unable to parse template negttl=\"%s\"",
2618                                         c->argv[4] );
2619                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2620                                         return( 1 );
2621                         }
2622                         temp->negttl = (time_t)t;
2623                 } else {
2624                         temp->negttl = 0;
2625                 }
2626
2627                 temp->no_of_queries = 0;
2628
2629                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2630                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2631                 Debug( pcache_debug, "  query template: %s\n",
2632                                 temp->querystr.bv_val, 0, 0 );
2633                 temp->attr_set_index = i;
2634                 qm->attr_sets[i].flags |= PC_REFERENCED;
2635                 temp->qtnext = qm->attr_sets[i].templates;
2636                 qm->attr_sets[i].templates = temp;
2637                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
2638                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2639                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
2640                                 Debug( pcache_debug, "\t%s\n",
2641                                         attrarray[i].an_name.bv_val, 0, 0 );
2642                 }
2643                 break;
2644         case PC_RESP:
2645                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2646                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2647
2648                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2649                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2650
2651                 } else {
2652                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2653                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2654                         return 1;
2655                 }
2656                 break;
2657         case PC_QUERIES:
2658                 if ( c->value_int <= 0 ) {
2659                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2660                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2661                         return( 1 );
2662                 }
2663                 cm->max_queries = c->value_int;
2664                 break;
2665         }
2666         return rc;
2667 }
2668
2669 static int
2670 pcache_db_config(
2671         BackendDB       *be,
2672         const char      *fname,
2673         int             lineno,
2674         int             argc,
2675         char            **argv
2676 )
2677 {
2678         slap_overinst   *on = (slap_overinst *)be->bd_info;
2679         cache_manager*  cm = on->on_bi.bi_private;
2680
2681         /* Something for the cache database? */
2682         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2683                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2684                         argc, argv );
2685         return SLAP_CONF_UNKNOWN;
2686 }
2687
2688 static int
2689 pcache_db_init(
2690         BackendDB *be,
2691         ConfigReply *cr)
2692 {
2693         slap_overinst *on = (slap_overinst *)be->bd_info;
2694         cache_manager *cm;
2695         query_manager *qm;
2696
2697         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2698         on->on_bi.bi_private = cm;
2699
2700         qm = (query_manager*)ch_malloc(sizeof(query_manager));
2701
2702         cm->db = *be;
2703         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2704         cm->db.be_private = NULL;
2705         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2706         cm->qm = qm;
2707         cm->numattrsets = 0;
2708         cm->num_entries_limit = 5;
2709         cm->num_cached_queries = 0;
2710         cm->max_entries = 0;
2711         cm->cur_entries = 0;
2712         cm->max_queries = 10000;
2713         cm->save_queries = 0;
2714         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2715         cm->cc_period = 1000;
2716         cm->cc_paused = 0;
2717
2718         qm->attr_sets = NULL;
2719         qm->templates = NULL;
2720         qm->lru_top = NULL;
2721         qm->lru_bottom = NULL;
2722
2723         qm->qcfunc = query_containment;
2724         qm->crfunc = cache_replacement;
2725         qm->addfunc = add_query;
2726         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2727
2728         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2729         return 0;
2730 }
2731
2732 static int
2733 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2734 {
2735         assert( op->o_tag == LDAP_REQ_SEARCH );
2736
2737         if ( rs->sr_type == REP_SEARCH ) {
2738                 Attribute       *a;
2739
2740                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2741                 if ( a != NULL ) {
2742                         BerVarray       *valsp;
2743
2744                         assert( a->a_nvals != NULL );
2745
2746                         valsp = op->o_callback->sc_private;
2747                         assert( *valsp == NULL );
2748
2749                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2750                 }
2751         }
2752
2753         return 0;
2754 }
2755
2756 static int
2757 pcache_db_open(
2758         BackendDB *be,
2759         ConfigReply *cr )
2760 {
2761         slap_overinst   *on = (slap_overinst *)be->bd_info;
2762         cache_manager   *cm = on->on_bi.bi_private;
2763         query_manager*  qm = cm->qm;
2764         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2765
2766         /* check attr sets */
2767         for ( i = 0; i < cm->numattrsets; i++) {
2768                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2769                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2770                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2771                                 rf++;
2772
2773                         } else {
2774                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2775                         }
2776                         ncf++;
2777
2778                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2779                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2780                         nrf++;
2781                 }
2782         }
2783
2784         if ( ncf || rf || nrf ) {
2785                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2786                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2787                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2788
2789                 if ( rf > 0 ) {
2790                         return 1;
2791                 }
2792         }
2793
2794         /* need to inherit something from the original database... */
2795         cm->db.be_def_limit = be->be_def_limit;
2796         cm->db.be_limits = be->be_limits;
2797         cm->db.be_acl = be->be_acl;
2798         cm->db.be_dfltaccess = be->be_dfltaccess;
2799
2800         if ( SLAP_DBMONITORING( be ) ) {
2801                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2802
2803         } else {
2804                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2805         }
2806
2807         rc = backend_startup_one( &cm->db, NULL );
2808
2809         /* There is no runqueue in TOOL mode */
2810         if ( slapMode & SLAP_SERVER_MODE ) {
2811                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2812                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2813                         consistency_check, on,
2814                         "pcache_consistency", be->be_suffix[0].bv_val );
2815                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2816
2817                 /* Cached database must have the rootdn */
2818                 if ( BER_BVISNULL( &cm->db.be_rootndn )
2819                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2820                 {
2821                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2822                                 "underlying database of type \"%s\"\n"
2823                                 "    serving naming context \"%s\"\n"
2824                                 "    has no \"rootdn\", required by \"proxycache\".\n",
2825                                 on->on_info->oi_orig->bi_type,
2826                                 cm->db.be_suffix[0].bv_val, 0 );
2827                         return 1;
2828                 }
2829
2830                 if ( cm->save_queries ) {
2831                         void            *thrctx = ldap_pvt_thread_pool_context();
2832                         Connection      conn = { 0 };
2833                         OperationBuffer opbuf;
2834                         Operation       *op;
2835                         slap_callback   cb = { 0 };
2836                         SlapReply       rs = { 0 };
2837                         BerVarray       vals = NULL;
2838                         AttributeName   attrs[ 2 ] = { 0 };
2839
2840                         connection_fake_init( &conn, &opbuf, thrctx );
2841                         op = &opbuf.ob_op;
2842
2843                         op->o_bd = &cm->db;
2844
2845                         op->o_tag = LDAP_REQ_SEARCH;
2846                         op->o_protocol = LDAP_VERSION3;
2847                         cb.sc_response = pcache_cachedquery_open_cb;
2848                         cb.sc_private = &vals;
2849                         op->o_callback = &cb;
2850                         op->o_time = slap_get_time();
2851                         op->o_do_not_cache = 1;
2852                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
2853
2854                         op->o_dn = cm->db.be_rootdn;
2855                         op->o_ndn = cm->db.be_rootndn;
2856                         op->o_req_dn = cm->db.be_suffix[ 0 ];
2857                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2858
2859                         op->ors_scope = LDAP_SCOPE_BASE;
2860                         op->ors_deref = LDAP_DEREF_NEVER;
2861                         op->ors_slimit = 1;
2862                         op->ors_tlimit = SLAP_NO_LIMIT;
2863                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
2864                         op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
2865                         if ( op->ors_filter != NULL ) {
2866                                 attrs[ 0 ].an_desc = ad_cachedQueryURL;
2867                                 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
2868                                 op->ors_attrs = attrs;
2869                                 op->ors_attrsonly = 0;
2870
2871                                 rc = op->o_bd->be_search( op, &rs );
2872                                 if ( rc == LDAP_SUCCESS && vals != NULL ) {
2873                                         int     i;
2874
2875                                         for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2876                                                 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
2877                                                         cm->num_cached_queries++;
2878                                                 }
2879                                         }
2880
2881                                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
2882                                 }
2883
2884                                 filter_free_x( op, op->ors_filter );
2885                         }
2886
2887                         /* ignore errors */
2888                         rc = 0;
2889                 }
2890         }
2891
2892         return rc;
2893 }
2894
2895 static void
2896 pcache_free_qbase( void *v )
2897 {
2898         Qbase *qb = v;
2899         int i;
2900
2901         for (i=0; i<3; i++)
2902                 tavl_free( qb->scopes[i], NULL );
2903         ch_free( qb );
2904 }
2905
2906 static int
2907 pcache_db_close(
2908         BackendDB *be,
2909         ConfigReply *cr
2910 )
2911 {
2912         slap_overinst *on = (slap_overinst *)be->bd_info;
2913         cache_manager *cm = on->on_bi.bi_private;
2914         query_manager *qm = cm->qm;
2915         QueryTemplate *tm;
2916         int i, rc = 0;
2917
2918         if ( cm->save_queries && qm->templates != NULL ) {
2919                 CachedQuery     *qc;
2920                 BerVarray       vals = NULL;
2921
2922                 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
2923                         for ( qc = tm->query; qc; qc = qc->next ) {
2924                                 struct berval   bv;
2925
2926                                 if ( query2url( qc, &bv ) == 0 ) {
2927                                         ber_bvarray_add( &vals, &bv );
2928                                 }
2929                         }
2930                 }
2931
2932                 if ( vals != NULL ) {
2933                         void            *thrctx = ldap_pvt_thread_pool_context();
2934                         Connection      conn = { 0 };
2935                         OperationBuffer opbuf;
2936                         Operation       *op;
2937                         slap_callback   cb = { 0 };
2938
2939                         SlapReply       rs = { REP_RESULT };
2940                         Modifications   mod = { 0 };
2941
2942                         connection_fake_init( &conn, &opbuf, thrctx );
2943                         op = &opbuf.ob_op;
2944
2945                         op->o_bd = &cm->db;
2946                         op->o_dn = cm->db.be_rootdn;
2947                         op->o_ndn = cm->db.be_rootndn;
2948
2949                         op->o_tag = LDAP_REQ_MODIFY;
2950                         op->o_protocol = LDAP_VERSION3;
2951                         cb.sc_response = slap_null_cb;
2952                         op->o_callback = &cb;
2953                         op->o_time = slap_get_time();
2954                         op->o_do_not_cache = 1;
2955                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
2956
2957                         op->o_req_dn = op->o_bd->be_suffix[0];
2958                         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2959
2960                         mod.sml_op = LDAP_MOD_REPLACE;
2961                         mod.sml_flags = 0;
2962                         mod.sml_desc = ad_cachedQueryURL;
2963                         mod.sml_type = ad_cachedQueryURL->ad_cname;
2964                         mod.sml_values = vals;
2965                         mod.sml_nvalues = NULL;
2966                         mod.sml_next = NULL;
2967                         Debug( pcache_debug,
2968                                 "SETTING CACHED QUERY URLS\n",
2969                                 0, 0, 0 );
2970
2971                         op->orm_modlist = &mod;
2972
2973                         op->o_bd->be_modify( op, &rs );
2974
2975                         ber_bvarray_free( vals );
2976                 }
2977         }
2978
2979         /* cleanup stuff inherited from the original database... */
2980         cm->db.be_limits = NULL;
2981         cm->db.be_acl = NULL;
2982
2983         /* stop the thread ... */
2984         if ( cm->cc_arg ) {
2985                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2986                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
2987                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
2988                 }
2989                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
2990                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2991         }
2992
2993         if ( cm->db.bd_info->bi_db_close ) {
2994                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
2995         }
2996         while ( (tm = qm->templates) != NULL ) {
2997                 CachedQuery *qc, *qn;
2998                 qm->templates = tm->qmnext;
2999                 for ( qc = tm->query; qc; qc = qn ) {
3000                         qn = qc->next;
3001                         free_query( qc );
3002                 }
3003                 avl_free( tm->qbase, pcache_free_qbase );
3004                 free( tm->querystr.bv_val );
3005                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3006                 free( tm->t_attrs.attrs );
3007                 free( tm );
3008         }
3009
3010         for ( i=0; i<cm->numattrsets; i++ ) {
3011                 free( qm->attr_sets[i].attrs );
3012         }
3013         free( qm->attr_sets );
3014         qm->attr_sets = NULL;
3015
3016         return rc;
3017 }
3018
3019 static int
3020 pcache_db_destroy(
3021         BackendDB *be,
3022         ConfigReply *cr
3023 )
3024 {
3025         slap_overinst *on = (slap_overinst *)be->bd_info;
3026         cache_manager *cm = on->on_bi.bi_private;
3027         query_manager *qm = cm->qm;
3028
3029         if ( cm->db.be_private != NULL ) {
3030                 backend_stopdown_one( &cm->db );
3031         }
3032
3033         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3034         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3035         free( qm );
3036         free( cm );
3037
3038         return 0;
3039 }
3040
3041 static slap_overinst pcache;
3042
3043 static char *obsolete_names[] = {
3044         "proxycache",
3045         NULL
3046 };
3047
3048 int pcache_initialize()
3049 {
3050         int i, code;
3051         struct berval debugbv = BER_BVC("pcache");
3052
3053         code = slap_loglevel_get( &debugbv, &pcache_debug );
3054         if ( code ) {
3055                 return code;
3056         }
3057
3058         for ( i = 0; as[i].desc != NULL; i++ ) {
3059                 code = register_at( as[i].desc, as[i].adp, 0 );
3060                 if ( code ) {
3061                         Debug( LDAP_DEBUG_ANY,
3062                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3063                         return code;
3064                 }
3065         }
3066
3067         pcache.on_bi.bi_type = "pcache";
3068         pcache.on_bi.bi_obsolete_names = obsolete_names;
3069         pcache.on_bi.bi_db_init = pcache_db_init;
3070         pcache.on_bi.bi_db_config = pcache_db_config;
3071         pcache.on_bi.bi_db_open = pcache_db_open;
3072         pcache.on_bi.bi_db_close = pcache_db_close;
3073         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3074
3075         pcache.on_bi.bi_op_search = pcache_op_search;
3076
3077         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3078
3079         pcache.on_bi.bi_cf_ocs = pcocs;
3080
3081         code = config_register_schema( pccfg, pcocs );
3082         if ( code ) return code;
3083
3084         return overlay_register( &pcache );
3085 }
3086
3087 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3088 int init_module(int argc, char *argv[]) {
3089         return pcache_initialize();
3090 }
3091 #endif
3092
3093 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */