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