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