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