]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
Remove lint (unused vars/labels/funcs/default:s)
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003-2010 The OpenLDAP Foundation.
5  * Portions Copyright 2003 IBM Corporation.
6  * Portions Copyright 2003-2009 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 "../back-monitor/back-monitor.h"
37
38 #include "config.h"
39
40 #ifdef LDAP_DEVEL
41 /*
42  * Control that allows to access the private DB
43  * instead of the public one
44  */
45 #define PCACHE_CONTROL_PRIVDB           "1.3.6.1.4.1.4203.666.11.9.5.1"
46
47 /*
48  * Extended Operation that allows to remove a query from the cache
49  */
50 #define PCACHE_EXOP_QUERY_DELETE        "1.3.6.1.4.1.4203.666.11.9.6.1"
51
52 /*
53  * Monitoring
54  */
55 #define PCACHE_MONITOR
56 #endif
57
58 /* query cache structs */
59 /* query */
60
61 typedef struct Query_s {
62         Filter*         filter;         /* Search Filter */
63         struct berval   base;           /* Search Base */
64         int             scope;          /* Search scope */
65 } Query;
66
67 struct query_template_s;
68
69 typedef struct Qbase_s {
70         Avlnode *scopes[4];             /* threaded AVL trees of cached queries */
71         struct berval base;
72         int queries;
73 } Qbase;
74
75 /* struct representing a cached query */
76 typedef struct cached_query_s {
77         Filter                                  *filter;
78         Filter                                  *first;
79         Qbase                                   *qbase;
80         int                                             scope;
81         struct berval                   q_uuid;         /* query identifier */
82         int                                             q_sizelimit;
83         struct query_template_s         *qtemp; /* template of the query */
84         time_t                                          expiry_time;    /* time till the query is considered invalid */
85         time_t                                          refresh_time;   /* time till the query is refreshed */
86         time_t                                          bindref_time;   /* time till the bind is refreshed */
87         unsigned long                   answerable_cnt; /* how many times it was answerable */
88         int                                             refcnt; /* references since last refresh */
89         ldap_pvt_thread_mutex_t         answerable_cnt_mutex;
90         struct cached_query_s           *next;          /* next query in the template */
91         struct cached_query_s           *prev;          /* previous query in the template */
92         struct cached_query_s           *lru_up;        /* previous query in the LRU list */
93         struct cached_query_s           *lru_down;      /* next query in the LRU list */
94         ldap_pvt_thread_rdwr_t          rwlock;
95 } CachedQuery;
96
97 /*
98  * URL representation:
99  *
100  * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>,x-refresh=<refresh>
101  *
102  * <base> ::= CachedQuery.qbase->base
103  * <scope> ::= CachedQuery.scope
104  * <filter> ::= filter2bv(CachedQuery.filter)
105  * <uuid> ::= CachedQuery.q_uuid
106  * <attrset> ::= CachedQuery.qtemp->attr_set_index
107  * <expiry> ::= CachedQuery.expiry_time
108  * <refresh> ::= CachedQuery.refresh_time
109  *
110  * quick hack: parse URI, call add_query() and then fix
111  * CachedQuery.expiry_time and CachedQuery.q_uuid
112  *
113  * NOTE: if the <attrset> changes, all stored URLs will be invalidated.
114  */
115
116 /*
117  * Represents a set of projected attributes.
118  */
119
120 struct attr_set {
121         struct query_template_s *templates;
122         AttributeName*  attrs;          /* specifies the set */
123         unsigned        flags;
124 #define PC_CONFIGURED   (0x1)
125 #define PC_REFERENCED   (0x2)
126 #define PC_GOT_OC               (0x4)
127         int             count;          /* number of attributes */
128 };
129
130 /* struct representing a query template
131  * e.g. template string = &(cn=)(mail=)
132  */
133 typedef struct query_template_s {
134         struct query_template_s *qtnext;
135         struct query_template_s *qmnext;
136
137         Avlnode*                qbase;
138         CachedQuery*    query;          /* most recent query cached for the template */
139         CachedQuery*    query_last;     /* oldest query cached for the template */
140         ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
141         struct berval   querystr;       /* Filter string corresponding to the QT */
142         struct berval   bindbase;       /* base DN for Bind request */
143         struct berval   bindfilterstr;  /* Filter string for Bind request */
144         struct berval   bindftemp;      /* bind filter template */
145         Filter          *bindfilter;
146         AttributeDescription **bindfattrs;      /* attrs to substitute in ftemp */
147
148         int                     bindnattrs;             /* number of bindfattrs */
149         int                     bindscope;
150         int             attr_set_index; /* determines the projected attributes */
151         int             no_of_queries;  /* Total number of queries in the template */
152         time_t          ttl;            /* TTL for the queries of this template */
153         time_t          negttl;         /* TTL for negative results */
154         time_t          limitttl;       /* TTL for sizelimit exceeding results */
155         time_t          ttr;    /* time to refresh */
156         time_t          bindttr;        /* TTR for cached binds */
157         struct attr_set t_attrs;        /* filter attrs + attr_set */
158 } QueryTemplate;
159
160 typedef enum {
161         PC_IGNORE = 0,
162         PC_POSITIVE,
163         PC_NEGATIVE,
164         PC_SIZELIMIT
165 } pc_caching_reason_t;
166
167 static const char *pc_caching_reason_str[] = {
168         "IGNORE",
169         "POSITIVE",
170         "NEGATIVE",
171         "SIZELIMIT",
172
173         NULL
174 };
175
176 struct query_manager_s;
177
178 /* prototypes for functions for 1) query containment
179  * 2) query addition, 3) cache replacement
180  */
181 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
182         Query*, QueryTemplate*);
183 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
184         Query*, QueryTemplate*, pc_caching_reason_t, int wlock);
185 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
186
187 /* LDAP query cache */
188 typedef struct query_manager_s {
189         struct attr_set*        attr_sets;              /* possible sets of projected attributes */
190         QueryTemplate*          templates;              /* cacheable templates */
191
192         CachedQuery*            lru_top;                /* top and bottom of LRU list */
193         CachedQuery*            lru_bottom;
194
195         ldap_pvt_thread_mutex_t         lru_mutex;      /* mutex for accessing LRU list */
196
197         /* Query cache methods */
198         QCfunc                  *qcfunc;                        /* Query containment*/
199         CRfunc                  *crfunc;                        /* cache replacement */
200         AddQueryfunc    *addfunc;                       /* add query */
201 } query_manager;
202
203 /* LDAP query cache manager */
204 typedef struct cache_manager_s {
205         BackendDB       db;     /* underlying database */
206         unsigned long   num_cached_queries;             /* total number of cached queries */
207         unsigned long   max_queries;                    /* upper bound on # of cached queries */
208         int             save_queries;                   /* save cached queries across restarts */
209         int     check_cacheability;             /* check whether a query is cacheable */
210         int     numattrsets;                    /* number of attribute sets */
211         int     cur_entries;                    /* current number of entries cached */
212         int     max_entries;                    /* max number of entries cached */
213         int     num_entries_limit;              /* max # of entries in a cacheable query */
214
215         char    response_cb;                    /* install the response callback
216                                                  * at the tail of the callback list */
217 #define PCACHE_RESPONSE_CB_HEAD 0
218 #define PCACHE_RESPONSE_CB_TAIL 1
219         char    defer_db_open;                  /* defer open for online add */
220         char    cache_binds;                    /* cache binds or just passthru */
221
222         time_t  cc_period;              /* interval between successive consistency checks (sec) */
223 #define PCACHE_CC_PAUSED        1
224 #define PCACHE_CC_OFFLINE       2
225         int     cc_paused;
226         void    *cc_arg;
227
228         ldap_pvt_thread_mutex_t         cache_mutex;
229
230         query_manager*   qm;    /* query cache managed by the cache manager */
231
232 #ifdef PCACHE_MONITOR
233         void            *monitor_cb;
234         struct berval   monitor_ndn;
235 #endif /* PCACHE_MONITOR */
236 } cache_manager;
237
238 #ifdef PCACHE_MONITOR
239 static int pcache_monitor_db_init( BackendDB *be );
240 static int pcache_monitor_db_open( BackendDB *be );
241 static int pcache_monitor_db_close( BackendDB *be );
242 static int pcache_monitor_db_destroy( BackendDB *be );
243 #endif /* PCACHE_MONITOR */
244
245 static int pcache_debug;
246
247 #ifdef PCACHE_CONTROL_PRIVDB
248 static int privDB_cid;
249 #endif /* PCACHE_CONTROL_PRIVDB */
250
251 static AttributeDescription     *ad_queryId, *ad_cachedQueryURL;
252
253 #ifdef PCACHE_MONITOR
254 static AttributeDescription     *ad_numQueries, *ad_numEntries;
255 static ObjectClass              *oc_olmPCache;
256 #endif /* PCACHE_MONITOR */
257
258 static struct {
259         char                    *name;
260         char                    *oid;
261 }               s_oid[] = {
262         { "PCacheOID",                  "1.3.6.1.4.1.4203.666.11.9.1" },
263         { "PCacheAttributes",           "PCacheOID:1" },
264         { "PCacheObjectClasses",        "PCacheOID:2" },
265
266         { NULL }
267 };
268
269 static struct {
270         char    *desc;
271         AttributeDescription **adp;
272 } s_ad[] = {
273         { "( PCacheAttributes:1 "
274                 "NAME 'pcacheQueryID' "
275                 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
276                 "EQUALITY octetStringMatch "
277                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
278                 "NO-USER-MODIFICATION "
279                 "USAGE directoryOperation )",
280                 &ad_queryId },
281         { "( PCacheAttributes:2 "
282                 "NAME 'pcacheQueryURL' "
283                 "DESC 'URI describing a cached query' "
284                 "EQUALITY caseExactMatch "
285                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
286                 "NO-USER-MODIFICATION "
287                 "USAGE directoryOperation )",
288                 &ad_cachedQueryURL },
289 #ifdef PCACHE_MONITOR
290         { "( PCacheAttributes:3 "
291                 "NAME 'pcacheNumQueries' "
292                 "DESC 'Number of cached queries' "
293                 "EQUALITY integerMatch "
294                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
295                 "NO-USER-MODIFICATION "
296                 "USAGE directoryOperation )",
297                 &ad_numQueries },
298         { "( PCacheAttributes:4 "
299                 "NAME 'pcacheNumEntries' "
300                 "DESC 'Number of cached entries' "
301                 "EQUALITY integerMatch "
302                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
303                 "NO-USER-MODIFICATION "
304                 "USAGE directoryOperation )",
305                 &ad_numEntries },
306 #endif /* PCACHE_MONITOR */
307
308         { NULL }
309 };
310
311 static struct {
312         char            *desc;
313         ObjectClass     **ocp;
314 }               s_oc[] = {
315 #ifdef PCACHE_MONITOR
316         /* augments an existing object, so it must be AUXILIARY */
317         { "( PCacheObjectClasses:1 "
318                 "NAME ( 'olmPCache' ) "
319                 "SUP top AUXILIARY "
320                 "MAY ( "
321                         "pcacheQueryURL "
322                         "$ pcacheNumQueries "
323                         "$ pcacheNumEntries "
324                         " ) )",
325                 &oc_olmPCache },
326 #endif /* PCACHE_MONITOR */
327
328         { NULL }
329 };
330
331 static int
332 filter2template(
333         Operation               *op,
334         Filter                  *f,
335         struct                  berval *fstr );
336
337 static CachedQuery *
338 add_query(
339         Operation *op,
340         query_manager* qm,
341         Query* query,
342         QueryTemplate *templ,
343         pc_caching_reason_t why,
344         int wlock);
345
346 static int
347 remove_query_data(
348         Operation       *op,
349         SlapReply       *rs,
350         struct berval   *query_uuid );
351
352 /*
353  * Turn a cached query into its URL representation
354  */
355 static int
356 query2url( Operation *op, CachedQuery *q, struct berval *urlbv, int dolock )
357 {
358         struct berval   bv_scope,
359                         bv_filter;
360         char            attrset_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
361                         expiry_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
362                         refresh_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
363                         answerable_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
364                         *ptr;
365         ber_len_t       attrset_len,
366                         expiry_len,
367                         refresh_len,
368                         answerable_len;
369
370         if ( dolock ) {
371                 ldap_pvt_thread_rdwr_rlock( &q->rwlock );
372         }
373
374         ldap_pvt_scope2bv( q->scope, &bv_scope );
375         filter2bv_x( op, q->filter, &bv_filter );
376         attrset_len = sprintf( attrset_buf,
377                 "%lu", (unsigned long)q->qtemp->attr_set_index );
378         expiry_len = sprintf( expiry_buf,
379                 "%lu", (unsigned long)q->expiry_time );
380         answerable_len = snprintf( answerable_buf, sizeof( answerable_buf ),
381                 "%lu", q->answerable_cnt );
382         if ( q->refresh_time )
383                 refresh_len = sprintf( refresh_buf,
384                         "%lu", (unsigned long)q->refresh_time );
385         else
386                 refresh_len = 0;
387
388         urlbv->bv_len = STRLENOF( "ldap:///" )
389                 + q->qbase->base.bv_len
390                 + STRLENOF( "??" )
391                 + bv_scope.bv_len
392                 + STRLENOF( "?" )
393                 + bv_filter.bv_len
394                 + STRLENOF( "?x-uuid=" )
395                 + q->q_uuid.bv_len
396                 + STRLENOF( ",x-attrset=" )
397                 + attrset_len
398                 + STRLENOF( ",x-expiry=" )
399                 + expiry_len
400                 + STRLENOF( ",x-answerable=" )
401                 + answerable_len;
402         if ( refresh_len )
403                 urlbv->bv_len += STRLENOF( ",x-refresh=" )
404                 + refresh_len;
405
406         ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
407         ptr = lutil_strcopy( ptr, "ldap:///" );
408         ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
409         ptr = lutil_strcopy( ptr, "??" );
410         ptr = lutil_strcopy( ptr, bv_scope.bv_val );
411         ptr = lutil_strcopy( ptr, "?" );
412         ptr = lutil_strcopy( ptr, bv_filter.bv_val );
413         ptr = lutil_strcopy( ptr, "?x-uuid=" );
414         ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
415         ptr = lutil_strcopy( ptr, ",x-attrset=" );
416         ptr = lutil_strcopy( ptr, attrset_buf );
417         ptr = lutil_strcopy( ptr, ",x-expiry=" );
418         ptr = lutil_strcopy( ptr, expiry_buf );
419         ptr = lutil_strcopy( ptr, ",x-answerable=" );
420         ptr = lutil_strcopy( ptr, answerable_buf );
421         if ( refresh_len ) {
422                 ptr = lutil_strcopy( ptr, ",x-refresh=" );
423                 ptr = lutil_strcopy( ptr, refresh_buf );
424         }
425
426         ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
427
428         if ( dolock ) {
429                 ldap_pvt_thread_rdwr_runlock( &q->rwlock );
430         }
431
432         return 0;
433 }
434
435 /* Find and record the empty filter clauses */
436
437 static int
438 ftemp_attrs( struct berval *ftemp, struct berval *template,
439         AttributeDescription ***ret, const char **text )
440 {
441         int i;
442         int attr_cnt=0;
443         struct berval bv;
444         char *p1, *p2, *t1;
445         AttributeDescription *ad;
446         AttributeDescription **descs = NULL;
447         char *temp2;
448
449         temp2 = ch_malloc( ftemp->bv_len );
450         p1 = ftemp->bv_val;
451         t1 = temp2;
452
453         *ret = NULL;
454
455         for (;;) {
456                 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' )
457                         *t1++ = *p1++;
458
459                 p2 = strchr( p1, '=' );
460                 if ( !p2 )
461                         break;
462                 i = p2 - p1;
463                 AC_MEMCPY( t1, p1, i );
464                 t1 += i;
465                 *t1++ = '=';
466
467                 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
468                 bv.bv_val = p1;
469                 bv.bv_len = p2 - p1;
470                 ad = NULL;
471                 i = slap_bv2ad( &bv, &ad, text );
472                 if ( i ) {
473                         ch_free( descs );
474                         return -1;
475                 }
476                 if ( *p2 == '<' || *p2 == '>' ) p2++;
477                 if ( p2[1] != ')' ) {
478                         p2++;
479                         while ( *p2 != ')' ) p2++;
480                         p1 = p2;
481                         continue;
482                 }
483
484                 descs = (AttributeDescription **)ch_realloc(descs,
485                                 (attr_cnt + 2)*sizeof(AttributeDescription *));
486
487                 descs[attr_cnt++] = ad;
488
489                 p1 = p2+1;
490         }
491         *t1 = '\0';
492         descs[attr_cnt] = NULL;
493         *ret = descs;
494         template->bv_val = temp2;
495         template->bv_len = t1 - temp2;
496         return attr_cnt;
497 }
498
499 static int
500 template_attrs( char *template, struct attr_set *set, AttributeName **ret,
501         const char **text )
502 {
503         int got_oc = 0;
504         int alluser = 0;
505         int allop = 0;
506         int i;
507         int attr_cnt;
508         int t_cnt = 0;
509         struct berval bv;
510         char *p1, *p2;
511         AttributeDescription *ad;
512         AttributeName *attrs;
513
514         p1 = template;
515
516         *ret = NULL;
517
518         attrs = ch_calloc( set->count + 1, sizeof(AttributeName) );
519         for ( i=0; i < set->count; i++ )
520                 attrs[i] = set->attrs[i];
521         attr_cnt = i;
522         alluser = an_find( attrs, slap_bv_all_user_attrs );
523         allop = an_find( attrs, slap_bv_all_operational_attrs );
524
525         for (;;) {
526                 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' ) p1++;
527                 p2 = strchr( p1, '=' );
528                 if ( !p2 )
529                         break;
530                 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
531                 bv.bv_val = p1;
532                 bv.bv_len = p2 - p1;
533                 ad = NULL;
534                 i = slap_bv2ad( &bv, &ad, text );
535                 if ( i ) {
536                         ch_free( attrs );
537                         return -1;
538                 }
539                 t_cnt++;
540
541                 if ( ad == slap_schema.si_ad_objectClass )
542                         got_oc = 1;
543
544                 if ( is_at_operational(ad->ad_type)) {
545                         if ( allop ) {
546                                 goto bottom;
547                         }
548                 } else if ( alluser ) {
549                         goto bottom;
550                 }
551                 if ( !ad_inlist( ad, attrs )) {
552                         attrs = (AttributeName *)ch_realloc(attrs,
553                                         (attr_cnt + 2)*sizeof(AttributeName));
554
555                         attrs[attr_cnt].an_desc = ad;
556                         attrs[attr_cnt].an_name = ad->ad_cname;
557                         attrs[attr_cnt].an_oc = NULL;
558                         attrs[attr_cnt].an_flags = 0;
559                         BER_BVZERO( &attrs[attr_cnt+1].an_name );
560                         attr_cnt++;
561                 }
562
563 bottom:
564                 p1 = p2+2;
565         }
566         if ( !t_cnt ) {
567                 *text = "couldn't parse template";
568                 return -1;
569         }
570         if ( !got_oc && !( set->flags & PC_GOT_OC )) {
571                 attrs = (AttributeName *)ch_realloc(attrs,
572                                 (attr_cnt + 2)*sizeof(AttributeName));
573
574                 ad = slap_schema.si_ad_objectClass;
575                 attrs[attr_cnt].an_desc = ad;
576                 attrs[attr_cnt].an_name = ad->ad_cname;
577                 attrs[attr_cnt].an_oc = NULL;
578                 attrs[attr_cnt].an_flags = 0;
579                 BER_BVZERO( &attrs[attr_cnt+1].an_name );
580                 attr_cnt++;
581         }
582         *ret = attrs;
583         return attr_cnt;
584 }
585
586 /*
587  * Turn an URL representing a formerly cached query into a cached query,
588  * and try to cache it
589  */
590 static int
591 url2query(
592         char            *url,
593         Operation       *op,
594         query_manager   *qm )
595 {
596         Query           query = { 0 };
597         QueryTemplate   *qt;
598         CachedQuery     *cq;
599         LDAPURLDesc     *lud = NULL;
600         struct berval   base,
601                         tempstr = BER_BVNULL,
602                         uuid;
603         int             attrset;
604         time_t          expiry_time;
605         time_t          refresh_time;
606         unsigned long   answerable_cnt;
607         int             i,
608                         got = 0,
609 #define GOT_UUID        0x1U
610 #define GOT_ATTRSET     0x2U
611 #define GOT_EXPIRY      0x4U
612 #define GOT_ANSWERABLE  0x8U
613 #define GOT_REFRESH     0x10U
614 #define GOT_ALL         (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
615                         rc = 0;
616
617         rc = ldap_url_parse( url, &lud );
618         if ( rc != LDAP_URL_SUCCESS ) {
619                 return -1;
620         }
621
622         /* non-allowed fields */
623         if ( lud->lud_host != NULL ) {
624                 rc = 1;
625                 goto error;
626         }
627
628         if ( lud->lud_attrs != NULL ) {
629                 rc = 1;
630                 goto error;
631         }
632
633         /* be pedantic */
634         if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
635                 rc = 1;
636                 goto error;
637         }
638
639         /* required fields */
640         if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
641                 rc = 1;
642                 goto error;
643         }
644
645         switch ( lud->lud_scope ) {
646         case LDAP_SCOPE_BASE:
647         case LDAP_SCOPE_ONELEVEL:
648         case LDAP_SCOPE_SUBTREE:
649         case LDAP_SCOPE_SUBORDINATE:
650                 break;
651
652         default:
653                 rc = 1;
654                 goto error;
655         }
656
657         if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
658                 rc = 1;
659                 goto error;
660         }
661
662         if ( lud->lud_exts == NULL ) {
663                 rc = 1;
664                 goto error;
665         }
666
667         for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
668                 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
669                         struct berval   tmpUUID;
670                         Syntax          *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
671
672                         if ( got & GOT_UUID ) {
673                                 rc = 1;
674                                 goto error;
675                         }
676
677                         ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
678                         rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
679                         if ( rc != LDAP_SUCCESS ) {
680                                 goto error;
681                         }
682                         got |= GOT_UUID;
683
684                 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
685                         if ( got & GOT_ATTRSET ) {
686                                 rc = 1;
687                                 goto error;
688                         }
689
690                         rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
691                         if ( rc ) {
692                                 goto error;
693                         }
694                         got |= GOT_ATTRSET;
695
696                 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
697                         unsigned long l;
698
699                         if ( got & GOT_EXPIRY ) {
700                                 rc = 1;
701                                 goto error;
702                         }
703
704                         rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
705                         if ( rc ) {
706                                 goto error;
707                         }
708                         expiry_time = (time_t)l;
709                         got |= GOT_EXPIRY;
710
711                 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
712                         if ( got & GOT_ANSWERABLE ) {
713                                 rc = 1;
714                                 goto error;
715                         }
716
717                         rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
718                         if ( rc ) {
719                                 goto error;
720                         }
721                         got |= GOT_ANSWERABLE;
722
723                 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
724                         unsigned long l;
725
726                         if ( got & GOT_REFRESH ) {
727                                 rc = 1;
728                                 goto error;
729                         }
730
731                         rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
732                         if ( rc ) {
733                                 goto error;
734                         }
735                         refresh_time = (time_t)l;
736                         got |= GOT_REFRESH;
737
738                 } else {
739                         rc = -1;
740                         goto error;
741                 }
742         }
743
744         if ( got != GOT_ALL ) {
745                 rc = 1;
746                 goto error;
747         }
748
749         if ( !(got & GOT_REFRESH ))
750                 refresh_time = 0;
751
752         /* ignore expired queries */
753         if ( expiry_time <= slap_get_time()) {
754                 Operation       op2 = *op;
755                 SlapReply       rs2 = { 0 };
756
757                 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
758
759                 (void)remove_query_data( &op2, &rs2, &uuid );
760
761                 rc = 0;
762
763         } else {
764                 ber_str2bv( lud->lud_dn, 0, 0, &base );
765                 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
766                 if ( rc != LDAP_SUCCESS ) {
767                         goto error;
768                 }
769                 query.scope = lud->lud_scope;
770                 query.filter = str2filter( lud->lud_filter );
771                 if ( query.filter == NULL ) {
772                         rc = -1;
773                         goto error;
774                 }
775
776                 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
777                 tempstr.bv_len = 0;
778                 if ( filter2template( op, query.filter, &tempstr ) ) {
779                         ch_free( tempstr.bv_val );
780                         rc = -1;
781                         goto error;
782                 }
783
784                 /* check for query containment */
785                 qt = qm->attr_sets[attrset].templates;
786                 for ( ; qt; qt = qt->qtnext ) {
787                         /* find if template i can potentially answer tempstr */
788                         if ( bvmatch( &qt->querystr, &tempstr ) ) {
789                                 break;
790                         }
791                 }
792
793                 if ( qt == NULL ) {
794                         rc = 1;
795                         goto error;
796                 }
797
798                 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
799                 if ( cq != NULL ) {
800                         cq->expiry_time = expiry_time;
801                         cq->refresh_time = refresh_time;
802                         cq->q_uuid = uuid;
803                         cq->answerable_cnt = answerable_cnt;
804                         cq->refcnt = 0;
805
806                         /* it's now into cq->filter */
807                         BER_BVZERO( &uuid );
808                         query.filter = NULL;
809
810                 } else {
811                         rc = 1;
812                 }
813         }
814
815 error:;
816         if ( query.filter != NULL ) filter_free( query.filter );
817         if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
818         if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
819         if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
820         if ( lud != NULL ) ldap_free_urldesc( lud );
821
822         return rc;
823 }
824
825 /* Return 1 for an added entry, else 0 */
826 static int
827 merge_entry(
828         Operation               *op,
829         Entry                   *e,
830         int                     dup,
831         struct berval*          query_uuid )
832 {
833         int             rc;
834         Modifications* modlist = NULL;
835         const char*     text = NULL;
836         Attribute               *attr;
837         char                    textbuf[SLAP_TEXT_BUFLEN];
838         size_t                  textlen = sizeof(textbuf);
839
840         SlapReply sreply = {REP_RESULT};
841
842         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
843
844         if ( dup )
845                 e = entry_dup( e );
846         attr = e->e_attrs;
847         e->e_attrs = NULL;
848
849         /* add queryId attribute */
850         attr_merge_one( e, ad_queryId, query_uuid, NULL );
851
852         /* append the attribute list from the fetched entry */
853         e->e_attrs->a_next = attr;
854
855         op->o_tag = LDAP_REQ_ADD;
856         op->o_protocol = LDAP_VERSION3;
857         op->o_callback = &cb;
858         op->o_time = slap_get_time();
859         op->o_do_not_cache = 1;
860
861         op->ora_e = e;
862         op->o_req_dn = e->e_name;
863         op->o_req_ndn = e->e_nname;
864         rc = op->o_bd->be_add( op, &sreply );
865
866         if ( rc != LDAP_SUCCESS ) {
867                 if ( rc == LDAP_ALREADY_EXISTS ) {
868                         slap_entry2mods( e, &modlist, &text, textbuf, textlen );
869                         modlist->sml_op = LDAP_MOD_ADD;
870                         op->o_tag = LDAP_REQ_MODIFY;
871                         op->orm_modlist = modlist;
872                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
873                         op->o_bd->be_modify( op, &sreply );
874                         slap_mods_free( modlist, 1 );
875                 } else if ( rc == LDAP_REFERRAL ||
876                                         rc == LDAP_NO_SUCH_OBJECT ) {
877                         syncrepl_add_glue( op, e );
878                         e = NULL;
879                         rc = 1;
880                 }
881                 if ( e ) {
882                         entry_free( e );
883                         rc = 0;
884                 }
885         } else {
886                 if ( op->ora_e == e )
887                         entry_free( e );
888                 rc = 1;
889         }
890
891         return rc;
892 }
893
894 /* Length-ordered sort on normalized DNs */
895 static int pcache_dn_cmp( const void *v1, const void *v2 )
896 {
897         const Qbase *q1 = v1, *q2 = v2;
898
899         int rc = q1->base.bv_len - q2->base.bv_len;
900         if ( rc == 0 )
901                 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
902         return rc;
903 }
904
905 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
906 {
907         int len, dif;
908         dif = bv1->bv_len - bv2->bv_len;
909         len = bv1->bv_len;
910         if ( dif > 0 ) len -= dif;
911         len = memcmp( bv1->bv_val, bv2->bv_val, len );
912         if ( !len )
913                 len = dif;
914         return len;
915 }
916
917 /* compare the current value in each filter */
918 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
919 {
920         int rc, weight1, weight2;
921
922         switch( f1->f_choice ) {
923         case LDAP_FILTER_PRESENT:
924                 weight1 = 0;
925                 break;
926         case LDAP_FILTER_EQUALITY:
927         case LDAP_FILTER_GE:
928         case LDAP_FILTER_LE:
929                 weight1 = 1;
930                 break;
931         default:
932                 weight1 = 2;
933         }
934         switch( f2->f_choice ) {
935         case LDAP_FILTER_PRESENT:
936                 weight2 = 0;
937                 break;
938         case LDAP_FILTER_EQUALITY:
939         case LDAP_FILTER_GE:
940         case LDAP_FILTER_LE:
941                 weight2 = 1;
942                 break;
943         default:
944                 weight2 = 2;
945         }
946         rc = weight1 - weight2;
947         if ( !rc ) {
948                 switch( weight1 ) {
949                 case 0:
950                         break;
951                 case 1:
952                         rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
953                         break;
954                 case 2:
955                         if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
956                                 rc = 0;
957                                 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
958                                         if ( !BER_BVISNULL( &f2->f_sub_initial )) {
959                                                 rc = lex_bvcmp( &f1->f_sub_initial,
960                                                         &f2->f_sub_initial );
961                                         } else {
962                                                 rc = 1;
963                                         }
964                                 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
965                                         rc = -1;
966                                 }
967                                 if ( rc ) break;
968                                 if ( f1->f_sub_any ) {
969                                         if ( f2->f_sub_any ) {
970                                                 rc = lex_bvcmp( f1->f_sub_any,
971                                                         f2->f_sub_any );
972                                         } else {
973                                                 rc = 1;
974                                         }
975                                 } else if ( f2->f_sub_any ) {
976                                         rc = -1;
977                                 }
978                                 if ( rc ) break;
979                                 if ( !BER_BVISNULL( &f1->f_sub_final )) {
980                                         if ( !BER_BVISNULL( &f2->f_sub_final )) {
981                                                 rc = lex_bvcmp( &f1->f_sub_final,
982                                                         &f2->f_sub_final );
983                                         } else {
984                                                 rc = 1;
985                                         }
986                                 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
987                                         rc = -1;
988                                 }
989                         } else {
990                                 rc = lex_bvcmp( &f1->f_mr_value,
991                                         &f2->f_mr_value );
992                         }
993                         break;
994                 }
995                 if ( !rc ) {
996                         f1 = f1->f_next;
997                         f2 = f2->f_next;
998                         if ( f1 || f2 ) {
999                                 if ( !f1 )
1000                                         rc = -1;
1001                                 else if ( !f2 )
1002                                         rc = 1;
1003                                 else {
1004                                         while ( f1->f_choice == LDAP_FILTER_AND || f1->f_choice == LDAP_FILTER_OR )
1005                                                 f1 = f1->f_and;
1006                                         while ( f2->f_choice == LDAP_FILTER_AND || f2->f_choice == LDAP_FILTER_OR )
1007                                                 f2 = f2->f_and;
1008                                         rc = pcache_filter_cmp( f1, f2 );
1009                                 }
1010                         }
1011                 }
1012         }
1013         return rc;
1014 }
1015
1016 /* compare filters in each query */
1017 static int pcache_query_cmp( const void *v1, const void *v2 )
1018 {
1019         const CachedQuery *q1 = v1, *q2 =v2;
1020         return pcache_filter_cmp( q1->first, q2->first );
1021 }
1022
1023 /* add query on top of LRU list */
1024 static void
1025 add_query_on_top (query_manager* qm, CachedQuery* qc)
1026 {
1027         CachedQuery* top = qm->lru_top;
1028
1029         qm->lru_top = qc;
1030
1031         if (top)
1032                 top->lru_up = qc;
1033         else
1034                 qm->lru_bottom = qc;
1035
1036         qc->lru_down = top;
1037         qc->lru_up = NULL;
1038         Debug( pcache_debug, "Base of added query = %s\n",
1039                         qc->qbase->base.bv_val, 0, 0 );
1040 }
1041
1042 /* remove_query from LRU list */
1043
1044 static void
1045 remove_query (query_manager* qm, CachedQuery* qc)
1046 {
1047         CachedQuery* up;
1048         CachedQuery* down;
1049
1050         if (!qc)
1051                 return;
1052
1053         up = qc->lru_up;
1054         down = qc->lru_down;
1055
1056         if (!up)
1057                 qm->lru_top = down;
1058
1059         if (!down)
1060                 qm->lru_bottom = up;
1061
1062         if (down)
1063                 down->lru_up = up;
1064
1065         if (up)
1066                 up->lru_down = down;
1067
1068         qc->lru_up = qc->lru_down = NULL;
1069 }
1070
1071 /* find and remove string2 from string1
1072  * from start if position = 1,
1073  * from end if position = 3,
1074  * from anywhere if position = 2
1075  * string1 is overwritten if position = 2.
1076  */
1077
1078 static int
1079 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
1080 {
1081         int ret=0;
1082
1083         if ( !ber2->bv_val )
1084                 return 1;
1085         if ( !ber1->bv_val )
1086                 return 0;
1087
1088         switch( position ) {
1089         case 1:
1090                 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
1091                         ber2->bv_val, ber2->bv_len )) {
1092                         ret = 1;
1093                         ber1->bv_val += ber2->bv_len;
1094                         ber1->bv_len -= ber2->bv_len;
1095                 }
1096                 break;
1097         case 2: {
1098                 char *temp;
1099                 ber1->bv_val[ber1->bv_len] = '\0';
1100                 temp = strstr( ber1->bv_val, ber2->bv_val );
1101                 if ( temp ) {
1102                         strcpy( temp, temp+ber2->bv_len );
1103                         ber1->bv_len -= ber2->bv_len;
1104                         ret = 1;
1105                 }
1106                 break;
1107                 }
1108         case 3:
1109                 if ( ber1->bv_len >= ber2->bv_len &&
1110                         !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
1111                                 ber2->bv_len )) {
1112                         ret = 1;
1113                         ber1->bv_len -= ber2->bv_len;
1114                 }
1115                 break;
1116         }
1117         return ret;
1118 }
1119
1120
1121 static struct berval*
1122 merge_init_final(Operation *op, struct berval* init, struct berval* any,
1123         struct berval* final)
1124 {
1125         struct berval* merged, *temp;
1126         int i, any_count, count;
1127
1128         for (any_count=0; any && any[any_count].bv_val; any_count++)
1129                 ;
1130
1131         count = any_count;
1132
1133         if (init->bv_val)
1134                 count++;
1135         if (final->bv_val)
1136                 count++;
1137
1138         merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
1139                 op->o_tmpmemctx );
1140         temp = merged;
1141
1142         if (init->bv_val) {
1143                 ber_dupbv_x( temp, init, op->o_tmpmemctx );
1144                 temp++;
1145         }
1146
1147         for (i=0; i<any_count; i++) {
1148                 ber_dupbv_x( temp, any, op->o_tmpmemctx );
1149                 temp++; any++;
1150         }
1151
1152         if (final->bv_val){
1153                 ber_dupbv_x( temp, final, op->o_tmpmemctx );
1154                 temp++;
1155         }
1156         BER_BVZERO( temp );
1157         return merged;
1158 }
1159
1160 /* Each element in stored must be found in incoming. Incoming is overwritten.
1161  */
1162 static int
1163 strings_containment(struct berval* stored, struct berval* incoming)
1164 {
1165         struct berval* element;
1166         int k=0;
1167         int j, rc = 0;
1168
1169         for ( element=stored; element->bv_val != NULL; element++ ) {
1170                 for (j = k; incoming[j].bv_val != NULL; j++) {
1171                         if (find_and_remove(&(incoming[j]), element, 2)) {
1172                                 k = j;
1173                                 rc = 1;
1174                                 break;
1175                         }
1176                         rc = 0;
1177                 }
1178                 if ( rc ) {
1179                         continue;
1180                 } else {
1181                         return 0;
1182                 }
1183         }
1184         return 1;
1185 }
1186
1187 static int
1188 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
1189 {
1190         int rc = 0;
1191
1192         struct berval init_incoming;
1193         struct berval final_incoming;
1194         struct berval *remaining_incoming = NULL;
1195
1196         if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
1197            || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
1198                 return 0;
1199
1200         init_incoming = incoming->f_sub_initial;
1201         final_incoming =  incoming->f_sub_final;
1202
1203         if (find_and_remove(&init_incoming,
1204                         &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
1205                         &(stored->f_sub_final), 3))
1206         {
1207                 if (stored->f_sub_any == NULL) {
1208                         rc = 1;
1209                         goto final;
1210                 }
1211                 remaining_incoming = merge_init_final(op, &init_incoming,
1212                                                 incoming->f_sub_any, &final_incoming);
1213                 rc = strings_containment(stored->f_sub_any, remaining_incoming);
1214                 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
1215         }
1216 final:
1217         return rc;
1218 }
1219
1220 static int
1221 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
1222 {
1223         struct berval incoming_val[2];
1224         int rc = 0;
1225
1226         incoming_val[1] = incoming->f_av_value;
1227
1228         if (find_and_remove(incoming_val+1,
1229                         &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
1230                         &(stored->f_sub_final), 3)) {
1231                 if (stored->f_sub_any == NULL){
1232                         rc = 1;
1233                         goto final;
1234                 }
1235                 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
1236                 BER_BVZERO( incoming_val+1 );
1237                 rc = strings_containment(stored->f_sub_any, incoming_val);
1238                 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1239         }
1240 final:
1241         return rc;
1242 }
1243
1244 static Filter *
1245 filter_first( Filter *f )
1246 {
1247         while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1248                 f = f->f_and;
1249         return f;
1250 }
1251
1252
1253 static CachedQuery *
1254 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
1255 {
1256         Filter* fs;
1257         Filter* fi;
1258         MatchingRule* mrule = NULL;
1259         int res=0, eqpass= 0;
1260         int ret, rc, dir;
1261         Avlnode *ptr;
1262         CachedQuery cq, *qc;
1263
1264         cq.filter = inputf;
1265         cq.first = first;
1266
1267         /* substring matches sort to the end, and we just have to
1268          * walk the entire list.
1269          */
1270         if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1271                 ptr = tavl_end( root, 1 );
1272                 dir = TAVL_DIR_LEFT;
1273         } else {
1274                 ptr = tavl_find3( root, &cq, pcache_query_cmp, &ret );
1275                 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1276                         TAVL_DIR_RIGHT;
1277         }
1278
1279         while (ptr) {
1280                 qc = ptr->avl_data;
1281                 fi = inputf;
1282                 fs = qc->filter;
1283
1284                 /* an incoming substr query can only be satisfied by a cached
1285                  * substr query.
1286                  */
1287                 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1288                         qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1289                         break;
1290
1291                 /* an incoming eq query can be satisfied by a cached eq or substr
1292                  * query
1293                  */
1294                 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1295                         if ( eqpass == 0 ) {
1296                                 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1297 nextpass:                       eqpass = 1;
1298                                         ptr = tavl_end( root, 1 );
1299                                         dir = TAVL_DIR_LEFT;
1300                                         continue;
1301                                 }
1302                         } else {
1303                                 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1304                                         break;
1305                         }
1306                 }
1307                 do {
1308                         res=0;
1309                         switch (fs->f_choice) {
1310                         case LDAP_FILTER_EQUALITY:
1311                                 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1312                                         mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1313                                 else
1314                                         ret = 1;
1315                                 break;
1316                         case LDAP_FILTER_GE:
1317                         case LDAP_FILTER_LE:
1318                                 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1319                                 break;
1320                         default:
1321                                 mrule = NULL; 
1322                         }
1323                         if (mrule) {
1324                                 const char *text;
1325                                 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1326                                         SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1327                                         &(fi->f_ava->aa_value),
1328                                         &(fs->f_ava->aa_value), &text);
1329                                 if (rc != LDAP_SUCCESS) {
1330                                         return NULL;
1331                                 }
1332                                 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1333                                         goto nextpass;
1334                         }
1335                         switch (fs->f_choice) {
1336                         case LDAP_FILTER_OR:
1337                         case LDAP_FILTER_AND:
1338                                 fs = fs->f_and;
1339                                 fi = fi->f_and;
1340                                 res=1;
1341                                 break;
1342                         case LDAP_FILTER_SUBSTRINGS:
1343                                 /* check if the equality query can be
1344                                 * answered with cached substring query */
1345                                 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1346                                         && substr_containment_equality( op,
1347                                         fs, fi))
1348                                         res=1;
1349                                 /* check if the substring query can be
1350                                 * answered with cached substring query */
1351                                 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1352                                         ) && substr_containment_substr( op,
1353                                         fs, fi))
1354                                         res= 1;
1355                                 fs=fs->f_next;
1356                                 fi=fi->f_next;
1357                                 break;
1358                         case LDAP_FILTER_PRESENT:
1359                                 res=1;
1360                                 fs=fs->f_next;
1361                                 fi=fi->f_next;
1362                                 break;
1363                         case LDAP_FILTER_EQUALITY:
1364                                 if (ret == 0)
1365                                         res = 1;
1366                                 fs=fs->f_next;
1367                                 fi=fi->f_next;
1368                                 break;
1369                         case LDAP_FILTER_GE:
1370                                 if (mrule && ret >= 0)
1371                                         res = 1;
1372                                 fs=fs->f_next;
1373                                 fi=fi->f_next;
1374                                 break;
1375                         case LDAP_FILTER_LE:
1376                                 if (mrule && ret <= 0)
1377                                         res = 1;
1378                                 fs=fs->f_next;
1379                                 fi=fi->f_next;
1380                                 break;
1381                         case LDAP_FILTER_NOT:
1382                                 res=0;
1383                                 break;
1384                         default:
1385                                 break;
1386                         }
1387                 } while((res) && (fi != NULL) && (fs != NULL));
1388
1389                 if ( res )
1390                         return qc;
1391                 ptr = tavl_next( ptr, dir );
1392         }
1393         return NULL;
1394 }
1395
1396 /* check whether query is contained in any of
1397  * the cached queries in template
1398  */
1399 static CachedQuery *
1400 query_containment(Operation *op, query_manager *qm,
1401                   Query *query,
1402                   QueryTemplate *templa)
1403 {
1404         CachedQuery* qc;
1405         int depth = 0, tscope;
1406         Qbase qbase, *qbptr = NULL;
1407         struct berval pdn;
1408
1409         if (query->filter != NULL) {
1410                 Filter *first;
1411
1412                 Debug( pcache_debug, "Lock QC index = %p\n",
1413                                 (void *) templa, 0, 0 );
1414                 qbase.base = query->base;
1415
1416                 first = filter_first( query->filter );
1417
1418                 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1419                 for( ;; ) {
1420                         /* Find the base */
1421                         qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1422                         if ( qbptr ) {
1423                                 tscope = query->scope;
1424                                 /* Find a matching scope:
1425                                  * match at depth 0 OK
1426                                  * scope is BASE,
1427                                  *      one at depth 1 OK
1428                                  *  subord at depth > 0 OK
1429                                  *      subtree at any depth OK
1430                                  * scope is ONE,
1431                                  *  subtree or subord at any depth OK
1432                                  * scope is SUBORD,
1433                                  *  subtree or subord at any depth OK
1434                                  * scope is SUBTREE,
1435                                  *  subord at depth > 0 OK
1436                                  *  subtree at any depth OK
1437                                  */
1438                                 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1439                                         switch ( query->scope ) {
1440                                         case LDAP_SCOPE_BASE:
1441                                                 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1442                                                 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1443                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1444                                                 break;
1445                                         case LDAP_SCOPE_ONE:
1446                                                 if ( tscope == LDAP_SCOPE_BASE )
1447                                                         tscope = LDAP_SCOPE_ONE;
1448                                                 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1449                                                 if ( !depth ) break;
1450                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1451                                                         tscope = LDAP_SCOPE_SUBTREE;
1452                                                 break;
1453                                         case LDAP_SCOPE_SUBTREE:
1454                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1455                                                         tscope = LDAP_SCOPE_SUBTREE;
1456                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1457                                                 break;
1458                                         case LDAP_SCOPE_CHILDREN:
1459                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1460                                                         tscope = LDAP_SCOPE_SUBTREE;
1461                                                 break;
1462                                         }
1463                                         if ( !qbptr->scopes[tscope] ) continue;
1464
1465                                         /* Find filter */
1466                                         qc = find_filter( op, qbptr->scopes[tscope],
1467                                                         query->filter, first );
1468                                         if ( qc ) {
1469                                                 if ( qc->q_sizelimit ) {
1470                                                         ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1471                                                         return NULL;
1472                                                 }
1473                                                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1474                                                 if (qm->lru_top != qc) {
1475                                                         remove_query(qm, qc);
1476                                                         add_query_on_top(qm, qc);
1477                                                 }
1478                                                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1479                                                 return qc;
1480                                         }
1481                                 }
1482                         }
1483                         if ( be_issuffix( op->o_bd, &qbase.base ))
1484                                 break;
1485                         /* Up a level */
1486                         dnParent( &qbase.base, &pdn );
1487                         qbase.base = pdn;
1488                         depth++;
1489                 }
1490
1491                 Debug( pcache_debug,
1492                         "Not answerable: Unlock QC index=%p\n",
1493                         (void *) templa, 0, 0 );
1494                 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1495         }
1496         return NULL;
1497 }
1498
1499 static void
1500 free_query (CachedQuery* qc)
1501 {
1502         free(qc->q_uuid.bv_val);
1503         filter_free(qc->filter);
1504         ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1505         ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1506         memset(qc, 0, sizeof(*qc));
1507         free(qc);
1508 }
1509
1510
1511 /* Add query to query cache, the returned Query is locked for writing */
1512 static CachedQuery *
1513 add_query(
1514         Operation *op,
1515         query_manager* qm,
1516         Query* query,
1517         QueryTemplate *templ,
1518         pc_caching_reason_t why,
1519         int wlock)
1520 {
1521         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1522         Qbase *qbase, qb;
1523         Filter *first;
1524         int rc;
1525         time_t ttl = 0, ttr = 0;
1526         time_t now;
1527
1528         new_cached_query->qtemp = templ;
1529         BER_BVZERO( &new_cached_query->q_uuid );
1530         new_cached_query->q_sizelimit = 0;
1531
1532         now = slap_get_time();
1533         switch ( why ) {
1534         case PC_POSITIVE:
1535                 ttl = templ->ttl;
1536                 if ( templ->ttr )
1537                         ttr = now + templ->ttr;
1538                 break;
1539
1540         case PC_NEGATIVE:
1541                 ttl = templ->negttl;
1542                 break;
1543
1544         case PC_SIZELIMIT:
1545                 ttl = templ->limitttl;
1546                 break;
1547
1548         default:
1549                 assert( 0 );
1550                 break;
1551         }
1552         new_cached_query->expiry_time = now + ttl;
1553         new_cached_query->refresh_time = ttr;
1554
1555         new_cached_query->answerable_cnt = 0;
1556         new_cached_query->refcnt = 1;
1557         ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1558
1559         new_cached_query->lru_up = NULL;
1560         new_cached_query->lru_down = NULL;
1561         Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1562                         (long) new_cached_query->expiry_time,
1563                         pc_caching_reason_str[ why ], 0 );
1564
1565         new_cached_query->scope = query->scope;
1566         new_cached_query->filter = query->filter;
1567         new_cached_query->first = first = filter_first( query->filter );
1568         
1569         ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1570         if (wlock)
1571                 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1572
1573         qb.base = query->base;
1574
1575         /* Adding a query    */
1576         Debug( pcache_debug, "Lock AQ index = %p\n",
1577                         (void *) templ, 0, 0 );
1578         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1579         qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1580         if ( !qbase ) {
1581                 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1582                 qbase->base.bv_len = qb.base.bv_len;
1583                 qbase->base.bv_val = (char *)(qbase+1);
1584                 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1585                 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1586                 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1587         }
1588         new_cached_query->next = templ->query;
1589         new_cached_query->prev = NULL;
1590         new_cached_query->qbase = qbase;
1591         rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1592                 pcache_query_cmp, avl_dup_error );
1593         if ( rc == 0 ) {
1594                 qbase->queries++;
1595                 if (templ->query == NULL)
1596                         templ->query_last = new_cached_query;
1597                 else
1598                         templ->query->prev = new_cached_query;
1599                 templ->query = new_cached_query;
1600                 templ->no_of_queries++;
1601         } else {
1602                 ldap_pvt_thread_mutex_destroy(&new_cached_query->answerable_cnt_mutex);
1603                 ldap_pvt_thread_rdwr_destroy( &new_cached_query->rwlock );
1604                 ch_free( new_cached_query );
1605                 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1606                                                         query->filter, first );
1607                 filter_free( query->filter );
1608                 query->filter = NULL;
1609         }
1610         Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1611                         (void *) templ, templ->no_of_queries, 0 );
1612
1613         Debug( pcache_debug, "Unlock AQ index = %p \n",
1614                         (void *) templ, 0, 0 );
1615         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1616
1617         /* Adding on top of LRU list  */
1618         if ( rc == 0 ) {
1619                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1620                 add_query_on_top(qm, new_cached_query);
1621                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1622         }
1623         return rc == 0 ? new_cached_query : NULL;
1624 }
1625
1626 static void
1627 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1628 {
1629         if (!qc->prev && !qc->next) {
1630                 template->query_last = template->query = NULL;
1631         } else if (qc->prev == NULL) {
1632                 qc->next->prev = NULL;
1633                 template->query = qc->next;
1634         } else if (qc->next == NULL) {
1635                 qc->prev->next = NULL;
1636                 template->query_last = qc->prev;
1637         } else {
1638                 qc->next->prev = qc->prev;
1639                 qc->prev->next = qc->next;
1640         }
1641         tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1642         qc->qbase->queries--;
1643         if ( qc->qbase->queries == 0 ) {
1644                 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1645                 ch_free( qc->qbase );
1646                 qc->qbase = NULL;
1647         }
1648
1649         template->no_of_queries--;
1650 }
1651
1652 /* remove bottom query of LRU list from the query cache */
1653 /*
1654  * NOTE: slight change in functionality.
1655  *
1656  * - if result->bv_val is NULL, the query at the bottom of the LRU
1657  *   is removed
1658  * - otherwise, the query whose UUID is *result is removed
1659  *      - if not found, result->bv_val is zeroed
1660  */
1661 static void
1662 cache_replacement(query_manager* qm, struct berval *result)
1663 {
1664         CachedQuery* bottom;
1665         QueryTemplate *temp;
1666
1667         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1668         if ( BER_BVISNULL( result ) ) {
1669                 bottom = qm->lru_bottom;
1670
1671                 if (!bottom) {
1672                         Debug ( pcache_debug,
1673                                 "Cache replacement invoked without "
1674                                 "any query in LRU list\n", 0, 0, 0 );
1675                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1676                         return;
1677                 }
1678
1679         } else {
1680                 for ( bottom = qm->lru_bottom;
1681                         bottom != NULL;
1682                         bottom = bottom->lru_up )
1683                 {
1684                         if ( bvmatch( result, &bottom->q_uuid ) ) {
1685                                 break;
1686                         }
1687                 }
1688
1689                 if ( !bottom ) {
1690                         Debug ( pcache_debug,
1691                                 "Could not find query with uuid=\"%s\""
1692                                 "in LRU list\n", result->bv_val, 0, 0 );
1693                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1694                         BER_BVZERO( result );
1695                         return;
1696                 }
1697         }
1698
1699         temp = bottom->qtemp;
1700         remove_query(qm, bottom);
1701         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1702
1703         *result = bottom->q_uuid;
1704         BER_BVZERO( &bottom->q_uuid );
1705
1706         Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1707         ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1708         remove_from_template(bottom, temp);
1709         Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1710                 (void *) temp, temp->no_of_queries, 0 );
1711         Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1712         ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1713         free_query(bottom);
1714 }
1715
1716 struct query_info {
1717         struct query_info *next;
1718         struct berval xdn;
1719         int del;
1720 };
1721
1722 static int
1723 remove_func (
1724         Operation       *op,
1725         SlapReply       *rs
1726 )
1727 {
1728         Attribute *attr;
1729         struct query_info *qi;
1730         int count = 0;
1731
1732         if ( rs->sr_type != REP_SEARCH ) return 0;
1733
1734         attr = attr_find( rs->sr_entry->e_attrs,  ad_queryId );
1735         if ( attr == NULL ) return 0;
1736
1737         count = attr->a_numvals;
1738         assert( count > 0 );
1739         qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1740         qi->next = op->o_callback->sc_private;
1741         op->o_callback->sc_private = qi;
1742         ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1743         qi->del = ( count == 1 );
1744
1745         return 0;
1746 }
1747
1748 static int
1749 remove_query_data(
1750         Operation       *op,
1751         SlapReply       *rs,
1752         struct berval   *query_uuid )
1753 {
1754         struct query_info       *qi, *qnext;
1755         char                    filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
1756         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
1757         Filter                  filter = {LDAP_FILTER_EQUALITY};
1758         SlapReply               sreply = {REP_RESULT};
1759         slap_callback cb = { NULL, remove_func, NULL, NULL };
1760         int deleted = 0;
1761
1762         sreply.sr_entry = NULL;
1763         sreply.sr_nentries = 0;
1764         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1765                 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1766         filter.f_ava = &ava;
1767         filter.f_av_desc = ad_queryId;
1768         filter.f_av_value = *query_uuid;
1769
1770         op->o_tag = LDAP_REQ_SEARCH;
1771         op->o_protocol = LDAP_VERSION3;
1772         op->o_callback = &cb;
1773         op->o_time = slap_get_time();
1774         op->o_do_not_cache = 1;
1775
1776         op->o_req_dn = op->o_bd->be_suffix[0];
1777         op->o_req_ndn = op->o_bd->be_nsuffix[0];
1778         op->ors_scope = LDAP_SCOPE_SUBTREE;
1779         op->ors_deref = LDAP_DEREF_NEVER;
1780         op->ors_slimit = SLAP_NO_LIMIT;
1781         op->ors_tlimit = SLAP_NO_LIMIT;
1782         op->ors_limit = NULL;
1783         op->ors_filter = &filter;
1784         op->ors_filterstr.bv_val = filter_str;
1785         op->ors_filterstr.bv_len = strlen(filter_str);
1786         op->ors_attrs = NULL;
1787         op->ors_attrsonly = 0;
1788
1789         op->o_bd->be_search( op, &sreply );
1790
1791         for ( qi=cb.sc_private; qi; qi=qnext ) {
1792                 qnext = qi->next;
1793
1794                 op->o_req_dn = qi->xdn;
1795                 op->o_req_ndn = qi->xdn;
1796
1797                 if ( qi->del ) {
1798                         Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1799                                 query_uuid->bv_val, 0, 0 );
1800
1801                         op->o_tag = LDAP_REQ_DELETE;
1802
1803                         if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1804                                 deleted++;
1805                         }
1806
1807                 } else {
1808                         Modifications mod;
1809                         struct berval vals[2];
1810
1811                         vals[0] = *query_uuid;
1812                         vals[1].bv_val = NULL;
1813                         vals[1].bv_len = 0;
1814                         mod.sml_op = LDAP_MOD_DELETE;
1815                         mod.sml_flags = 0;
1816                         mod.sml_desc = ad_queryId;
1817                         mod.sml_type = ad_queryId->ad_cname;
1818                         mod.sml_values = vals;
1819                         mod.sml_nvalues = NULL;
1820                         mod.sml_numvals = 1;
1821                         mod.sml_next = NULL;
1822                         Debug( pcache_debug,
1823                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1824                                 query_uuid->bv_val, 0, 0 );
1825
1826                         op->orm_modlist = &mod;
1827
1828                         op->o_bd->be_modify( op, &sreply );
1829                 }
1830                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1831                 op->o_tmpfree( qi, op->o_tmpmemctx );
1832         }
1833         return deleted;
1834 }
1835
1836 static int
1837 get_attr_set(
1838         AttributeName* attrs,
1839         query_manager* qm,
1840         int num
1841 );
1842
1843 static int
1844 filter2template(
1845         Operation               *op,
1846         Filter                  *f,
1847         struct                  berval *fstr )
1848 {
1849         AttributeDescription *ad;
1850         int len, ret;
1851
1852         switch ( f->f_choice ) {
1853         case LDAP_FILTER_EQUALITY:
1854                 ad = f->f_av_desc;
1855                 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1856                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1857                 assert( ret == len );
1858                 fstr->bv_len += len;
1859                 break;
1860
1861         case LDAP_FILTER_GE:
1862                 ad = f->f_av_desc;
1863                 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1864                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1865                 assert( ret == len );
1866                 fstr->bv_len += len;
1867                 break;
1868
1869         case LDAP_FILTER_LE:
1870                 ad = f->f_av_desc;
1871                 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1872                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1873                 assert( ret == len );
1874                 fstr->bv_len += len;
1875                 break;
1876
1877         case LDAP_FILTER_APPROX:
1878                 ad = f->f_av_desc;
1879                 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1880                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1881                 assert( ret == len );
1882                 fstr->bv_len += len;
1883                 break;
1884
1885         case LDAP_FILTER_SUBSTRINGS:
1886                 ad = f->f_sub_desc;
1887                 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1888                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1889                 assert( ret == len );
1890                 fstr->bv_len += len;
1891                 break;
1892
1893         case LDAP_FILTER_PRESENT:
1894                 ad = f->f_desc;
1895                 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1896                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1897                 assert( ret == len );
1898                 fstr->bv_len += len;
1899                 break;
1900
1901         case LDAP_FILTER_AND:
1902         case LDAP_FILTER_OR:
1903         case LDAP_FILTER_NOT: {
1904                 int rc = 0;
1905                 fstr->bv_val[fstr->bv_len++] = '(';
1906                 switch ( f->f_choice ) {
1907                 case LDAP_FILTER_AND:
1908                         fstr->bv_val[fstr->bv_len] = '&';
1909                         break;
1910                 case LDAP_FILTER_OR:
1911                         fstr->bv_val[fstr->bv_len] = '|';
1912                         break;
1913                 case LDAP_FILTER_NOT:
1914                         fstr->bv_val[fstr->bv_len] = '!';
1915                         break;
1916                 }
1917                 fstr->bv_len++;
1918
1919                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1920                         rc = filter2template( op, f, fstr );
1921                         if ( rc ) break;
1922                 }
1923                 fstr->bv_val[fstr->bv_len++] = ')';
1924                 fstr->bv_val[fstr->bv_len] = '\0';
1925
1926                 return rc;
1927                 }
1928
1929         default:
1930                 /* a filter should at least have room for "()",
1931                  * an "=" and for a 1-char attr */
1932                 strcpy( fstr->bv_val, "(?=)" );
1933                 fstr->bv_len += STRLENOF("(?=)");
1934                 return -1;
1935         }
1936
1937         return 0;
1938 }
1939
1940 #define BI_HASHED       0x01
1941 #define BI_DIDCB        0x02
1942 #define BI_LOOKUP       0x04
1943
1944 struct search_info;
1945
1946 typedef struct bindinfo {
1947         cache_manager *bi_cm;
1948         CachedQuery *bi_cq;
1949         QueryTemplate *bi_templ;
1950         struct search_info *bi_si;
1951         int bi_flags;
1952         slap_callback bi_cb;
1953 } bindinfo;
1954
1955 struct search_info {
1956         slap_overinst *on;
1957         Query query;
1958         QueryTemplate *qtemp;
1959         AttributeName*  save_attrs;     /* original attributes, saved for response */
1960         int swap_saved_attrs;
1961         int max;
1962         int over;
1963         int count;
1964         int slimit;
1965         int slimit_exceeded;
1966         pc_caching_reason_t caching_reason;
1967         Entry *head, *tail;
1968         bindinfo *pbi;
1969 };
1970
1971 static void
1972 remove_query_and_data(
1973         Operation       *op,
1974         SlapReply       *rs,
1975         cache_manager   *cm,
1976         struct berval   *uuid )
1977 {
1978         query_manager*          qm = cm->qm;
1979
1980         qm->crfunc( qm, uuid );
1981         if ( !BER_BVISNULL( uuid ) ) {
1982                 int     return_val;
1983
1984                 Debug( pcache_debug,
1985                         "Removing query UUID %s\n",
1986                         uuid->bv_val, 0, 0 );
1987                 return_val = remove_query_data( op, rs, uuid );
1988                 Debug( pcache_debug,
1989                         "QUERY REMOVED, SIZE=%d\n",
1990                         return_val, 0, 0);
1991                 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1992                 cm->cur_entries -= return_val;
1993                 cm->num_cached_queries--;
1994                 Debug( pcache_debug,
1995                         "STORED QUERIES = %lu\n",
1996                         cm->num_cached_queries, 0, 0 );
1997                 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1998                 Debug( pcache_debug,
1999                         "QUERY REMOVED, CACHE ="
2000                         "%d entries\n",
2001                         cm->cur_entries, 0, 0 );
2002         }
2003 }
2004
2005 /*
2006  * Callback used to fetch queryId values based on entryUUID;
2007  * used by pcache_remove_entries_from_cache()
2008  */
2009 static int
2010 fetch_queryId_cb( Operation *op, SlapReply *rs )
2011 {
2012         int             rc = 0;
2013
2014         /* only care about searchEntry responses */
2015         if ( rs->sr_type != REP_SEARCH ) {
2016                 return 0;
2017         }
2018
2019         /* allow only one response per entryUUID */
2020         if ( op->o_callback->sc_private != NULL ) {
2021                 rc = 1;
2022
2023         } else {
2024                 Attribute       *a;
2025
2026                 /* copy all queryId values into callback's private data */
2027                 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2028                 if ( a != NULL ) {
2029                         BerVarray       vals = NULL;
2030
2031                         ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
2032                         op->o_callback->sc_private = (void *)vals;
2033                 }
2034         }
2035
2036         /* clear entry if required */
2037         if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
2038                 entry_free( rs->sr_entry );
2039                 rs->sr_entry = NULL;
2040                 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
2041         }
2042
2043         return rc;
2044 }
2045
2046 /*
2047  * Call that allows to remove a set of entries from the cache,
2048  * by forcing the removal of all the related queries.
2049  */
2050 int
2051 pcache_remove_entries_from_cache(
2052         Operation       *op,
2053         cache_manager   *cm,
2054         BerVarray       entryUUIDs )
2055 {
2056         Connection      conn = { 0 };
2057         OperationBuffer opbuf;
2058         Operation       op2;
2059         slap_callback   sc = { 0 };
2060         SlapReply       rs = { REP_RESULT };
2061         Filter          f = { 0 };
2062         char            filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
2063         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2064         AttributeName   attrs[ 2 ] = {{{ 0 }}};
2065         int             s, rc;
2066
2067         if ( op == NULL ) {
2068                 void    *thrctx = ldap_pvt_thread_pool_context();
2069
2070                 connection_fake_init( &conn, &opbuf, thrctx );
2071                 op = &opbuf.ob_op;
2072
2073         } else {
2074                 op2 = *op;
2075                 op = &op2;
2076         }
2077
2078         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2079         op->ors_scope = LDAP_SCOPE_SUBTREE;
2080         op->ors_deref = LDAP_DEREF_NEVER;
2081         f.f_choice = LDAP_FILTER_EQUALITY;
2082         f.f_ava = &ava;
2083         ava.aa_desc = slap_schema.si_ad_entryUUID;
2084         op->ors_filter = &f;
2085         op->ors_slimit = 1;
2086         op->ors_tlimit = SLAP_NO_LIMIT;
2087         op->ors_limit = NULL;
2088         attrs[ 0 ].an_desc = ad_queryId;
2089         attrs[ 0 ].an_name = ad_queryId->ad_cname;
2090         op->ors_attrs = attrs;
2091         op->ors_attrsonly = 0;
2092
2093         op->o_req_dn = cm->db.be_suffix[ 0 ];
2094         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2095
2096         op->o_tag = LDAP_REQ_SEARCH;
2097         op->o_protocol = LDAP_VERSION3;
2098         op->o_managedsait = SLAP_CONTROL_CRITICAL;
2099         op->o_bd = &cm->db;
2100         op->o_dn = op->o_bd->be_rootdn;
2101         op->o_ndn = op->o_bd->be_rootndn;
2102         sc.sc_response = fetch_queryId_cb;
2103         op->o_callback = &sc;
2104
2105         for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
2106                 BerVarray       vals = NULL;
2107
2108                 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
2109                         "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
2110                 op->ors_filterstr.bv_val = filtbuf;
2111                 ava.aa_value = entryUUIDs[ s ];
2112
2113                 rc = op->o_bd->be_search( op, &rs );
2114                 if ( rc != LDAP_SUCCESS ) {
2115                         continue;
2116                 }
2117
2118                 vals = (BerVarray)op->o_callback->sc_private;
2119                 if ( vals != NULL ) {
2120                         int             i;
2121
2122                         for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2123                                 struct berval   val = vals[ i ];
2124
2125                                 remove_query_and_data( op, &rs, cm, &val );
2126
2127                                 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2128                                         ch_free( val.bv_val );
2129                                 }
2130                         }
2131
2132                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
2133                         op->o_callback->sc_private = NULL;
2134                 }
2135         }
2136
2137         return 0;
2138 }
2139
2140 /*
2141  * Call that allows to remove a query from the cache.
2142  */
2143 int
2144 pcache_remove_query_from_cache(
2145         Operation       *op,
2146         cache_manager   *cm,
2147         struct berval   *queryid )
2148 {
2149         Operation       op2 = *op;
2150         SlapReply       rs2 = { 0 };
2151
2152         op2.o_bd = &cm->db;
2153
2154         /* remove the selected query */
2155         remove_query_and_data( &op2, &rs2, cm, queryid );
2156
2157         return LDAP_SUCCESS;
2158 }
2159
2160 /*
2161  * Call that allows to remove a set of queries related to an entry 
2162  * from the cache; if queryid is not null, the entry must belong to
2163  * the query indicated by queryid.
2164  */
2165 int
2166 pcache_remove_entry_queries_from_cache(
2167         Operation       *op,
2168         cache_manager   *cm,
2169         struct berval   *ndn,
2170         struct berval   *queryid )
2171 {
2172         Connection              conn = { 0 };
2173         OperationBuffer         opbuf;
2174         Operation               op2;
2175         slap_callback           sc = { 0 };
2176         SlapReply               rs = { REP_RESULT };
2177         Filter                  f = { 0 };
2178         char                    filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
2179         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
2180         AttributeName           attrs[ 2 ] = {{{ 0 }}};
2181         int                     rc;
2182
2183         BerVarray               vals = NULL;
2184
2185         if ( op == NULL ) {
2186                 void    *thrctx = ldap_pvt_thread_pool_context();
2187
2188                 connection_fake_init( &conn, &opbuf, thrctx );
2189                 op = &opbuf.ob_op;
2190
2191         } else {
2192                 op2 = *op;
2193                 op = &op2;
2194         }
2195
2196         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2197         op->ors_scope = LDAP_SCOPE_BASE;
2198         op->ors_deref = LDAP_DEREF_NEVER;
2199         if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
2200                 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
2201                 f.f_choice = LDAP_FILTER_PRESENT;
2202                 f.f_desc = slap_schema.si_ad_objectClass;
2203
2204         } else {
2205                 op->ors_filterstr.bv_len = snprintf( filter_str,
2206                         sizeof( filter_str ), "(%s=%s)",
2207                         ad_queryId->ad_cname.bv_val, queryid->bv_val );
2208                 f.f_choice = LDAP_FILTER_EQUALITY;
2209                 f.f_ava = &ava;
2210                 f.f_av_desc = ad_queryId;
2211                 f.f_av_value = *queryid;
2212         }
2213         op->ors_filter = &f;
2214         op->ors_slimit = 1;
2215         op->ors_tlimit = SLAP_NO_LIMIT;
2216         op->ors_limit = NULL;
2217         attrs[ 0 ].an_desc = ad_queryId;
2218         attrs[ 0 ].an_name = ad_queryId->ad_cname;
2219         op->ors_attrs = attrs;
2220         op->ors_attrsonly = 0;
2221
2222         op->o_req_dn = *ndn;
2223         op->o_req_ndn = *ndn;
2224
2225         op->o_tag = LDAP_REQ_SEARCH;
2226         op->o_protocol = LDAP_VERSION3;
2227         op->o_managedsait = SLAP_CONTROL_CRITICAL;
2228         op->o_bd = &cm->db;
2229         op->o_dn = op->o_bd->be_rootdn;
2230         op->o_ndn = op->o_bd->be_rootndn;
2231         sc.sc_response = fetch_queryId_cb;
2232         op->o_callback = &sc;
2233
2234         rc = op->o_bd->be_search( op, &rs );
2235         if ( rc != LDAP_SUCCESS ) {
2236                 return rc;
2237         }
2238
2239         vals = (BerVarray)op->o_callback->sc_private;
2240         if ( vals != NULL ) {
2241                 int             i;
2242
2243                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2244                         struct berval   val = vals[ i ];
2245
2246                         remove_query_and_data( op, &rs, cm, &val );
2247
2248                         if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2249                                 ch_free( val.bv_val );
2250                         }
2251                 }
2252
2253                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2254         }
2255
2256         return LDAP_SUCCESS;
2257 }
2258
2259 static int
2260 cache_entries(
2261         Operation       *op,
2262         SlapReply       *rs,
2263         struct berval *query_uuid )
2264 {
2265         struct search_info *si = op->o_callback->sc_private;
2266         slap_overinst *on = si->on;
2267         cache_manager *cm = on->on_bi.bi_private;
2268         int             return_val = 0;
2269         Entry           *e;
2270         struct berval   crp_uuid;
2271         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2272         Operation       *op_tmp;
2273         Connection      conn = {0};
2274         OperationBuffer opbuf;
2275         void            *thrctx = ldap_pvt_thread_pool_context();
2276
2277         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2278         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2279
2280         connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2281         op_tmp = &opbuf.ob_op;
2282         op_tmp->o_bd = &cm->db;
2283         op_tmp->o_dn = cm->db.be_rootdn;
2284         op_tmp->o_ndn = cm->db.be_rootndn;
2285
2286         Debug( pcache_debug, "UUID for query being added = %s\n",
2287                         uuidbuf, 0, 0 );
2288
2289         for ( e=si->head; e; e=si->head ) {
2290                 si->head = e->e_private;
2291                 e->e_private = NULL;
2292                 while ( cm->cur_entries > (cm->max_entries) ) {
2293                         BER_BVZERO( &crp_uuid );
2294                         remove_query_and_data( op_tmp, rs, cm, &crp_uuid );
2295                 }
2296
2297                 return_val = merge_entry(op_tmp, e, 0, query_uuid);
2298                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2299                 cm->cur_entries += return_val;
2300                 Debug( pcache_debug,
2301                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2302                         cm->cur_entries, 0, 0 );
2303                 return_val = 0;
2304                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2305         }
2306
2307         return return_val;
2308 }
2309
2310 static int
2311 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2312         slap_callback   *cb = op->o_callback;
2313         struct search_info *si = cb->sc_private;
2314         slap_overinst *on = si->on;
2315         cache_manager *cm = on->on_bi.bi_private;
2316         query_manager*          qm = cm->qm;
2317
2318         if ( rs->sr_type == REP_SEARCH ) {
2319                 Entry *e;
2320
2321                 /* don't return more entries than requested by the client */
2322                 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2323                         si->slimit_exceeded = 1;
2324                 }
2325
2326                 /* If we haven't exceeded the limit for this query,
2327                  * build a chain of answers to store. If we hit the
2328                  * limit, empty the chain and ignore the rest.
2329                  */
2330                 if ( !si->over ) {
2331                         /* check if the entry contains undefined
2332                          * attributes/objectClasses (ITS#5680) */
2333                         if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2334                                 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2335                                         op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
2336                                 goto over;
2337                         }
2338
2339                         /* check for malformed entries: attrs with no values */
2340                         {
2341                                 Attribute *a = rs->sr_entry->e_attrs;
2342                                 for (; a; a=a->a_next) {
2343                                         if ( !a->a_numvals ) {
2344                                                 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2345                                                 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2346                                                 a->a_desc->ad_cname.bv_val );
2347                                                 goto over;
2348                                         }
2349                                 }
2350                         }
2351
2352                         if ( si->count < si->max ) {
2353                                 si->count++;
2354                                 e = entry_dup( rs->sr_entry );
2355                                 if ( !si->head ) si->head = e;
2356                                 if ( si->tail ) si->tail->e_private = e;
2357                                 si->tail = e;
2358
2359                         } else {
2360 over:;
2361                                 si->over = 1;
2362                                 si->count = 0;
2363                                 for (;si->head; si->head=e) {
2364                                         e = si->head->e_private;
2365                                         si->head->e_private = NULL;
2366                                         entry_free(si->head);
2367                                 }
2368                                 si->tail = NULL;
2369                         }
2370                 }
2371
2372         }
2373
2374         if ( rs->sr_type == REP_RESULT || 
2375                 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2376         {
2377                 if ( si->swap_saved_attrs ) {
2378                         rs->sr_attrs = si->save_attrs;
2379                         op->ors_attrs = si->save_attrs;
2380                 }
2381                 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) && 
2382                                 si->caching_reason == PC_IGNORE )
2383                 {
2384                         filter_free( si->query.filter );
2385                         if ( si->count ) {
2386                                 /* duplicate query, free it */
2387                                 Entry *e;
2388                                 for (;si->head; si->head=e) {
2389                                         e = si->head->e_private;
2390                                         si->head->e_private = NULL;
2391                                         entry_free(si->head);
2392                                 }
2393                         }
2394
2395                 } else if ( si->caching_reason != PC_IGNORE ) {
2396                         CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2397                                 si->qtemp, si->caching_reason, 1 );
2398
2399                         if ( qc != NULL ) {
2400                                 switch ( si->caching_reason ) {
2401                                 case PC_POSITIVE:
2402                                         cache_entries( op, rs, &qc->q_uuid );
2403                                         if ( si->pbi )
2404                                                 si->pbi->bi_cq = qc;
2405                                         break;
2406
2407                                 case PC_SIZELIMIT:
2408                                         qc->q_sizelimit = rs->sr_nentries;
2409                                         break;
2410
2411                                 case PC_NEGATIVE:
2412                                         break;
2413
2414                                 default:
2415                                         assert( 0 );
2416                                         break;
2417                                 }
2418                                 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2419                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2420                                 cm->num_cached_queries++;
2421                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2422                                                 cm->num_cached_queries, 0, 0 );
2423                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2424
2425                                 /* If the consistency checker suspended itself,
2426                                  * wake it back up
2427                                  */
2428                                 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2429                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2430                                         if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2431                                                 cm->cc_paused = 0;
2432                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2433                                         }
2434                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2435                                 }
2436
2437                         } else if ( si->count ) {
2438                                 /* duplicate query, free it */
2439                                 Entry *e;
2440                                 for (;si->head; si->head=e) {
2441                                         e = si->head->e_private;
2442                                         si->head->e_private = NULL;
2443                                         entry_free(si->head);
2444                                 }
2445                         }
2446
2447                 } else {
2448                         filter_free( si->query.filter );
2449                 }
2450
2451                 op->o_callback = op->o_callback->sc_next;
2452                 op->o_tmpfree( cb, op->o_tmpmemctx );
2453         }
2454
2455         return SLAP_CB_CONTINUE;
2456 }
2457
2458 static int
2459 pcache_response(
2460         Operation       *op,
2461         SlapReply       *rs )
2462 {
2463         struct search_info *si = op->o_callback->sc_private;
2464
2465         if ( si->swap_saved_attrs ) {
2466                 rs->sr_attrs = si->save_attrs;
2467                 op->ors_attrs = si->save_attrs;
2468         }
2469
2470         if ( rs->sr_type == REP_SEARCH ) {
2471                 /* don't return more entries than requested by the client */
2472                 if ( si->slimit_exceeded ) {
2473                         return 0;
2474                 }
2475
2476         } else if ( rs->sr_type == REP_RESULT ) {
2477
2478                 if ( si->count ) {
2479                         if ( rs->sr_err == LDAP_SUCCESS ) {
2480                                 si->caching_reason = PC_POSITIVE;
2481
2482                         } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2483                                 && si->qtemp->limitttl )
2484                         {
2485                                 Entry *e;
2486
2487                                 si->caching_reason = PC_SIZELIMIT;
2488                                 for (;si->head; si->head=e) {
2489                                         e = si->head->e_private;
2490                                         si->head->e_private = NULL;
2491                                         entry_free(si->head);
2492                                 }
2493                         }
2494
2495                 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2496                                 rs->sr_err == LDAP_SUCCESS )
2497                 {
2498                         si->caching_reason = PC_NEGATIVE;
2499                 }
2500
2501
2502                 if ( si->slimit_exceeded ) {
2503                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2504                 }
2505         }
2506
2507         return SLAP_CB_CONTINUE;
2508 }
2509
2510 /* NOTE: this is a quick workaround to let pcache minimally interact
2511  * with pagedResults.  A more articulated solutions would be to
2512  * perform the remote query without control and cache all results,
2513  * performing the pagedResults search only within the client
2514  * and the proxy.  This requires pcache to understand pagedResults. */
2515 static int
2516 pcache_chk_controls(
2517         Operation       *op,
2518         SlapReply       *rs )
2519 {
2520         const char      *non = "";
2521         const char      *stripped = "";
2522
2523         switch( op->o_pagedresults ) {
2524         case SLAP_CONTROL_NONCRITICAL:
2525                 non = "non-";
2526                 stripped = "; stripped";
2527                 /* fallthru */
2528
2529         case SLAP_CONTROL_CRITICAL:
2530                 Debug( pcache_debug, "%s: "
2531                         "%scritical pagedResults control "
2532                         "disabled with proxy cache%s.\n",
2533                         op->o_log_prefix, non, stripped );
2534                 
2535                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2536                 break;
2537
2538         default:
2539                 rs->sr_err = SLAP_CB_CONTINUE;
2540                 break;
2541         }
2542
2543         return rs->sr_err;
2544 }
2545
2546 static int
2547 pc_setpw( Operation *op, struct berval *pwd, cache_manager *cm )
2548 {
2549         struct berval vals[2];
2550
2551         {
2552                 const char *text = NULL;
2553                 BER_BVZERO( &vals[0] );
2554                 slap_passwd_hash( pwd, &vals[0], &text );
2555                 if ( BER_BVISEMPTY( &vals[0] )) {
2556                         Debug( pcache_debug, "pc_setpw: hash failed %s\n",
2557                                 text, 0, 0 );
2558                         return LDAP_OTHER;
2559                 }
2560         }
2561
2562         BER_BVZERO( &vals[1] );
2563
2564         {
2565                 Modifications mod;
2566                 SlapReply sr = { REP_RESULT };
2567                 slap_callback cb = { 0, slap_null_cb, 0, 0 };
2568                 int rc;
2569
2570                 mod.sml_op = LDAP_MOD_REPLACE;
2571                 mod.sml_flags = 0;
2572                 mod.sml_desc = slap_schema.si_ad_userPassword;
2573                 mod.sml_type = mod.sml_desc->ad_cname;
2574                 mod.sml_values = vals;
2575                 mod.sml_nvalues = NULL;
2576                 mod.sml_numvals = 1;
2577                 mod.sml_next = NULL;
2578
2579                 op->o_tag = LDAP_REQ_MODIFY;
2580                 op->orm_modlist = &mod;
2581                 op->o_bd = &cm->db;
2582                 op->o_dn = op->o_bd->be_rootdn;
2583                 op->o_ndn = op->o_bd->be_rootndn;
2584                 op->o_callback = &cb;
2585                 Debug( pcache_debug, "pc_setpw: CACHING BIND for %s\n",
2586                         op->o_req_dn.bv_val, 0, 0 );
2587                 rc = op->o_bd->be_modify( op, &sr );
2588                 ch_free( vals[0].bv_val );
2589                 return rc;
2590         }
2591 }
2592
2593 typedef struct bindcacheinfo {
2594         slap_overinst *on;
2595         CachedQuery *qc;
2596 } bindcacheinfo;
2597
2598 static int
2599 pc_bind_save( Operation *op, SlapReply *rs )
2600 {
2601         if ( rs->sr_err == LDAP_SUCCESS ) {
2602                 bindcacheinfo *bci = op->o_callback->sc_private;
2603                 slap_overinst *on = bci->on;
2604                 cache_manager *cm = on->on_bi.bi_private;
2605
2606                 Operation op2 = *op;
2607                 if ( pc_setpw( &op2, &op->orb_cred, cm ) == LDAP_SUCCESS )
2608                         bci->qc->bindref_time = op->o_time + bci->qc->qtemp->bindttr;
2609         }
2610         return SLAP_CB_CONTINUE;
2611 }
2612
2613 static Filter *
2614 pc_bind_attrs( Operation *op, Entry *e, QueryTemplate *temp,
2615         struct berval *fbv )
2616 {
2617         int i, len = 0;
2618         struct berval *vals, pres = BER_BVC("*");
2619         char *p1, *p2;
2620         Attribute *a;
2621
2622         vals = op->o_tmpalloc( temp->bindnattrs * sizeof( struct berval ),
2623                 op->o_tmpmemctx );
2624
2625         for ( i=0; i<temp->bindnattrs; i++ ) {
2626                 a = attr_find( e->e_attrs, temp->bindfattrs[i] );
2627                 if ( a && a->a_vals ) {
2628                         vals[i] = a->a_vals[0];
2629                         len += a->a_vals[0].bv_len;
2630                 } else {
2631                         vals[i] = pres;
2632                 }
2633         }
2634         fbv->bv_len = len + temp->bindftemp.bv_len;
2635         fbv->bv_val = op->o_tmpalloc( fbv->bv_len + 1, op->o_tmpmemctx );
2636
2637         p1 = temp->bindftemp.bv_val;
2638         p2 = fbv->bv_val;
2639         i = 0;
2640         while ( *p1 ) {
2641                 *p2++ = *p1;
2642                 if ( p1[0] == '=' && p1[1] == ')' ) {
2643                         AC_MEMCPY( p2, vals[i].bv_val, vals[i].bv_len );
2644                         p2 += vals[i].bv_len;
2645                         i++;
2646                 }
2647                 p1++;
2648         }
2649         *p2 = '\0';
2650         op->o_tmpfree( vals, op->o_tmpmemctx );
2651
2652         /* FIXME: are we sure str2filter_x can't fail?
2653          * caller needs to check */
2654         {
2655                 Filter *f = str2filter_x( op, fbv->bv_val );
2656                 assert( f != NULL );
2657                 return f;
2658         }
2659 }
2660
2661 /* Check if the requested entry is from the cache and has a valid
2662  * ttr and password hash
2663  */
2664 static int
2665 pc_bind_search( Operation *op, SlapReply *rs )
2666 {
2667         if ( rs->sr_type == REP_SEARCH ) {
2668                 bindinfo *pbi = op->o_callback->sc_private;
2669
2670                 /* We only care if this is an already cached result and we're
2671                  * below the refresh time, or we're offline.
2672                  */
2673                 if ( pbi->bi_cq ) {
2674                         if (( pbi->bi_cm->cc_paused & PCACHE_CC_OFFLINE ) ||
2675                                 op->o_time < pbi->bi_cq->bindref_time ) {
2676                                 Attribute *a;
2677
2678                                 /* See if a recognized password is hashed here */
2679                                 a = attr_find( rs->sr_entry->e_attrs,
2680                                         slap_schema.si_ad_userPassword );
2681                                 if ( a && a->a_vals[0].bv_val[0] == '{' &&
2682                                         lutil_passwd_scheme( a->a_vals[0].bv_val ))
2683                                         pbi->bi_flags |= BI_HASHED;
2684                         } else {
2685                                 Debug( pcache_debug, "pc_bind_search: cache is stale, "
2686                                         "reftime: %ld, current time: %ld\n",
2687                                         pbi->bi_cq->bindref_time, op->o_time, 0 );
2688                         }
2689                 } else if ( pbi->bi_si ) {
2690                         /* This search result is going into the cache */
2691                         struct berval fbv;
2692                         Filter *f;
2693
2694                         filter_free( pbi->bi_si->query.filter );
2695                         f = pc_bind_attrs( op, rs->sr_entry, pbi->bi_templ, &fbv );
2696                         op->o_tmpfree( fbv.bv_val, op->o_tmpmemctx );
2697                         pbi->bi_si->query.filter = filter_dup( f, NULL );
2698                         filter_free_x( op, f, 1 );
2699                 }
2700         }
2701         return 0;
2702 }
2703
2704 /* We always want pc_bind_search to run after the search handlers */
2705 static int
2706 pc_bind_resp( Operation *op, SlapReply *rs )
2707 {
2708         bindinfo *pbi = op->o_callback->sc_private;
2709         if ( !( pbi->bi_flags & BI_DIDCB )) {
2710                 slap_callback *sc = op->o_callback;
2711                 while ( sc && sc->sc_response != pcache_response )
2712                         sc = sc->sc_next;
2713                 if ( !sc )
2714                         sc = op->o_callback;
2715                 pbi->bi_cb.sc_next = sc->sc_next;
2716                 sc->sc_next = &pbi->bi_cb;
2717                 pbi->bi_flags |= BI_DIDCB;
2718         }
2719         return SLAP_CB_CONTINUE;
2720 }
2721
2722 #ifdef PCACHE_CONTROL_PRIVDB
2723 static int
2724 pcache_op_privdb(
2725         Operation               *op,
2726         SlapReply               *rs )
2727 {
2728         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
2729         cache_manager   *cm = on->on_bi.bi_private;
2730         slap_callback   *save_cb;
2731         slap_op_t       type;
2732
2733         /* skip if control is unset */
2734         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2735                 return SLAP_CB_CONTINUE;
2736         }
2737
2738         /* The cache DB isn't open yet */
2739         if ( cm->defer_db_open ) {
2740                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2741                         "pcachePrivDB: cacheDB not available" );
2742                 return rs->sr_err;
2743         }
2744
2745         /* FIXME: might be a little bit exaggerated... */
2746         if ( !be_isroot( op ) ) {
2747                 save_cb = op->o_callback;
2748                 op->o_callback = NULL;
2749                 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2750                         "pcachePrivDB: operation not allowed" );
2751                 op->o_callback = save_cb;
2752
2753                 return rs->sr_err;
2754         }
2755
2756         /* map tag to operation */
2757         type = slap_req2op( op->o_tag );
2758         if ( type != SLAP_OP_LAST ) {
2759                 BI_op_func      **func;
2760                 int             rc;
2761
2762                 /* execute, if possible */
2763                 func = &cm->db.be_bind;
2764                 if ( func[ type ] != NULL ) {
2765                         Operation       op2 = *op;
2766         
2767                         op2.o_bd = &cm->db;
2768
2769                         rc = func[ type ]( &op2, rs );
2770                         if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2771                                 op->o_conn->c_authz_cookie = cm->db.be_private;
2772                         }
2773
2774                         return rs->sr_err;
2775                 }
2776         }
2777
2778         /* otherwise fall back to error */
2779         save_cb = op->o_callback;
2780         op->o_callback = NULL;
2781         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2782                 "operation not supported with pcachePrivDB control" );
2783         op->o_callback = save_cb;
2784
2785         return rs->sr_err;
2786 }
2787 #endif /* PCACHE_CONTROL_PRIVDB */
2788
2789 static int
2790 pcache_op_bind(
2791         Operation               *op,
2792         SlapReply               *rs )
2793 {
2794         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
2795         cache_manager   *cm = on->on_bi.bi_private;
2796         QueryTemplate *temp;
2797         Entry *e;
2798         slap_callback   cb = { 0 }, *sc;
2799         bindinfo bi;
2800         bindcacheinfo *bci;
2801         Operation op2;
2802         int rc;
2803
2804 #ifdef PCACHE_CONTROL_PRIVDB
2805         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL )
2806                 return pcache_op_privdb( op, rs );
2807 #endif /* PCACHE_CONTROL_PRIVDB */
2808
2809         /* Skip if we're not configured for Binds, or cache DB isn't open yet */
2810         if ( !cm->cache_binds || cm->defer_db_open )
2811                 return SLAP_CB_CONTINUE;
2812
2813         /* First find a matching template with Bind info */
2814         for ( temp=cm->qm->templates; temp; temp=temp->qmnext ) {
2815                 if ( temp->bindttr && dnIsSuffix( &op->o_req_ndn, &temp->bindbase ))
2816                         break;
2817         }
2818         /* Didn't find a suitable template, just passthru */
2819         if ( !temp )
2820                 return SLAP_CB_CONTINUE;
2821
2822         /* See if the entry is already locally cached. If so, we can
2823          * populate the query filter to retrieve the cached query. We
2824          * need to check the bindrefresh time in the query.
2825          */
2826         op2 = *op;
2827         op2.o_dn = op->o_bd->be_rootdn;
2828         op2.o_ndn = op->o_bd->be_rootndn;
2829         bi.bi_flags = 0;
2830
2831         op2.o_bd = &cm->db;
2832         e = NULL;
2833         rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL, NULL, 0, &e );
2834         if ( rc == LDAP_SUCCESS && e ) {
2835                 bi.bi_flags |= BI_LOOKUP;
2836                 op2.ors_filter = pc_bind_attrs( op, e, temp, &op2.ors_filterstr );
2837                 be_entry_release_r( &op2, e );
2838         } else {
2839                 op2.ors_filter = temp->bindfilter;
2840                 op2.ors_filterstr = temp->bindfilterstr;
2841         }
2842
2843         op2.o_bd = op->o_bd;
2844         op2.o_tag = LDAP_REQ_SEARCH;
2845         op2.ors_scope = LDAP_SCOPE_BASE;
2846         op2.ors_deref = LDAP_DEREF_NEVER;
2847         op2.ors_slimit = 1;
2848         op2.ors_tlimit = SLAP_NO_LIMIT;
2849         op2.ors_limit = NULL;
2850         op2.ors_attrs = cm->qm->attr_sets[temp->attr_set_index].attrs;
2851         op2.ors_attrsonly = 0;
2852
2853         /* We want to invoke search at the same level of the stack
2854          * as we're already at...
2855          */
2856         bi.bi_cm = cm;
2857         bi.bi_templ = temp;
2858         bi.bi_cq = NULL;
2859         bi.bi_si = NULL;
2860
2861         bi.bi_cb.sc_response = pc_bind_search;
2862         bi.bi_cb.sc_cleanup = NULL;
2863         bi.bi_cb.sc_private = &bi;
2864         cb.sc_private = &bi;
2865         cb.sc_response = pc_bind_resp;
2866         op2.o_callback = &cb;
2867         overlay_op_walk( &op2, rs, op_search, on->on_info, on );
2868
2869         /* OK, just bind locally */
2870         if ( bi.bi_flags & BI_HASHED ) {
2871                 BackendDB *be = op->o_bd;
2872                 op->o_bd = &cm->db;
2873
2874                 Debug( pcache_debug, "pcache_op_bind: CACHED BIND for %s\n",
2875                         op->o_req_dn.bv_val, 0, 0 );
2876
2877                 if ( op->o_bd->be_bind( op, rs ) == LDAP_SUCCESS ) {
2878                         op->o_conn->c_authz_cookie = cm->db.be_private;
2879                 }
2880                 op->o_bd = be;
2881                 return rs->sr_err;
2882         }
2883
2884         /* We have a cached query to work with */
2885         if ( bi.bi_cq ) {
2886                 sc = op->o_tmpalloc( sizeof(slap_callback) + sizeof(bindcacheinfo),
2887                         op->o_tmpmemctx );
2888                 sc->sc_response = pc_bind_save;
2889                 sc->sc_cleanup = NULL;
2890                 sc->sc_private = sc+1;
2891                 bci = sc->sc_private;
2892                 sc->sc_next = op->o_callback;
2893                 op->o_callback = sc;
2894                 bci->on = on;
2895                 bci->qc = bi.bi_cq;
2896         }
2897         return SLAP_CB_CONTINUE;
2898 }
2899
2900 static int
2901 pcache_op_search(
2902         Operation       *op,
2903         SlapReply       *rs )
2904 {
2905         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2906         cache_manager *cm = on->on_bi.bi_private;
2907         query_manager*          qm = cm->qm;
2908
2909         int i = -1;
2910
2911         Query           query;
2912         QueryTemplate   *qtemp = NULL;
2913         bindinfo *pbi = NULL;
2914
2915         int             attr_set = -1;
2916         CachedQuery     *answerable = NULL;
2917         int             cacheable = 0;
2918
2919         struct berval   tempstr;
2920
2921 #ifdef PCACHE_CONTROL_PRIVDB
2922         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2923                 return pcache_op_privdb( op, rs );
2924         }
2925 #endif /* PCACHE_CONTROL_PRIVDB */
2926
2927         /* The cache DB isn't open yet */
2928         if ( cm->defer_db_open ) {
2929                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2930                         "pcachePrivDB: cacheDB not available" );
2931                 return rs->sr_err;
2932         }
2933
2934         /* pickup runtime ACL changes */
2935         cm->db.be_acl = op->o_bd->be_acl;
2936
2937         {
2938                 /* See if we're processing a Bind request */
2939                 slap_callback *cb = op->o_callback;
2940
2941                 for ( ; cb; cb=cb->sc_next ) {
2942                         if ( cb->sc_response == pc_bind_resp ) {
2943                                 pbi = cb->sc_private;
2944                                 break;
2945                         }
2946                 }
2947         }
2948
2949         /* FIXME: cannot cache/answer requests with pagedResults control */
2950
2951         query.filter = op->ors_filter;
2952
2953         if ( pbi ) {
2954                 query.base = pbi->bi_templ->bindbase;
2955                 query.scope = pbi->bi_templ->bindscope;
2956                 attr_set = pbi->bi_templ->attr_set_index;
2957                 cacheable = 1;
2958                 qtemp = pbi->bi_templ;
2959                 if ( pbi->bi_flags & BI_LOOKUP )
2960                         answerable = qm->qcfunc(op, qm, &query, qtemp);
2961
2962         } else {
2963                 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1,
2964                         op->o_tmpmemctx );
2965                 tempstr.bv_len = 0;
2966                 if ( filter2template( op, op->ors_filter, &tempstr ))
2967                 {
2968                         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2969                         return SLAP_CB_CONTINUE;
2970                 }
2971
2972                 Debug( pcache_debug, "query template of incoming query = %s\n",
2973                                                 tempstr.bv_val, 0, 0 );
2974
2975                 /* find attr set */
2976                 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2977
2978                 query.base = op->o_req_ndn;
2979                 query.scope = op->ors_scope;
2980
2981                 /* check for query containment */
2982                 if (attr_set > -1) {
2983                         QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2984                         for (; qt; qt = qt->qtnext ) {
2985                                 /* find if template i can potentially answer tempstr */
2986                                 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
2987                                         continue;
2988                                 cacheable = 1;
2989                                 qtemp = qt;
2990                                 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2991                                                 op->ors_filterstr.bv_val, 0, 0 );
2992                                 answerable = qm->qcfunc(op, qm, &query, qt);
2993
2994                                 /* if != NULL, rlocks qtemp->t_rwlock */
2995                                 if (answerable)
2996                                         break;
2997                         }
2998                 }
2999                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3000         }
3001
3002         if (answerable) {
3003                 BackendDB       *save_bd = op->o_bd;
3004
3005                 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
3006                 answerable->answerable_cnt++;
3007                 /* we only care about refcnts if we're refreshing */
3008                 if ( answerable->refresh_time )
3009                         answerable->refcnt++;
3010                 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
3011                         answerable->answerable_cnt, 0, 0 );
3012                 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
3013
3014                 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
3015                 if ( BER_BVISNULL( &answerable->q_uuid )) {
3016                         /* No entries cached, just an empty result set */
3017                         i = rs->sr_err = 0;
3018                         send_ldap_result( op, rs );
3019                 } else {
3020                         /* Let Bind know we used a cached query */
3021                         if ( pbi )
3022                                 pbi->bi_cq = answerable;
3023
3024                         op->o_bd = &cm->db;
3025                         if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
3026                                 slap_callback cb;
3027                                 /* The cached entry was already processed by any
3028                                  * other overlays, so don't let it get processed again.
3029                                  *
3030                                  * This loop removes over_back_response from the stack.
3031                                  */
3032                                 if ( overlay_callback_after_backover( op, &cb, 0) == 0 ) {
3033                                         slap_callback **scp;
3034                                         for ( scp = &op->o_callback; *scp != NULL;
3035                                                 scp = &(*scp)->sc_next ) {
3036                                                 if ( (*scp)->sc_next == &cb ) {
3037                                                         *scp = cb.sc_next;
3038                                                         break;
3039                                                 }
3040                                         }
3041                                 }
3042                         }
3043                         i = cm->db.bd_info->bi_op_search( op, rs );
3044                 }
3045                 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
3046                 /* locked by qtemp->qcfunc (query_containment) */
3047                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
3048                 op->o_bd = save_bd;
3049                 return i;
3050         }
3051
3052         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
3053
3054         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3055         if (cm->num_cached_queries >= cm->max_queries) {
3056                 cacheable = 0;
3057         }
3058         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3059
3060         if (op->ors_attrsonly)
3061                 cacheable = 0;
3062
3063         if (cacheable) {
3064                 slap_callback           *cb;
3065                 struct search_info      *si;
3066
3067                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
3068                 query.filter = filter_dup(op->ors_filter, NULL);
3069
3070                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
3071                 cb->sc_response = pcache_response;
3072                 cb->sc_cleanup = pcache_op_cleanup;
3073                 cb->sc_private = (cb+1);
3074                 si = cb->sc_private;
3075                 si->on = on;
3076                 si->query = query;
3077                 si->qtemp = qtemp;
3078                 si->max = cm->num_entries_limit ;
3079                 si->over = 0;
3080                 si->count = 0;
3081                 si->slimit = 0;
3082                 si->slimit_exceeded = 0;
3083                 si->caching_reason = PC_IGNORE;
3084                 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
3085                         si->slimit = op->ors_slimit;
3086                         op->ors_slimit = cm->num_entries_limit;
3087                 }
3088                 si->head = NULL;
3089                 si->tail = NULL;
3090                 si->swap_saved_attrs = 1;
3091                 si->save_attrs = op->ors_attrs;
3092                 si->pbi = pbi;
3093                 if ( pbi )
3094                         pbi->bi_si = si;
3095
3096                 op->ors_attrs = qtemp->t_attrs.attrs;
3097
3098                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3099                         cb->sc_next = op->o_callback;
3100                         op->o_callback = cb;
3101
3102                 } else {
3103                         slap_callback           **pcb;
3104
3105                         /* need to move the callback at the end, in case other
3106                          * overlays are present, so that the final entry is
3107                          * actually cached */
3108                         cb->sc_next = NULL;
3109                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
3110                         *pcb = cb;
3111                 }
3112
3113         } else {
3114                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
3115                                         0, 0, 0);
3116         }
3117
3118         return SLAP_CB_CONTINUE;
3119 }
3120
3121 static int
3122 get_attr_set(
3123         AttributeName* attrs,
3124         query_manager* qm,
3125         int num )
3126 {
3127         int i = 0;
3128         int count = 0;
3129
3130         if ( attrs ) {
3131                 for ( ; attrs[i].an_name.bv_val; i++ ) {
3132                         /* only count valid attribute names
3133                          * (searches ignore others, this overlay does the same) */
3134                         if ( attrs[i].an_desc ) {
3135                                 count++;
3136                         }
3137                 }
3138         }
3139
3140         /* recognize default or explicit single "*" */
3141         if ( ! attrs ||
3142                 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_all_user_attrs ) ) )
3143         {
3144                 count = 1;
3145                 attrs = slap_anlist_all_user_attributes;
3146
3147         /* recognize implicit (no valid attributes) or explicit single "1.1" */
3148         } else if ( count == 0 ||
3149                 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) )
3150         {
3151                 count = 0;
3152                 attrs = NULL;
3153         }
3154
3155         for ( i = 0; i < num; i++ ) {
3156                 AttributeName *a2;
3157                 int found = 1;
3158
3159                 if ( count > qm->attr_sets[i].count ) {
3160                         continue;
3161                 }
3162
3163                 if ( !count ) {
3164                         if ( !qm->attr_sets[i].count ) {
3165                                 break;
3166                         }
3167                         continue;
3168                 }
3169
3170                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
3171                         if ( !a2->an_desc && !bvmatch( &a2->an_name, slap_bv_all_user_attrs ) ) continue;
3172
3173                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
3174                                 found = 0;
3175                                 break;
3176                         }
3177                 }
3178
3179                 if ( found ) {
3180                         break;
3181                 }
3182         }
3183
3184         if ( i == num ) {
3185                 i = -1;
3186         }
3187
3188         return i;
3189 }
3190
3191 /* Refresh a cached query:
3192  * 1: Replay the query on the remote DB and merge each entry into
3193  * the local DB. Remember the DNs of each remote entry.
3194  * 2: Search the local DB for all entries matching this queryID.
3195  * Delete any entry whose DN is not in the list from (1).
3196  */
3197 typedef struct dnlist {
3198         struct dnlist *next;
3199         struct berval dn;
3200         char delete;
3201 } dnlist;
3202
3203 typedef struct refresh_info {
3204         dnlist *ri_dns;
3205         dnlist *ri_tail;
3206         dnlist *ri_dels;
3207         BackendDB *ri_be;
3208         CachedQuery *ri_q;
3209 } refresh_info;
3210
3211 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
3212 {
3213         dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
3214                         op->o_tmpmemctx );
3215         dn->dn.bv_len = bvdn->bv_len;
3216         dn->dn.bv_val = (char *)(dn+1);
3217         AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
3218         dn->dn.bv_val[dn->dn.bv_len] = '\0';
3219         return dn;
3220 }
3221
3222 static int
3223 refresh_merge( Operation *op, SlapReply *rs )
3224 {
3225         if ( rs->sr_type == REP_SEARCH ) {
3226                 refresh_info *ri = op->o_callback->sc_private;
3227                 Entry *e;
3228                 dnlist *dnl;
3229                 slap_callback *ocb;
3230                 int rc;
3231
3232                 ocb = op->o_callback;
3233                 /* Find local entry, merge */
3234                 op->o_bd = ri->ri_be;
3235                 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
3236                 if ( rc != LDAP_SUCCESS || e == NULL ) {
3237                         /* No local entry, just add it. FIXME: we are not checking
3238                          * the cache entry limit here
3239                          */
3240                          merge_entry( op, rs->sr_entry, 1, &ri->ri_q->q_uuid );
3241                 } else {
3242                         /* Entry exists, update it */
3243                         Entry ne;
3244                         Attribute *a, **b;
3245                         Modifications *modlist, *mods = NULL;
3246                         const char*     text = NULL;
3247                         char                    textbuf[SLAP_TEXT_BUFLEN];
3248                         size_t                  textlen = sizeof(textbuf);
3249                         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
3250
3251                         ne = *e;
3252                         b = &ne.e_attrs;
3253                         /* Get a copy of only the attrs we requested */
3254                         for ( a=e->e_attrs; a; a=a->a_next ) {
3255                                 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
3256                                         *b = attr_alloc( a->a_desc );
3257                                         *(*b) = *a;
3258                                         /* The actual values still belong to e */
3259                                         (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
3260                                                 SLAP_ATTR_DONT_FREE_DATA;
3261                                         b = &((*b)->a_next);
3262                                 }
3263                         }
3264                         *b = NULL;
3265                         slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
3266                         syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
3267                                 &mods, &modlist, 0 );
3268                         be_entry_release_r( op, e );
3269                         attrs_free( ne.e_attrs );
3270                         slap_mods_free( modlist, 1 );
3271                         /* mods is NULL if there are no changes */
3272                         if ( mods ) {
3273                                 struct berval dn = op->o_req_dn;
3274                                 struct berval ndn = op->o_req_ndn;
3275                                 op->o_tag = LDAP_REQ_MODIFY;
3276                                 op->orm_modlist = mods;
3277                                 op->o_req_dn = rs->sr_entry->e_name;
3278                                 op->o_req_ndn = rs->sr_entry->e_nname;
3279                                 op->o_callback = &cb;
3280                                 op->o_bd->be_modify( op, rs );
3281                                 slap_mods_free( mods, 1 );
3282                                 op->o_req_dn = dn;
3283                                 op->o_req_ndn = ndn;
3284                         }
3285                 }
3286
3287                 /* Add DN to list */
3288                 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3289                 dnl->next = NULL;
3290                 if ( ri->ri_tail ) {
3291                         ri->ri_tail->next = dnl;
3292                 } else {
3293                         ri->ri_dns = dnl;
3294                 }
3295                 ri->ri_tail = dnl;
3296                 op->o_callback = ocb;
3297         }
3298         return 0;
3299 }
3300
3301 static int
3302 refresh_purge( Operation *op, SlapReply *rs )
3303 {
3304         if ( rs->sr_type == REP_SEARCH ) {
3305                 refresh_info *ri = op->o_callback->sc_private;
3306                 dnlist **dn;
3307                 int del = 1;
3308
3309                 /* Did the entry exist on the remote? */
3310                 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
3311                         if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
3312                                 dnlist *dnext = (*dn)->next;
3313                                 op->o_tmpfree( *dn, op->o_tmpmemctx );
3314                                 *dn = dnext;
3315                                 del = 0;
3316                                 break;
3317                         }
3318                 }
3319                 /* No, so put it on the list to delete */
3320                 if ( del ) {
3321                         Attribute *a;
3322                         dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3323                         dnl->next = ri->ri_dels;
3324                         ri->ri_dels = dnl;
3325                         a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
3326                         /* If ours is the only queryId, delete entry */
3327                         dnl->delete = ( a->a_numvals == 1 );
3328                 }
3329         }
3330         return 0;
3331 }
3332
3333 static int
3334 refresh_query( Operation *op, SlapReply *rs, CachedQuery *query,
3335         slap_overinst *on )
3336 {
3337         slap_callback cb = { 0 };
3338         refresh_info ri = { 0 };
3339         char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
3340         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
3341         Filter filter = {LDAP_FILTER_EQUALITY};
3342         AttributeName attrs[ 2 ] = {{{ 0 }}};
3343         dnlist *dn;
3344         int rc;
3345
3346         ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
3347         query->refcnt = 0;
3348         ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
3349
3350         cb.sc_response = refresh_merge;
3351         cb.sc_private = &ri;
3352
3353         /* cache DB */
3354         ri.ri_be = op->o_bd;
3355         ri.ri_q = query;
3356
3357         op->o_tag = LDAP_REQ_SEARCH;
3358         op->o_protocol = LDAP_VERSION3;
3359         op->o_callback = &cb;
3360         op->o_do_not_cache = 1;
3361
3362         op->o_req_dn = query->qbase->base;
3363         op->o_req_ndn = query->qbase->base;
3364         op->ors_scope = query->scope;
3365         op->ors_slimit = SLAP_NO_LIMIT;
3366         op->ors_tlimit = SLAP_NO_LIMIT;
3367         op->ors_limit = NULL;
3368         op->ors_filter = query->filter;
3369         filter2bv_x( op, query->filter, &op->ors_filterstr );
3370         op->ors_attrs = query->qtemp->t_attrs.attrs;
3371         op->ors_attrsonly = 0;
3372
3373         op->o_bd = on->on_info->oi_origdb;
3374         rc = op->o_bd->be_search( op, rs );
3375         if ( rc ) {
3376                 op->o_bd = ri.ri_be;
3377                 goto leave;
3378         }
3379
3380         /* Get the DNs of all entries matching this query */
3381         cb.sc_response = refresh_purge;
3382
3383         op->o_bd = ri.ri_be;
3384         op->o_req_dn = op->o_bd->be_suffix[0];
3385         op->o_req_ndn = op->o_bd->be_nsuffix[0];
3386         op->ors_scope = LDAP_SCOPE_SUBTREE;
3387         op->ors_deref = LDAP_DEREF_NEVER;
3388         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
3389                 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
3390         filter.f_ava = &ava;
3391         filter.f_av_desc = ad_queryId;
3392         filter.f_av_value = query->q_uuid;
3393         attrs[ 0 ].an_desc = ad_queryId;
3394         attrs[ 0 ].an_name = ad_queryId->ad_cname;
3395         op->ors_attrs = attrs;
3396         op->ors_attrsonly = 0;
3397         rs->sr_entry = NULL;
3398         rs->sr_nentries = 0;
3399         rc = op->o_bd->be_search( op, rs );
3400         if ( rc ) goto leave;
3401
3402         while (( dn = ri.ri_dels )) {
3403                 op->o_req_dn = dn->dn;
3404                 op->o_req_ndn = dn->dn;
3405                 if ( dn->delete ) {
3406                         op->o_tag = LDAP_REQ_DELETE;
3407                         op->o_bd->be_delete( op, rs );
3408                 } else {
3409                         Modifications mod;
3410                         struct berval vals[2];
3411
3412                         vals[0] = query->q_uuid;
3413                         BER_BVZERO( &vals[1] );
3414                         mod.sml_op = LDAP_MOD_DELETE;
3415                         mod.sml_flags = 0;
3416                         mod.sml_desc = ad_queryId;
3417                         mod.sml_type = ad_queryId->ad_cname;
3418                         mod.sml_values = vals;
3419                         mod.sml_nvalues = NULL;
3420                         mod.sml_numvals = 1;
3421                         mod.sml_next = NULL;
3422
3423                         op->o_tag = LDAP_REQ_MODIFY;
3424                         op->orm_modlist = &mod;
3425                         op->o_bd->be_modify( op, rs );
3426                 }
3427                 ri.ri_dels = dn->next;
3428                 op->o_tmpfree( dn, op->o_tmpmemctx );
3429         }
3430
3431 leave:
3432         /* reset our local heap, we're done with it */
3433         slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
3434         return rc;
3435 }
3436
3437 static void*
3438 consistency_check(
3439         void *ctx,
3440         void *arg )
3441 {
3442         struct re_s *rtask = arg;
3443         slap_overinst *on = rtask->arg;
3444         cache_manager *cm = on->on_bi.bi_private;
3445         query_manager *qm = cm->qm;
3446         Connection conn = {0};
3447         OperationBuffer opbuf;
3448         Operation *op;
3449
3450         SlapReply rs = {REP_RESULT};
3451         CachedQuery *query, *qprev;
3452         int return_val, pause = PCACHE_CC_PAUSED;
3453         QueryTemplate *templ;
3454
3455         /* Don't expire anything when we're offline */
3456         if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
3457                 pause = PCACHE_CC_OFFLINE;
3458                 goto leave;
3459         }
3460
3461         connection_fake_init( &conn, &opbuf, ctx );
3462         op = &opbuf.ob_op;
3463
3464         op->o_bd = &cm->db;
3465         op->o_dn = cm->db.be_rootdn;
3466         op->o_ndn = cm->db.be_rootndn;
3467
3468         cm->cc_arg = arg;
3469
3470         for (templ = qm->templates; templ; templ=templ->qmnext) {
3471                 time_t ttl;
3472                 if ( !templ->query_last ) continue;
3473                 pause = 0;
3474                 op->o_time = slap_get_time();
3475                 if ( !templ->ttr ) {
3476                         ttl = templ->ttl;
3477                         if ( templ->negttl && templ->negttl < ttl )
3478                                 ttl = templ->negttl;
3479                         if ( templ->limitttl && templ->limitttl < ttl )
3480                                 ttl = templ->limitttl;
3481                         /* The oldest timestamp that needs expiration checking */
3482                         ttl += op->o_time;
3483                 }
3484
3485                 for ( query=templ->query_last; query; query=qprev ) {
3486                         qprev = query->prev;
3487                         if ( query->refresh_time && query->refresh_time < op->o_time ) {
3488                                 /* A refresh will extend the expiry if the query has been
3489                                  * referenced, but not if it's unreferenced. If the
3490                                  * expiration has been hit, then skip the refresh since
3491                                  * we're just going to discard the result anyway.
3492                                  */
3493                                 if ( query->refcnt )
3494                                         query->expiry_time = op->o_time + templ->ttl;
3495                                 if ( query->expiry_time > op->o_time ) {
3496                                         refresh_query( op, &rs, query, on );
3497                                         continue;
3498                                 }
3499                         }
3500
3501                         if (query->expiry_time < op->o_time) {
3502                                 int rem = 0;
3503                                 Debug( pcache_debug, "Lock CR index = %p\n",
3504                                                 (void *) templ, 0, 0 );
3505                                 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
3506                                 if ( query == templ->query_last ) {
3507                                         rem = 1;
3508                                         remove_from_template(query, templ);
3509                                         Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
3510                                                         (void *) templ, templ->no_of_queries, 0 );
3511                                         Debug( pcache_debug, "Unlock CR index = %p\n",
3512                                                         (void *) templ, 0, 0 );
3513                                 }
3514                                 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3515                                 if ( !rem ) {
3516                                         continue;
3517                                 }
3518                                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
3519                                 remove_query(qm, query);
3520                                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
3521                                 if ( BER_BVISNULL( &query->q_uuid ))
3522                                         return_val = 0;
3523                                 else
3524                                         return_val = remove_query_data(op, &rs, &query->q_uuid);
3525                                 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3526                                                         return_val, 0, 0 );
3527                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3528                                 cm->cur_entries -= return_val;
3529                                 cm->num_cached_queries--;
3530                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3531                                                 cm->num_cached_queries, 0, 0 );
3532                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3533                                 Debug( pcache_debug,
3534                                         "STALE QUERY REMOVED, CACHE ="
3535                                         "%d entries\n",
3536                                         cm->cur_entries, 0, 0 );
3537                                 free_query(query);
3538                         } else if ( !templ->ttr && query->expiry_time > ttl ) {
3539                                 /* We don't need to check for refreshes, and this
3540                                  * query's expiry is too new, and all subsequent queries
3541                                  * will be newer yet. So stop looking.
3542                                  *
3543                                  * If we have refreshes, then we always have to walk the
3544                                  * entire query list.
3545                                  */
3546                                 break;
3547                         }
3548                 }
3549         }
3550
3551 leave:
3552         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3553         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3554                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3555         }
3556         /* If there were no queries, defer processing for a while */
3557         if ( cm->cc_paused != pause )
3558                 cm->cc_paused = pause;
3559         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3560
3561         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3562         return NULL;
3563 }
3564
3565
3566 #define MAX_ATTR_SETS 500
3567
3568 enum {
3569         PC_MAIN = 1,
3570         PC_ATTR,
3571         PC_TEMP,
3572         PC_RESP,
3573         PC_QUERIES,
3574         PC_OFFLINE,
3575         PC_BIND,
3576         PC_PRIVATE_DB
3577 };
3578
3579 static ConfigDriver pc_cf_gen;
3580 static ConfigLDAPadd pc_ldadd;
3581 static ConfigCfAdd pc_cfadd;
3582
3583 static ConfigTable pccfg[] = {
3584         { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3585                                 "<cycle_time",
3586                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3587                 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3588                         "DESC 'Proxy Cache basic parameters' "
3589                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3590         { "pcacheAttrset", "index> <attributes...",
3591                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3592                 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3593                         "DESC 'A set of attributes to cache' "
3594                         "SYNTAX OMsDirectoryString )", NULL, NULL },
3595         { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3596                         "<limitTTL> <TTR",
3597                 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3598                 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3599                         "DESC 'Filter template, attrset, cache TTL, "
3600                                 "optional negative TTL, optional sizelimit TTL, "
3601                                 "optional TTR' "
3602                         "SYNTAX OMsDirectoryString )", NULL, NULL },
3603         { "pcachePosition", "head|tail(default)",
3604                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3605                 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3606                         "DESC 'Response callback position in overlay stack' "
3607                         "SYNTAX OMsDirectoryString )", NULL, NULL },
3608         { "pcacheMaxQueries", "queries",
3609                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3610                 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3611                         "DESC 'Maximum number of queries to cache' "
3612                         "SYNTAX OMsInteger )", NULL, NULL },
3613         { "pcachePersist", "TRUE|FALSE",
3614                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3615                 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3616                         "DESC 'Save cached queries for hot restart' "
3617                         "SYNTAX OMsBoolean )", NULL, NULL },
3618         { "pcacheValidate", "TRUE|FALSE",
3619                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3620                 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3621                         "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3622                         "SYNTAX OMsBoolean )", NULL, NULL },
3623         { "pcacheOffline", "TRUE|FALSE",
3624                 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3625                 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3626                         "DESC 'Set cache to offline mode and disable expiration' "
3627                         "SYNTAX OMsBoolean )", NULL, NULL },
3628         { "pcacheBind", "filter> <attrset-index> <TTR> <scope> <base",
3629                 6, 6, 0, ARG_MAGIC|PC_BIND, pc_cf_gen,
3630                 "( OLcfgOvAt:2.9 NAME 'olcPcacheBind' "
3631                         "DESC 'Parameters for caching Binds' "
3632                         "SYNTAX OMsDirectoryString )", NULL, NULL },
3633         { "pcache-", "private database args",
3634                 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3635                 NULL, NULL, NULL },
3636
3637         /* Legacy keywords */
3638         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3639                                 "<cycle_time",
3640                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3641                 NULL, NULL, NULL },
3642         { "proxyattrset", "index> <attributes...",
3643                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3644                 NULL, NULL, NULL },
3645         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3646                 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3647                 NULL, NULL, NULL },
3648         { "response-callback", "head|tail(default)",
3649                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3650                 NULL, NULL, NULL },
3651         { "proxyCacheQueries", "queries",
3652                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3653                 NULL, NULL, NULL },
3654         { "proxySaveQueries", "TRUE|FALSE",
3655                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3656                 NULL, NULL, NULL },
3657         { "proxyCheckCacheability", "TRUE|FALSE",
3658                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3659                 NULL, NULL, NULL },
3660
3661         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3662 };
3663
3664 static ConfigOCs pcocs[] = {
3665         { "( OLcfgOvOc:2.1 "
3666                 "NAME 'olcPcacheConfig' "
3667                 "DESC 'ProxyCache configuration' "
3668                 "SUP olcOverlayConfig "
3669                 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3670                 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3671                         "olcPcacheValidate $ olcPcacheOffline $ olcPcacheBind ) )",
3672                 Cft_Overlay, pccfg, NULL, pc_cfadd },
3673         { "( OLcfgOvOc:2.2 "
3674                 "NAME 'olcPcacheDatabase' "
3675                 "DESC 'Cache database configuration' "
3676                 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3677         { NULL, 0, NULL }
3678 };
3679
3680 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3681
3682 static int
3683 pc_ldadd_cleanup( ConfigArgs *c )
3684 {
3685         slap_overinst *on = c->ca_private;
3686         return pcache_db_open2( on, &c->reply );
3687 }
3688
3689 static int
3690 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3691 {
3692         slap_overinst *on;
3693         cache_manager *cm;
3694
3695         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3696                 p->ce_bi->bi_cf_ocs != pcocs )
3697                 return LDAP_CONSTRAINT_VIOLATION;
3698
3699         on = (slap_overinst *)p->ce_bi;
3700         cm = on->on_bi.bi_private;
3701         ca->be = &cm->db;
3702         /* Defer open if this is an LDAPadd */
3703         if ( CONFIG_ONLINE_ADD( ca ))
3704                 ca->cleanup = pc_ldadd_cleanup;
3705         else
3706                 cm->defer_db_open = 0;
3707         ca->ca_private = on;
3708         return LDAP_SUCCESS;
3709 }
3710
3711 static int
3712 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3713 {
3714         CfEntryInfo *pe = p->e_private;
3715         slap_overinst *on = (slap_overinst *)pe->ce_bi;
3716         cache_manager *cm = on->on_bi.bi_private;
3717         struct berval bv;
3718
3719         /* FIXME: should not hardcode "olcDatabase" here */
3720         bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3721                 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3722                 0, cm->db.bd_info->bi_type );
3723         if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3724                 return -1;
3725         }
3726         bv.bv_val = ca->cr_msg;
3727         ca->be = &cm->db;
3728         cm->defer_db_open = 0;
3729
3730         /* We can only create this entry if the database is table-driven
3731          */
3732         if ( cm->db.bd_info->bi_cf_ocs )
3733                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3734                         &pcocs[1] );
3735
3736         return 0;
3737 }
3738
3739 static int
3740 pc_cf_gen( ConfigArgs *c )
3741 {
3742         slap_overinst   *on = (slap_overinst *)c->bi;
3743         cache_manager*  cm = on->on_bi.bi_private;
3744         query_manager*  qm = cm->qm;
3745         QueryTemplate*  temp;
3746         AttributeName*  attr_name;
3747         AttributeName*  attrarray;
3748         const char*     text=NULL;
3749         int             i, num, rc = 0;
3750         char            *ptr;
3751         unsigned long   t;
3752
3753         if ( c->op == SLAP_CONFIG_EMIT ) {
3754                 struct berval bv;
3755                 switch( c->type ) {
3756                 case PC_MAIN:
3757                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3758                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3759                                 cm->num_entries_limit, cm->cc_period );
3760                         bv.bv_val = c->cr_msg;
3761                         value_add_one( &c->rvalue_vals, &bv );
3762                         break;
3763                 case PC_ATTR:
3764                         for (i=0; i<cm->numattrsets; i++) {
3765                                 if ( !qm->attr_sets[i].count ) continue;
3766
3767                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3768
3769                                 /* count the attr length */
3770                                 for ( attr_name = qm->attr_sets[i].attrs;
3771                                         attr_name->an_name.bv_val; attr_name++ )
3772                                         bv.bv_len += attr_name->an_name.bv_len + 1;
3773
3774                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
3775                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3776                                 for ( attr_name = qm->attr_sets[i].attrs;
3777                                         attr_name->an_name.bv_val; attr_name++ ) {
3778                                         *ptr++ = ' ';
3779                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3780                                 }
3781                                 ber_bvarray_add( &c->rvalue_vals, &bv );
3782                         }
3783                         if ( !c->rvalue_vals )
3784                                 rc = 1;
3785                         break;
3786                 case PC_TEMP:
3787                         for (temp=qm->templates; temp; temp=temp->qmnext) {
3788                                 /* HEADS-UP: always print all;
3789                                  * if optional == 0, ignore */
3790                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3791                                         " %d %ld %ld %ld %ld",
3792                                         temp->attr_set_index,
3793                                         temp->ttl,
3794                                         temp->negttl,
3795                                         temp->limitttl,
3796                                         temp->ttr );
3797                                 bv.bv_len += temp->querystr.bv_len + 2;
3798                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
3799                                 ptr = bv.bv_val;
3800                                 *ptr++ = '"';
3801                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3802                                 *ptr++ = '"';
3803                                 strcpy( ptr, c->cr_msg );
3804                                 ber_bvarray_add( &c->rvalue_vals, &bv );
3805                         }
3806                         if ( !c->rvalue_vals )
3807                                 rc = 1;
3808                         break;
3809                 case PC_BIND:
3810                         for (temp=qm->templates; temp; temp=temp->qmnext) {
3811                                 if ( !temp->bindttr ) continue;
3812                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3813                                         " %d %ld %s ",
3814                                         temp->attr_set_index,
3815                                         temp->bindttr,
3816                                         ldap_pvt_scope2str( temp->bindscope ));
3817                                 bv.bv_len += temp->bindbase.bv_len + temp->bindftemp.bv_len + 4;
3818                                 bv.bv_val = ch_malloc( bv.bv_len + 1 );
3819                                 ptr = bv.bv_val;
3820                                 *ptr++ = '"';
3821                                 ptr = lutil_strcopy( ptr, temp->bindftemp.bv_val );
3822                                 *ptr++ = '"';
3823                                 ptr = lutil_strcopy( ptr, c->cr_msg );
3824                                 *ptr++ = '"';
3825                                 ptr = lutil_strcopy( ptr, temp->bindbase.bv_val );
3826                                 *ptr++ = '"';
3827                                 *ptr = '\0';
3828                                 ber_bvarray_add( &c->rvalue_vals, &bv );
3829                         }
3830                         if ( !c->rvalue_vals )
3831                                 rc = 1;
3832                         break;
3833                 case PC_RESP:
3834                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3835                                 BER_BVSTR( &bv, "head" );
3836                         } else {
3837                                 BER_BVSTR( &bv, "tail" );
3838                         }
3839                         value_add_one( &c->rvalue_vals, &bv );
3840                         break;
3841                 case PC_QUERIES:
3842                         c->value_int = cm->max_queries;
3843                         break;
3844                 case PC_OFFLINE:
3845                         c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3846                         break;
3847                 }
3848                 return rc;
3849         } else if ( c->op == LDAP_MOD_DELETE ) {
3850                 rc = 1;
3851                 switch( c->type ) {
3852                 case PC_ATTR: /* FIXME */
3853                 case PC_TEMP:
3854                 case PC_BIND:
3855                         break;
3856                 case PC_OFFLINE:
3857                         cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3858                         /* If there were cached queries when we went offline,
3859                          * restart the checker now.
3860                          */
3861                         if ( cm->num_cached_queries ) {
3862                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3863                                 cm->cc_paused = 0;
3864                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3865                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3866                         }
3867                         rc = 0;
3868                         break;
3869                 }
3870                 return rc;
3871         }
3872
3873         switch( c->type ) {
3874         case PC_MAIN:
3875                 if ( cm->numattrsets > 0 ) {
3876                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive already provided" );
3877                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3878                         return( 1 );
3879                 }
3880
3881                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3882                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3883                                 c->argv[3] );
3884                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3885                         return( 1 );
3886                 }
3887                 if ( cm->numattrsets <= 0 ) {
3888                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3889                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3890                         return( 1 );
3891                 }
3892                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3893                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3894                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3895                         return( 1 );
3896                 }
3897
3898                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3899                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3900                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3901                         return( 1 );
3902                 }
3903
3904                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3905                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3906                                 c->argv[2] );
3907                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3908                         return( 1 );
3909                 }
3910                 if ( cm->max_entries <= 0 ) {
3911                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3912                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
3913                         return( 1 );
3914                 }
3915
3916                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
3917                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
3918                                 c->argv[4] );
3919                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3920                         return( 1 );
3921                 }
3922                 if ( cm->num_entries_limit <= 0 ) {
3923                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
3924                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3925                         return( 1 );
3926                 }
3927                 if ( cm->num_entries_limit > cm->max_entries ) {
3928                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
3929                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3930                         return( 1 );
3931                 }
3932
3933                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3934                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
3935                                 c->argv[5] );
3936                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3937                         return( 1 );
3938                 }
3939
3940                 cm->cc_period = (time_t)t;
3941                 Debug( pcache_debug,
3942                                 "Total # of attribute sets to be cached = %d.\n",
3943                                 cm->numattrsets, 0, 0 );
3944                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
3945                                                 sizeof( struct attr_set ) );
3946                 break;
3947         case PC_ATTR:
3948                 if ( cm->numattrsets == 0 ) {
3949                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
3950                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3951                         return( 1 );
3952                 }
3953                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
3954                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
3955                                 c->argv[1] );
3956                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3957                         return( 1 );
3958                 }
3959
3960                 if ( num < 0 || num >= cm->numattrsets ) {
3961                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
3962                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3963                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3964                         return 1;
3965                 }
3966                 qm->attr_sets[num].flags |= PC_CONFIGURED;
3967                 if ( c->argc == 2 ) {
3968                         /* assume "1.1" */
3969                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3970                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
3971                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3972                         return 1;
3973
3974                 } else if ( c->argc == 3 ) {
3975                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3976                                 qm->attr_sets[num].count = 1;
3977                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3978                                         sizeof( AttributeName ) );
3979                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
3980                                 break;
3981
3982                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3983                                 qm->attr_sets[num].count = 1;
3984                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3985                                         sizeof( AttributeName ) );
3986                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3987                                 break;
3988
3989                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
3990                                 break;
3991                         }
3992                         /* else: fallthru */
3993
3994                 } else if ( c->argc == 4 ) {
3995                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
3996                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
3997                         {
3998                                 qm->attr_sets[num].count = 2;
3999                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
4000                                         sizeof( AttributeName ) );
4001                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4002                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4003                                 break;
4004                         }
4005                         /* else: fallthru */
4006                 }
4007
4008                 if ( c->argc > 2 ) {
4009                         int all_user = 0, all_op = 0;
4010
4011                         qm->attr_sets[num].count = c->argc - 2;
4012                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
4013                                 sizeof( AttributeName ) );
4014                         attr_name = qm->attr_sets[num].attrs;
4015                         for ( i = 2; i < c->argc; i++ ) {
4016                                 attr_name->an_desc = NULL;
4017                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
4018                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4019                                                 "invalid attr #%d \"%s\" in attrlist",
4020                                                 i - 2, c->argv[i] );
4021                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4022                                         ch_free( qm->attr_sets[num].attrs );
4023                                         qm->attr_sets[num].attrs = NULL;
4024                                         qm->attr_sets[num].count = 0;
4025                                         return 1;
4026                                 }
4027                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4028                                         all_user = 1;
4029                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
4030                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4031                                         all_op = 1;
4032                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4033                                 } else {
4034                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
4035                                                 strcpy( c->cr_msg, text );
4036                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4037                                                 ch_free( qm->attr_sets[num].attrs );
4038                                                 qm->attr_sets[num].attrs = NULL;
4039                                                 qm->attr_sets[num].count = 0;
4040                                                 return 1;
4041                                         }
4042                                         attr_name->an_name = attr_name->an_desc->ad_cname;
4043                                 }
4044                                 attr_name->an_oc = NULL;
4045                                 attr_name->an_flags = 0;
4046                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
4047                                         qm->attr_sets[num].flags |= PC_GOT_OC;
4048                                 attr_name++;
4049                                 BER_BVZERO( &attr_name->an_name );
4050                         }
4051
4052                         /* warn if list contains both "*" and "+" */
4053                         if ( i > 4 && all_user && all_op ) {
4054                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4055                                         "warning: attribute list contains \"*\" and \"+\"" );
4056                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4057                         }
4058                 }
4059                 break;
4060         case PC_TEMP:
4061                 if ( cm->numattrsets == 0 ) {
4062                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4063                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4064                         return( 1 );
4065                 }
4066                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4067                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
4068                                 c->argv[2] );
4069                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4070                         return( 1 );
4071                 }
4072
4073                 if ( i < 0 || i >= cm->numattrsets || 
4074                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4075                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
4076                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4077                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4078                         return 1;
4079                 }
4080                 {
4081                         AttributeName *attrs;
4082                         int cnt;
4083                         cnt = template_attrs( c->argv[1], &qm->attr_sets[i], &attrs, &text );
4084                         if ( cnt < 0 ) {
4085                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4086                                         text );
4087                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4088                                 return 1;
4089                         }
4090                         temp = ch_calloc( 1, sizeof( QueryTemplate ));
4091                         temp->qmnext = qm->templates;
4092                         qm->templates = temp;
4093                         temp->t_attrs.attrs = attrs;
4094                         temp->t_attrs.count = cnt;
4095                 }
4096                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
4097                 temp->query = temp->query_last = NULL;
4098                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4099                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4100                                 "unable to parse template ttl=\"%s\"",
4101                                 c->argv[3] );
4102                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4103 pc_temp_fail:
4104                         ch_free( temp->t_attrs.attrs );
4105                         ch_free( temp );
4106                         return( 1 );
4107                 }
4108                 temp->ttl = (time_t)t;
4109                 temp->negttl = (time_t)0;
4110                 temp->limitttl = (time_t)0;
4111                 temp->ttr = (time_t)0;
4112                 switch ( c->argc ) {
4113                 case 7:
4114                         if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
4115                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4116                                         "unable to parse template ttr=\"%s\"",
4117                                         c->argv[6] );
4118                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4119                                 goto pc_temp_fail;
4120                         }
4121                         temp->ttr = (time_t)t;
4122                         /* fallthru */
4123
4124                 case 6:
4125                         if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4126                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4127                                         "unable to parse template sizelimit ttl=\"%s\"",
4128                                         c->argv[5] );
4129                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4130                                 goto pc_temp_fail;
4131                         }
4132                         temp->limitttl = (time_t)t;
4133                         /* fallthru */
4134
4135                 case 5:
4136                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
4137                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4138                                         "unable to parse template negative ttl=\"%s\"",
4139                                         c->argv[4] );
4140                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4141                                 goto pc_temp_fail;
4142                         }
4143                         temp->negttl = (time_t)t;
4144                         break;
4145                 }
4146
4147                 temp->no_of_queries = 0;
4148
4149                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
4150                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
4151                 Debug( pcache_debug, "  query template: %s\n",
4152                                 temp->querystr.bv_val, 0, 0 );
4153                 temp->attr_set_index = i;
4154                 qm->attr_sets[i].flags |= PC_REFERENCED;
4155                 temp->qtnext = qm->attr_sets[i].templates;
4156                 qm->attr_sets[i].templates = temp;
4157                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
4158                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
4159                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
4160                                 Debug( pcache_debug, "\t%s\n",
4161                                         attrarray[i].an_name.bv_val, 0, 0 );
4162                 }
4163                 break;
4164         case PC_BIND:
4165                 if ( !qm->templates ) {
4166                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcacheTemplate\" directive not provided yet" );
4167                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4168                         return( 1 );
4169                 }
4170                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4171                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse Bind index #=\"%s\"",
4172                                 c->argv[2] );
4173                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4174                         return( 1 );
4175                 }
4176
4177                 if ( i < 0 || i >= cm->numattrsets || 
4178                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4179                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind index %d invalid (%s%d)",
4180                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4181                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4182                         return 1;
4183                 }
4184                 {       struct berval bv, tempbv;
4185                         AttributeDescription **descs;
4186                         int ndescs;
4187                         ber_str2bv( c->argv[1], 0, 0, &bv );
4188                         ndescs = ftemp_attrs( &bv, &tempbv, &descs, &text );
4189                         if ( ndescs < 0 ) {
4190                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4191                                         text );
4192                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4193                                 return 1;
4194                         }
4195                         for ( temp = qm->templates; temp; temp=temp->qmnext ) {
4196                                 if ( temp->attr_set_index == i && bvmatch( &tempbv,
4197                                         &temp->querystr ))
4198                                         break;
4199                         }
4200                         ch_free( tempbv.bv_val );
4201                         if ( !temp ) {
4202                                 ch_free( descs );
4203                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind template %s %d invalid",
4204                                         c->argv[1], i );
4205                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4206                                 return 1;
4207                         }
4208                         ber_dupbv( &temp->bindftemp, &bv );
4209                         temp->bindfattrs = descs;
4210                         temp->bindnattrs = ndescs;
4211                 }
4212                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4213                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4214                                 "unable to parse bind ttr=\"%s\"",
4215                                 c->argv[3] );
4216                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4217 pc_bind_fail:
4218                         ch_free( temp->bindfattrs );
4219                         temp->bindfattrs = NULL;
4220                         ch_free( temp->bindftemp.bv_val );
4221                         BER_BVZERO( &temp->bindftemp );
4222                         return( 1 );
4223                 }
4224                 num = ldap_pvt_str2scope( c->argv[4] );
4225                 if ( num < 0 ) {
4226                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4227                                 "unable to parse bind scope=\"%s\"",
4228                                 c->argv[4] );
4229                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4230                         goto pc_bind_fail;
4231                 }
4232                 {
4233                         struct berval dn, ndn;
4234                         ber_str2bv( c->argv[5], 0, 0, &dn );
4235                         rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
4236                         if ( rc ) {
4237                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4238                                         "invalid bind baseDN=\"%s\"",
4239                                         c->argv[5] );
4240                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4241                                 goto pc_bind_fail;
4242                         }
4243                         if ( temp->bindbase.bv_val )
4244                                 ch_free( temp->bindbase.bv_val );
4245                         temp->bindbase = ndn;
4246                 }
4247                 {
4248                         /* convert the template into dummy filter */
4249                         struct berval bv;
4250                         char *eq = temp->bindftemp.bv_val, *e2;
4251                         Filter *f;
4252                         i = 0;
4253                         while ((eq = strchr(eq, '=' ))) {
4254                                 eq++;
4255                                 if ( eq[1] == ')' )
4256                                         i++;
4257                         }
4258                         bv.bv_len = temp->bindftemp.bv_len + i;
4259                         bv.bv_val = ch_malloc( bv.bv_len + 1 );
4260                         for ( e2 = bv.bv_val, eq = temp->bindftemp.bv_val;
4261                                 *eq; eq++ ) {
4262                                 if ( *eq == '=' ) {
4263                                         *e2++ = '=';
4264                                         if ( eq[1] == ')' )
4265                                                 *e2++ = '*';
4266                                 } else {
4267                                         *e2++ = *eq;
4268                                 }
4269                         }
4270                         *e2 = '\0';
4271                         f = str2filter( bv.bv_val );
4272                         if ( !f ) {
4273                                 ch_free( bv.bv_val );
4274                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4275                                         "unable to parse bindfilter=\"%s\"", bv.bv_val );
4276                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4277                                 ch_free( temp->bindbase.bv_val );
4278                                 BER_BVZERO( &temp->bindbase );
4279                                 goto pc_bind_fail;
4280                         }
4281                         if ( temp->bindfilter )
4282                                 filter_free( temp->bindfilter );
4283                         if ( temp->bindfilterstr.bv_val )
4284                                 ch_free( temp->bindfilterstr.bv_val );
4285                         temp->bindfilterstr = bv;
4286                         temp->bindfilter = f;
4287                 }
4288                 temp->bindttr = (time_t)t;
4289                 temp->bindscope = num;
4290                 cm->cache_binds = 1;
4291                 break;
4292
4293         case PC_RESP:
4294                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
4295                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
4296
4297                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
4298                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4299
4300                 } else {
4301                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
4302                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4303                         return 1;
4304                 }
4305                 break;
4306         case PC_QUERIES:
4307                 if ( c->value_int <= 0 ) {
4308                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
4309                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4310                         return( 1 );
4311                 }
4312                 cm->max_queries = c->value_int;
4313                 break;
4314         case PC_OFFLINE:
4315                 if ( c->value_int )
4316                         cm->cc_paused |= PCACHE_CC_OFFLINE;
4317                 else
4318                         cm->cc_paused &= ~PCACHE_CC_OFFLINE;
4319                 break;
4320         case PC_PRIVATE_DB:
4321                 if ( cm->db.be_private == NULL ) {
4322                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4323                                 "private database must be defined before setting database specific options" );
4324                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4325                         return( 1 );
4326                 }
4327
4328                 if ( cm->db.bd_info->bi_cf_ocs ) {
4329                         ConfigTable     *ct;
4330                         ConfigArgs      c2 = *c;
4331                         char            *argv0 = c->argv[ 0 ];
4332
4333                         c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4334
4335                         ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
4336                         if ( ct == NULL ) {
4337                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4338                                         "private database does not recognize specific option '%s'",
4339                                         c->argv[ 0 ] );
4340                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4341                                 rc = 1;
4342
4343                         } else {
4344                                 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
4345                                 c->be = &cm->db;
4346                                 c->bi = c->be->bd_info;
4347
4348                                 rc = config_add_vals( ct, c );
4349
4350                                 c->bi = c2.bi;
4351                                 c->be = c2.be;
4352                                 c->table = c2.table;
4353                         }
4354
4355                         c->argv[ 0 ] = argv0;
4356
4357                 } else if ( cm->db.be_config != NULL ) {
4358                         char    *argv0 = c->argv[ 0 ];
4359
4360                         c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4361                         rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
4362                         c->argv[ 0 ] = argv0;
4363
4364                 } else {
4365                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4366                                 "no means to set private database specific options" );
4367                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4368                         return 1;
4369                 }
4370                 break;
4371         default:
4372                 rc = SLAP_CONF_UNKNOWN;
4373                 break;
4374         }
4375
4376         return rc;
4377 }
4378
4379 static int
4380 pcache_db_config(
4381         BackendDB       *be,
4382         const char      *fname,
4383         int             lineno,
4384         int             argc,
4385         char            **argv
4386 )
4387 {
4388         slap_overinst   *on = (slap_overinst *)be->bd_info;
4389         cache_manager*  cm = on->on_bi.bi_private;
4390
4391         /* Something for the cache database? */
4392         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
4393                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
4394                         argc, argv );
4395         return SLAP_CONF_UNKNOWN;
4396 }
4397
4398 static int
4399 pcache_db_init(
4400         BackendDB *be,
4401         ConfigReply *cr)
4402 {
4403         slap_overinst *on = (slap_overinst *)be->bd_info;
4404         cache_manager *cm;
4405         query_manager *qm;
4406
4407         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
4408         on->on_bi.bi_private = cm;
4409
4410         qm = (query_manager*)ch_malloc(sizeof(query_manager));
4411
4412         cm->db = *be;
4413         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
4414         cm->db.be_private = NULL;
4415         cm->db.bd_self = &cm->db;
4416         cm->qm = qm;
4417         cm->numattrsets = 0;
4418         cm->num_entries_limit = 5;
4419         cm->num_cached_queries = 0;
4420         cm->max_entries = 0;
4421         cm->cur_entries = 0;
4422         cm->max_queries = 10000;
4423         cm->save_queries = 0;
4424         cm->check_cacheability = 0;
4425         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4426         cm->defer_db_open = 1;
4427         cm->cache_binds = 0;
4428         cm->cc_period = 1000;
4429         cm->cc_paused = 0;
4430         cm->cc_arg = NULL;
4431 #ifdef PCACHE_MONITOR
4432         cm->monitor_cb = NULL;
4433 #endif /* PCACHE_MONITOR */
4434
4435         qm->attr_sets = NULL;
4436         qm->templates = NULL;
4437         qm->lru_top = NULL;
4438         qm->lru_bottom = NULL;
4439
4440         qm->qcfunc = query_containment;
4441         qm->crfunc = cache_replacement;
4442         qm->addfunc = add_query;
4443         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
4444
4445         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
4446
4447 #ifndef PCACHE_MONITOR
4448         return 0;
4449 #else /* PCACHE_MONITOR */
4450         return pcache_monitor_db_init( be );
4451 #endif /* PCACHE_MONITOR */
4452 }
4453
4454 static int
4455 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
4456 {
4457         assert( op->o_tag == LDAP_REQ_SEARCH );
4458
4459         if ( rs->sr_type == REP_SEARCH ) {
4460                 Attribute       *a;
4461
4462                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
4463                 if ( a != NULL ) {
4464                         BerVarray       *valsp;
4465
4466                         assert( a->a_nvals != NULL );
4467
4468                         valsp = op->o_callback->sc_private;
4469                         assert( *valsp == NULL );
4470
4471                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
4472                 }
4473         }
4474
4475         return 0;
4476 }
4477
4478 static int
4479 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
4480 {
4481         assert( op->o_tag == LDAP_REQ_SEARCH );
4482
4483         if ( rs->sr_type == REP_SEARCH ) {
4484                 int     *countp = (int *)op->o_callback->sc_private;
4485
4486                 (*countp)++;
4487         }
4488
4489         return 0;
4490 }
4491
4492 static int
4493 pcache_db_open2(
4494         slap_overinst *on,
4495         ConfigReply *cr )
4496 {
4497         cache_manager   *cm = on->on_bi.bi_private;
4498         query_manager*  qm = cm->qm;
4499         int rc;
4500
4501         rc = backend_startup_one( &cm->db, cr );
4502         if ( rc == 0 ) {
4503                 cm->defer_db_open = 0;
4504         }
4505
4506         /* There is no runqueue in TOOL mode */
4507         if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
4508                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4509                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
4510                         consistency_check, on,
4511                         "pcache_consistency", cm->db.be_suffix[0].bv_val );
4512                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4513
4514                 /* Cached database must have the rootdn */
4515                 if ( BER_BVISNULL( &cm->db.be_rootndn )
4516                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
4517                 {
4518                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
4519                                 "underlying database of type \"%s\"\n"
4520                                 "    serving naming context \"%s\"\n"
4521                                 "    has no \"rootdn\", required by \"pcache\".\n",
4522                                 on->on_info->oi_orig->bi_type,
4523                                 cm->db.be_suffix[0].bv_val, 0 );
4524                         return 1;
4525                 }
4526
4527                 if ( cm->save_queries ) {
4528                         void            *thrctx = ldap_pvt_thread_pool_context();
4529                         Connection      conn = { 0 };
4530                         OperationBuffer opbuf;
4531                         Operation       *op;
4532                         slap_callback   cb = { 0 };
4533                         SlapReply       rs = { 0 };
4534                         BerVarray       vals = NULL;
4535                         Filter          f = { 0 }, f2 = { 0 };
4536                         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
4537                         AttributeName   attrs[ 2 ] = {{{ 0 }}};
4538
4539                         connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4540                         op = &opbuf.ob_op;
4541
4542                         op->o_bd = &cm->db;
4543
4544                         op->o_tag = LDAP_REQ_SEARCH;
4545                         op->o_protocol = LDAP_VERSION3;
4546                         cb.sc_response = pcache_cachedquery_open_cb;
4547                         cb.sc_private = &vals;
4548                         op->o_callback = &cb;
4549                         op->o_time = slap_get_time();
4550                         op->o_do_not_cache = 1;
4551                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
4552
4553                         op->o_dn = cm->db.be_rootdn;
4554                         op->o_ndn = cm->db.be_rootndn;
4555                         op->o_req_dn = cm->db.be_suffix[ 0 ];
4556                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
4557
4558                         op->ors_scope = LDAP_SCOPE_BASE;
4559                         op->ors_deref = LDAP_DEREF_NEVER;
4560                         op->ors_slimit = 1;
4561                         op->ors_tlimit = SLAP_NO_LIMIT;
4562                         op->ors_limit = NULL;
4563                         ber_str2bv( "(pcacheQueryURL=*)", 0, 0, &op->ors_filterstr );
4564                         f.f_choice = LDAP_FILTER_PRESENT;
4565                         f.f_desc = ad_cachedQueryURL;
4566                         op->ors_filter = &f;
4567                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
4568                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
4569                         op->ors_attrs = attrs;
4570                         op->ors_attrsonly = 0;
4571
4572                         rc = op->o_bd->be_search( op, &rs );
4573                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
4574                                 int     i;
4575
4576                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
4577                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
4578                                                 cm->num_cached_queries++;
4579                                         }
4580                                 }
4581
4582                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4583                         }
4584
4585                         /* count cached entries */
4586                         f.f_choice = LDAP_FILTER_NOT;
4587                         f.f_not = &f2;
4588                         f2.f_choice = LDAP_FILTER_EQUALITY;
4589                         f2.f_ava = &ava;
4590                         f2.f_av_desc = slap_schema.si_ad_objectClass;
4591                         BER_BVSTR( &f2.f_av_value, "glue" );
4592                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
4593
4594                         op->ors_slimit = SLAP_NO_LIMIT;
4595                         op->ors_scope = LDAP_SCOPE_SUBTREE;
4596                         op->ors_attrs = slap_anlist_no_attrs;
4597
4598                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
4599                         rs.sr_nentries = 0;
4600                         op->o_callback->sc_private = &rs.sr_nentries;
4601
4602                         rc = op->o_bd->be_search( op, &rs );
4603
4604                         cm->cur_entries = rs.sr_nentries;
4605
4606                         /* ignore errors */
4607                         rc = 0;
4608                 }
4609         }
4610         return rc;
4611 }
4612
4613 static int
4614 pcache_db_open(
4615         BackendDB *be,
4616         ConfigReply *cr )
4617 {
4618         slap_overinst   *on = (slap_overinst *)be->bd_info;
4619         cache_manager   *cm = on->on_bi.bi_private;
4620         query_manager*  qm = cm->qm;
4621         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
4622
4623         /* check attr sets */
4624         for ( i = 0; i < cm->numattrsets; i++) {
4625                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
4626                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
4627                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
4628                                 rf++;
4629
4630                         } else {
4631                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
4632                         }
4633                         ncf++;
4634
4635                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
4636                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
4637                         nrf++;
4638                 }
4639         }
4640
4641         if ( ncf || rf || nrf ) {
4642                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
4643                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
4644                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
4645
4646                 if ( rf > 0 ) {
4647                         return 1;
4648                 }
4649         }
4650
4651         /* need to inherit something from the original database... */
4652         cm->db.be_def_limit = be->be_def_limit;
4653         cm->db.be_limits = be->be_limits;
4654         cm->db.be_acl = be->be_acl;
4655         cm->db.be_dfltaccess = be->be_dfltaccess;
4656
4657         if ( SLAP_DBMONITORING( be ) ) {
4658                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
4659
4660         } else {
4661                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
4662         }
4663
4664         if ( !cm->defer_db_open ) {
4665                 rc = pcache_db_open2( on, cr );
4666         }
4667
4668 #ifdef PCACHE_MONITOR
4669         if ( rc == LDAP_SUCCESS ) {
4670                 rc = pcache_monitor_db_open( be );
4671         }
4672 #endif /* PCACHE_MONITOR */
4673
4674         return rc;
4675 }
4676
4677 static void
4678 pcache_free_qbase( void *v )
4679 {
4680         Qbase *qb = v;
4681         int i;
4682
4683         for (i=0; i<3; i++)
4684                 tavl_free( qb->scopes[i], NULL );
4685         ch_free( qb );
4686 }
4687
4688 static int
4689 pcache_db_close(
4690         BackendDB *be,
4691         ConfigReply *cr
4692 )
4693 {
4694         slap_overinst *on = (slap_overinst *)be->bd_info;
4695         cache_manager *cm = on->on_bi.bi_private;
4696         query_manager *qm = cm->qm;
4697         QueryTemplate *tm;
4698         int i, rc = 0;
4699
4700         /* stop the thread ... */
4701         if ( cm->cc_arg ) {
4702                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4703                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4704                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4705                 }
4706                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4707                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4708         }
4709
4710         if ( cm->save_queries ) {
4711                 CachedQuery     *qc;
4712                 BerVarray       vals = NULL;
4713
4714                 void            *thrctx;
4715                 Connection      conn = { 0 };
4716                 OperationBuffer opbuf;
4717                 Operation       *op;
4718                 slap_callback   cb = { 0 };
4719
4720                 SlapReply       rs = { REP_RESULT };
4721                 Modifications   mod = {{ 0 }};
4722
4723                 thrctx = ldap_pvt_thread_pool_context();
4724
4725                 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4726                 op = &opbuf.ob_op;
4727
4728                 if ( qm->templates != NULL ) {
4729                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4730                                 for ( qc = tm->query; qc; qc = qc->next ) {
4731                                         struct berval   bv;
4732
4733                                         if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4734                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4735                                         }
4736                                 }
4737                         }
4738                 }
4739
4740                 op->o_bd = &cm->db;
4741                 op->o_dn = cm->db.be_rootdn;
4742                 op->o_ndn = cm->db.be_rootndn;
4743
4744                 op->o_tag = LDAP_REQ_MODIFY;
4745                 op->o_protocol = LDAP_VERSION3;
4746                 cb.sc_response = slap_null_cb;
4747                 op->o_callback = &cb;
4748                 op->o_time = slap_get_time();
4749                 op->o_do_not_cache = 1;
4750                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4751
4752                 op->o_req_dn = op->o_bd->be_suffix[0];
4753                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4754
4755                 mod.sml_op = LDAP_MOD_REPLACE;
4756                 mod.sml_flags = 0;
4757                 mod.sml_desc = ad_cachedQueryURL;
4758                 mod.sml_type = ad_cachedQueryURL->ad_cname;
4759                 mod.sml_values = vals;
4760                 mod.sml_nvalues = NULL;
4761                 mod.sml_numvals = 1;
4762                 mod.sml_next = NULL;
4763                 Debug( pcache_debug,
4764                         "%sSETTING CACHED QUERY URLS\n",
4765                         vals == NULL ? "RE" : "", 0, 0 );
4766
4767                 op->orm_modlist = &mod;
4768
4769                 op->o_bd->be_modify( op, &rs );
4770
4771                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4772         }
4773
4774         /* cleanup stuff inherited from the original database... */
4775         cm->db.be_limits = NULL;
4776         cm->db.be_acl = NULL;
4777
4778
4779         if ( cm->db.bd_info->bi_db_close ) {
4780                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4781         }
4782         while ( (tm = qm->templates) != NULL ) {
4783                 CachedQuery *qc, *qn;
4784                 qm->templates = tm->qmnext;
4785                 for ( qc = tm->query; qc; qc = qn ) {
4786                         qn = qc->next;
4787                         free_query( qc );
4788                 }
4789                 avl_free( tm->qbase, pcache_free_qbase );
4790                 free( tm->querystr.bv_val );
4791                 free( tm->bindfattrs );
4792                 free( tm->bindftemp.bv_val );
4793                 free( tm->bindfilterstr.bv_val );
4794                 free( tm->bindbase.bv_val );
4795                 filter_free( tm->bindfilter );
4796                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4797                 free( tm->t_attrs.attrs );
4798                 free( tm );
4799         }
4800
4801         for ( i=0; i<cm->numattrsets; i++ ) {
4802                 free( qm->attr_sets[i].attrs );
4803         }
4804         free( qm->attr_sets );
4805         qm->attr_sets = NULL;
4806
4807 #ifdef PCACHE_MONITOR
4808         if ( rc == LDAP_SUCCESS ) {
4809                 rc = pcache_monitor_db_close( be );
4810         }
4811 #endif /* PCACHE_MONITOR */
4812
4813         return rc;
4814 }
4815
4816 static int
4817 pcache_db_destroy(
4818         BackendDB *be,
4819         ConfigReply *cr
4820 )
4821 {
4822         slap_overinst *on = (slap_overinst *)be->bd_info;
4823         cache_manager *cm = on->on_bi.bi_private;
4824         query_manager *qm = cm->qm;
4825
4826         if ( cm->db.be_private != NULL ) {
4827                 backend_stopdown_one( &cm->db );
4828         }
4829
4830         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4831         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4832         free( qm );
4833         free( cm );
4834
4835 #ifdef PCACHE_MONITOR
4836         pcache_monitor_db_destroy( be );
4837 #endif /* PCACHE_MONITOR */
4838
4839         return 0;
4840 }
4841
4842 #ifdef PCACHE_CONTROL_PRIVDB
4843 /*
4844         Control ::= SEQUENCE {
4845              controlType             LDAPOID,
4846              criticality             BOOLEAN DEFAULT FALSE,
4847              controlValue            OCTET STRING OPTIONAL }
4848
4849         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4850
4851  * criticality must be TRUE; controlValue must be absent.
4852  */
4853 static int
4854 parse_privdb_ctrl(
4855         Operation       *op,
4856         SlapReply       *rs,
4857         LDAPControl     *ctrl )
4858 {
4859         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4860                 rs->sr_text = "privateDB control specified multiple times";
4861                 return LDAP_PROTOCOL_ERROR;
4862         }
4863
4864         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4865                 rs->sr_text = "privateDB control value not absent";
4866                 return LDAP_PROTOCOL_ERROR;
4867         }
4868
4869         if ( !ctrl->ldctl_iscritical ) {
4870                 rs->sr_text = "privateDB control criticality required";
4871                 return LDAP_PROTOCOL_ERROR;
4872         }
4873
4874         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4875
4876         return LDAP_SUCCESS;
4877 }
4878
4879 static char *extops[] = {
4880         LDAP_EXOP_MODIFY_PASSWD,
4881         NULL
4882 };
4883 #endif /* PCACHE_CONTROL_PRIVDB */
4884
4885 static struct berval pcache_exop_MODIFY_PASSWD = BER_BVC( LDAP_EXOP_MODIFY_PASSWD );
4886 #ifdef PCACHE_EXOP_QUERY_DELETE
4887 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4888
4889 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4890 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4891 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
4892
4893 /*
4894         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
4895              requestName      [0] LDAPOID,
4896              requestValue     [1] OCTET STRING OPTIONAL }
4897
4898         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
4899
4900         requestValue ::= SEQUENCE { CHOICE {
4901                   baseDN           [0] LDAPDN
4902                   entryDN          [1] LDAPDN },
4903              queryID          [2] OCTET STRING (SIZE(16))
4904                   -- constrained to UUID }
4905
4906  * Either baseDN or entryDN must be present, to allow database selection.
4907  *
4908  * 1. if baseDN and queryID are present, then the query corresponding
4909  *    to queryID is deleted;
4910  * 2. if baseDN is present and queryID is absent, then all queries
4911  *    are deleted;
4912  * 3. if entryDN is present and queryID is absent, then all queries
4913  *    corresponding to the queryID values present in entryDN are deleted;
4914  * 4. if entryDN and queryID are present, then all queries
4915  *    corresponding to the queryID values present in entryDN are deleted,
4916  *    but only if the value of queryID is contained in the entry;
4917  *
4918  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
4919  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
4920  * or by removing the database files.
4921
4922         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
4923              COMPONENTS OF LDAPResult,
4924              responseName     [10] LDAPOID OPTIONAL,
4925              responseValue    [11] OCTET STRING OPTIONAL }
4926
4927  * responseName and responseValue must be absent.
4928  */
4929
4930 /*
4931  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
4932  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
4933  * - if ndn != NULL, it is set to the normalized DN in the request
4934  *   corresponding to either the baseDN or the entryDN, according
4935  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
4936  *   be freed by the caller.
4937  * - if uuid != NULL, it is set to point to the normalized UUID;
4938  *   memory is malloc'ed on the Operation's slab, and must
4939  *   be freed by the caller.
4940  */
4941 static int
4942 pcache_parse_query_delete(
4943         struct berval   *in,
4944         ber_tag_t       *tagp,
4945         struct berval   *ndn,
4946         struct berval   *uuid,
4947         const char      **text,
4948         void            *ctx )
4949 {
4950         int                     rc = LDAP_SUCCESS;
4951         ber_tag_t               tag;
4952         ber_len_t               len = -1;
4953         BerElementBuffer        berbuf;
4954         BerElement              *ber = (BerElement *)&berbuf;
4955         struct berval           reqdata = BER_BVNULL;
4956
4957         *text = NULL;
4958
4959         if ( ndn ) {
4960                 BER_BVZERO( ndn );
4961         }
4962
4963         if ( uuid ) {
4964                 BER_BVZERO( uuid );
4965         }
4966
4967         if ( in == NULL || in->bv_len == 0 ) {
4968                 *text = "empty request data field in queryDelete exop";
4969                 return LDAP_PROTOCOL_ERROR;
4970         }
4971
4972         ber_dupbv_x( &reqdata, in, ctx );
4973
4974         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
4975         ber_init2( ber, &reqdata, 0 );
4976
4977         tag = ber_scanf( ber, "{" /*}*/ );
4978
4979         if ( tag == LBER_ERROR ) {
4980                 Debug( LDAP_DEBUG_TRACE,
4981                         "pcache_parse_query_delete: decoding error.\n",
4982                         0, 0, 0 );
4983                 goto decoding_error;
4984         }
4985
4986         tag = ber_peek_tag( ber, &len );
4987         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
4988                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
4989         {
4990                 *tagp = tag;
4991
4992                 if ( ndn != NULL ) {
4993                         struct berval   dn;
4994
4995                         tag = ber_scanf( ber, "m", &dn );
4996                         if ( tag == LBER_ERROR ) {
4997                                 Debug( LDAP_DEBUG_TRACE,
4998                                         "pcache_parse_query_delete: DN parse failed.\n",
4999                                         0, 0, 0 );
5000                                 goto decoding_error;
5001                         }
5002
5003                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
5004                         if ( rc != LDAP_SUCCESS ) {
5005                                 *text = "invalid DN in queryDelete exop request data";
5006                                 goto done;
5007                         }
5008
5009                 } else {
5010                         tag = ber_scanf( ber, "x" /* "m" */ );
5011                         if ( tag == LBER_DEFAULT ) {
5012                                 goto decoding_error;
5013                         }
5014                 }
5015
5016                 tag = ber_peek_tag( ber, &len );
5017         }
5018
5019         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
5020                 if ( uuid != NULL ) {
5021                         struct berval   bv;
5022                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
5023
5024                         tag = ber_scanf( ber, "m", &bv );
5025                         if ( tag == LBER_ERROR ) {
5026                                 Debug( LDAP_DEBUG_TRACE,
5027                                         "pcache_parse_query_delete: UUID parse failed.\n",
5028                                         0, 0, 0 );
5029                                 goto decoding_error;
5030                         }
5031
5032                         if ( bv.bv_len != 16 ) {
5033                                 Debug( LDAP_DEBUG_TRACE,
5034                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
5035                                         (unsigned long)bv.bv_len, 0, 0 );
5036                                 goto decoding_error;
5037                         }
5038
5039                         rc = lutil_uuidstr_from_normalized(
5040                                 bv.bv_val, bv.bv_len,
5041                                 uuidbuf, sizeof( uuidbuf ) );
5042                         if ( rc == -1 ) {
5043                                 goto decoding_error;
5044                         }
5045                         ber_str2bv( uuidbuf, rc, 1, uuid );
5046                         rc = LDAP_SUCCESS;
5047
5048                 } else {
5049                         tag = ber_skip_tag( ber, &len );
5050                         if ( tag == LBER_DEFAULT ) {
5051                                 goto decoding_error;
5052                         }
5053
5054                         if ( len != 16 ) {
5055                                 Debug( LDAP_DEBUG_TRACE,
5056                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
5057                                         (unsigned long)len, 0, 0 );
5058                                 goto decoding_error;
5059                         }
5060                 }
5061
5062                 tag = ber_peek_tag( ber, &len );
5063         }
5064
5065         if ( tag != LBER_DEFAULT || len != 0 ) {
5066 decoding_error:;
5067                 Debug( LDAP_DEBUG_TRACE,
5068                         "pcache_parse_query_delete: decoding error\n",
5069                         0, 0, 0 );
5070                 rc = LDAP_PROTOCOL_ERROR;
5071                 *text = "queryDelete data decoding error";
5072
5073 done:;
5074                 if ( ndn && !BER_BVISNULL( ndn ) ) {
5075                         slap_sl_free( ndn->bv_val, ctx );
5076                         BER_BVZERO( ndn );
5077                 }
5078
5079                 if ( uuid && !BER_BVISNULL( uuid ) ) {
5080                         slap_sl_free( uuid->bv_val, ctx );
5081                         BER_BVZERO( uuid );
5082                 }
5083         }
5084
5085         if ( !BER_BVISNULL( &reqdata ) ) {
5086                 ber_memfree_x( reqdata.bv_val, ctx );
5087         }
5088
5089         return rc;
5090 }
5091
5092 static int
5093 pcache_exop_query_delete(
5094         Operation       *op,
5095         SlapReply       *rs )
5096 {
5097         BackendDB       *bd = op->o_bd;
5098
5099         struct berval   uuid = BER_BVNULL,
5100                         *uuidp = NULL;
5101         char            buf[ SLAP_TEXT_BUFLEN ];
5102         unsigned        len;
5103         ber_tag_t       tag = LBER_DEFAULT;
5104
5105         if ( LogTest( LDAP_DEBUG_STATS ) ) {
5106                 uuidp = &uuid;
5107         }
5108
5109         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5110                 &tag, &op->o_req_ndn, uuidp,
5111                 &rs->sr_text, op->o_tmpmemctx );
5112         if ( rs->sr_err != LDAP_SUCCESS ) {
5113                 return rs->sr_err;
5114         }
5115
5116         if ( LogTest( LDAP_DEBUG_STATS ) ) {
5117                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
5118                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
5119
5120                 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
5121                         snprintf( &buf[ len ], sizeof( buf ) - len, " pcacheQueryId=\"%s\"", uuid.bv_val );
5122                 }
5123
5124                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
5125                         op->o_log_prefix, buf, 0 );
5126         }
5127         op->o_req_dn = op->o_req_ndn;
5128
5129         op->o_bd = select_backend( &op->o_req_ndn, 0 );
5130         if ( op->o_bd == NULL ) {
5131                 send_ldap_error( op, rs, LDAP_NO_SUCH_OBJECT,
5132                         "no global superior knowledge" );
5133         }
5134         rs->sr_err = backend_check_restrictions( op, rs,
5135                 (struct berval *)&pcache_exop_QUERY_DELETE );
5136         if ( rs->sr_err != LDAP_SUCCESS ) {
5137                 goto done;
5138         }
5139
5140         if ( op->o_bd->be_extended == NULL ) {
5141                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
5142                         "backend does not support extended operations" );
5143                 goto done;
5144         }
5145
5146         op->o_bd->be_extended( op, rs );
5147
5148 done:;
5149         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
5150                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
5151                 BER_BVZERO( &op->o_req_ndn );
5152                 BER_BVZERO( &op->o_req_dn );
5153         }
5154
5155         if ( !BER_BVISNULL( &uuid ) ) {
5156                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5157         }
5158
5159         op->o_bd = bd;
5160
5161         return rs->sr_err;
5162 }
5163 #endif /* PCACHE_EXOP_QUERY_DELETE */
5164
5165 static int
5166 pcache_op_extended( Operation *op, SlapReply *rs )
5167 {
5168         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
5169         cache_manager   *cm = on->on_bi.bi_private;
5170
5171 #ifdef PCACHE_CONTROL_PRIVDB
5172         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
5173                 return pcache_op_privdb( op, rs );
5174         }
5175 #endif /* PCACHE_CONTROL_PRIVDB */
5176
5177 #ifdef PCACHE_EXOP_QUERY_DELETE
5178         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
5179                 struct berval   uuid = BER_BVNULL;
5180                 ber_tag_t       tag = LBER_DEFAULT;
5181
5182                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5183                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
5184                 assert( rs->sr_err == LDAP_SUCCESS );
5185
5186                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
5187                         /* remove all queries related to the selected entry */
5188                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
5189                                 cm, &op->o_req_ndn, &uuid );
5190
5191                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
5192                         if ( !BER_BVISNULL( &uuid ) ) {
5193                                 /* remove the selected query */
5194                                 rs->sr_err = pcache_remove_query_from_cache( op,
5195                                         cm, &uuid );
5196
5197                         } else {
5198                                 /* TODO: remove all queries */
5199                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
5200                                 rs->sr_text = "deletion of all queries not implemented";
5201                         }
5202                 }
5203
5204                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5205                 return rs->sr_err;
5206         }
5207 #endif /* PCACHE_EXOP_QUERY_DELETE */
5208
5209         /* We only care if we're configured for Bind caching */
5210         if ( bvmatch( &op->ore_reqoid, &pcache_exop_MODIFY_PASSWD ) &&
5211                 cm->cache_binds ) {
5212                 /* See if the local entry exists and has a password.
5213                  * It's too much work to find the matching query, so
5214                  * we just see if there's a hashed password to update.
5215                  */
5216                 Operation op2 = *op;
5217                 Entry *e = NULL;
5218                 int rc;
5219                 int doit = 0;
5220
5221                 op2.o_bd = &cm->db;
5222                 op2.o_dn = op->o_bd->be_rootdn;
5223                 op2.o_ndn = op->o_bd->be_rootndn;
5224                 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL,
5225                         slap_schema.si_ad_userPassword, 0, &e );
5226                 if ( rc == LDAP_SUCCESS && e ) {
5227                         /* See if a recognized password is hashed here */
5228                         Attribute *a = attr_find( e->e_attrs,
5229                                 slap_schema.si_ad_userPassword );
5230                         if ( a && a->a_vals[0].bv_val[0] == '{' &&
5231                                 lutil_passwd_scheme( a->a_vals[0].bv_val )) {
5232                                 doit = 1;
5233                         }
5234                         be_entry_release_r( &op2, e );
5235                 }
5236
5237                 if ( doit ) {
5238                         rc = overlay_op_walk( op, rs, op_extended, on->on_info,
5239                                 on->on_next );
5240                         if ( rc == LDAP_SUCCESS ) {
5241                                 req_pwdexop_s *qpw = &op->oq_pwdexop;
5242
5243                                 /* We don't care if it succeeds or not */
5244                                 pc_setpw( &op2, &qpw->rs_new, cm );
5245                         }
5246                         return rc;
5247                 }
5248         }
5249         return SLAP_CB_CONTINUE;
5250 }
5251
5252 static int
5253 pcache_entry_release( Operation  *op, Entry *e, int rw )
5254 {
5255         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
5256         cache_manager   *cm = on->on_bi.bi_private;
5257         BackendDB *db = op->o_bd;
5258         int rc;
5259
5260         op->o_bd = &cm->db;
5261         rc = be_entry_release_rw( op, e, rw );
5262         op->o_bd = db;
5263         return rc;
5264 }
5265
5266 #ifdef PCACHE_MONITOR
5267
5268 static int
5269 pcache_monitor_update(
5270         Operation       *op,
5271         SlapReply       *rs,
5272         Entry           *e,
5273         void            *priv )
5274 {
5275         cache_manager   *cm = (cache_manager *) priv;
5276         query_manager   *qm = cm->qm;
5277
5278         CachedQuery     *qc;
5279         BerVarray       vals = NULL;
5280
5281         attr_delete( &e->e_attrs, ad_cachedQueryURL );
5282         if ( ( SLAP_OPATTRS( rs->sr_attr_flags ) || ad_inlist( ad_cachedQueryURL, rs->sr_attrs ) )
5283                 && qm->templates != NULL )
5284         {
5285                 QueryTemplate *tm;
5286
5287                 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
5288                         for ( qc = tm->query; qc; qc = qc->next ) {
5289                                 struct berval   bv;
5290
5291                                 if ( query2url( op, qc, &bv, 1 ) == 0 ) {
5292                                         ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
5293                                 }
5294                         }
5295                 }
5296
5297
5298                 if ( vals != NULL ) {
5299                         attr_merge_normalize( e, ad_cachedQueryURL, vals, NULL );
5300                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
5301                 }
5302         }
5303
5304         {
5305                 Attribute       *a;
5306                 char            buf[ SLAP_TEXT_BUFLEN ];
5307                 struct berval   bv;
5308
5309                 /* number of cached queries */
5310                 a = attr_find( e->e_attrs, ad_numQueries );
5311                 assert( a != NULL );
5312
5313                 bv.bv_val = buf;
5314                 bv.bv_len = snprintf( buf, sizeof( buf ), "%lu", cm->num_cached_queries );
5315
5316                 if ( a->a_nvals != a->a_vals ) {
5317                         ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5318                 }
5319                 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5320
5321                 /* number of cached entries */
5322                 a = attr_find( e->e_attrs, ad_numEntries );
5323                 assert( a != NULL );
5324
5325                 bv.bv_val = buf;
5326                 bv.bv_len = snprintf( buf, sizeof( buf ), "%d", cm->cur_entries );
5327
5328                 if ( a->a_nvals != a->a_vals ) {
5329                         ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5330                 }
5331                 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5332         }
5333
5334         return SLAP_CB_CONTINUE;
5335 }
5336
5337 static int
5338 pcache_monitor_free(
5339         Entry           *e,
5340         void            **priv )
5341 {
5342         struct berval   values[ 2 ];
5343         Modification    mod = { 0 };
5344
5345         const char      *text;
5346         char            textbuf[ SLAP_TEXT_BUFLEN ];
5347
5348         int             rc;
5349
5350         /* NOTE: if slap_shutdown != 0, priv might have already been freed */
5351         *priv = NULL;
5352
5353         /* Remove objectClass */
5354         mod.sm_op = LDAP_MOD_DELETE;
5355         mod.sm_desc = slap_schema.si_ad_objectClass;
5356         mod.sm_values = values;
5357         mod.sm_numvals = 1;
5358         values[ 0 ] = oc_olmPCache->soc_cname;
5359         BER_BVZERO( &values[ 1 ] );
5360
5361         rc = modify_delete_values( e, &mod, 1, &text,
5362                 textbuf, sizeof( textbuf ) );
5363         /* don't care too much about return code... */
5364
5365         /* remove attrs */
5366         mod.sm_values = NULL;
5367         mod.sm_desc = ad_cachedQueryURL;
5368         mod.sm_numvals = 0;
5369         rc = modify_delete_values( e, &mod, 1, &text,
5370                 textbuf, sizeof( textbuf ) );
5371         /* don't care too much about return code... */
5372
5373         /* remove attrs */
5374         mod.sm_values = NULL;
5375         mod.sm_desc = ad_numQueries;
5376         mod.sm_numvals = 0;
5377         rc = modify_delete_values( e, &mod, 1, &text,
5378                 textbuf, sizeof( textbuf ) );
5379         /* don't care too much about return code... */
5380
5381         /* remove attrs */
5382         mod.sm_values = NULL;
5383         mod.sm_desc = ad_numEntries;
5384         mod.sm_numvals = 0;
5385         rc = modify_delete_values( e, &mod, 1, &text,
5386                 textbuf, sizeof( textbuf ) );
5387         /* don't care too much about return code... */
5388
5389         return SLAP_CB_CONTINUE;
5390 }
5391
5392 /*
5393  * call from within pcache_initialize()
5394  */
5395 static int
5396 pcache_monitor_initialize( void )
5397 {
5398         static int      pcache_monitor_initialized = 0;
5399
5400         if ( backend_info( "monitor" ) == NULL ) {
5401                 return -1;
5402         }
5403
5404         if ( pcache_monitor_initialized++ ) {
5405                 return 0;
5406         }
5407
5408         return 0;
5409 }
5410
5411 static int
5412 pcache_monitor_db_init( BackendDB *be )
5413 {
5414         if ( pcache_monitor_initialize() == LDAP_SUCCESS ) {
5415                 SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_MONITORING;
5416         }
5417
5418         return 0;
5419 }
5420
5421 static int
5422 pcache_monitor_db_open( BackendDB *be )
5423 {
5424         slap_overinst           *on = (slap_overinst *)be->bd_info;
5425         cache_manager           *cm = on->on_bi.bi_private;
5426         Attribute               *a, *next;
5427         monitor_callback_t      *cb = NULL;
5428         int                     rc = 0;
5429         BackendInfo             *mi;
5430         monitor_extra_t         *mbe;
5431         struct berval           dummy = BER_BVC( "" );
5432
5433         if ( !SLAP_DBMONITORING( be ) ) {
5434                 return 0;
5435         }
5436
5437         mi = backend_info( "monitor" );
5438         if ( !mi || !mi->bi_extra ) {
5439                 SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
5440                 return 0;
5441         }
5442         mbe = mi->bi_extra;
5443
5444         /* don't bother if monitor is not configured */
5445         if ( !mbe->is_configured() ) {
5446                 static int warning = 0;
5447
5448                 if ( warning++ == 0 ) {
5449                         Debug( LDAP_DEBUG_ANY, "pcache_monitor_db_open: "
5450                                 "monitoring disabled; "
5451                                 "configure monitor database to enable\n",
5452                                 0, 0, 0 );
5453                 }
5454
5455                 return 0;
5456         }
5457
5458         /* alloc as many as required (plus 1 for objectClass) */
5459         a = attrs_alloc( 1 + 2 );
5460         if ( a == NULL ) {
5461                 rc = 1;
5462                 goto cleanup;
5463         }
5464
5465         a->a_desc = slap_schema.si_ad_objectClass;
5466         attr_valadd( a, &oc_olmPCache->soc_cname, NULL, 1 );
5467         next = a->a_next;
5468
5469         {
5470                 struct berval   bv = BER_BVC( "0" );
5471
5472                 next->a_desc = ad_numQueries;
5473                 attr_valadd( next, &bv, NULL, 1 );
5474                 next = next->a_next;
5475
5476                 next->a_desc = ad_numEntries;
5477                 attr_valadd( next, &bv, NULL, 1 );
5478                 next = next->a_next;
5479         }
5480
5481         cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
5482         cb->mc_update = pcache_monitor_update;
5483         cb->mc_free = pcache_monitor_free;
5484         cb->mc_private = (void *)cm;
5485
5486         /* make sure the database is registered; then add monitor attributes */
5487         BER_BVZERO( &cm->monitor_ndn );
5488         rc = mbe->register_overlay( be, on, &cm->monitor_ndn );
5489         if ( rc == 0 ) {
5490                 rc = mbe->register_entry_attrs( &cm->monitor_ndn, a, cb,
5491                         &dummy, -1, &dummy);
5492         }
5493
5494 cleanup:;
5495         if ( rc != 0 ) {
5496                 if ( cb != NULL ) {
5497                         ch_free( cb );
5498                         cb = NULL;
5499                 }
5500
5501                 if ( a != NULL ) {
5502                         attrs_free( a );
5503                         a = NULL;
5504                 }
5505         }
5506
5507         /* store for cleanup */
5508         cm->monitor_cb = (void *)cb;
5509
5510         /* we don't need to keep track of the attributes, because
5511          * bdb_monitor_free() takes care of everything */
5512         if ( a != NULL ) {
5513                 attrs_free( a );
5514         }
5515
5516         return rc;
5517 }
5518
5519 static int
5520 pcache_monitor_db_close( BackendDB *be )
5521 {
5522         slap_overinst *on = (slap_overinst *)be->bd_info;
5523         cache_manager *cm = on->on_bi.bi_private;
5524
5525         if ( cm->monitor_cb != NULL ) {
5526                 BackendInfo             *mi = backend_info( "monitor" );
5527                 monitor_extra_t         *mbe;
5528
5529                 if ( mi && &mi->bi_extra ) {
5530                         mbe = mi->bi_extra;
5531                         mbe->unregister_entry_callback( NULL,
5532                                 (monitor_callback_t *)cm->monitor_cb,
5533                                 NULL, 0, NULL );
5534                 }
5535         }
5536
5537         return 0;
5538 }
5539
5540 static int
5541 pcache_monitor_db_destroy( BackendDB *be )
5542 {
5543         return 0;
5544 }
5545
5546 #endif /* PCACHE_MONITOR */
5547
5548 static slap_overinst pcache;
5549
5550 static char *obsolete_names[] = {
5551         "proxycache",
5552         NULL
5553 };
5554
5555 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5556 static
5557 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
5558 int
5559 pcache_initialize()
5560 {
5561         int i, code;
5562         struct berval debugbv = BER_BVC("pcache");
5563         ConfigArgs c;
5564         char *argv[ 4 ];
5565
5566         code = slap_loglevel_get( &debugbv, &pcache_debug );
5567         if ( code ) {
5568                 return code;
5569         }
5570
5571 #ifdef PCACHE_CONTROL_PRIVDB
5572         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
5573                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
5574                 parse_privdb_ctrl, &privDB_cid );
5575         if ( code != LDAP_SUCCESS ) {
5576                 Debug( LDAP_DEBUG_ANY,
5577                         "pcache_initialize: failed to register control %s (%d)\n",
5578                         PCACHE_CONTROL_PRIVDB, code, 0 );
5579                 return code;
5580         }
5581 #endif /* PCACHE_CONTROL_PRIVDB */
5582
5583 #ifdef PCACHE_EXOP_QUERY_DELETE
5584         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
5585                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
5586                 0 );
5587         if ( code != LDAP_SUCCESS ) {
5588                 Debug( LDAP_DEBUG_ANY,
5589                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
5590                         code, 0, 0 );
5591                 return code;
5592         }
5593 #endif /* PCACHE_EXOP_QUERY_DELETE */
5594
5595         argv[ 0 ] = "back-bdb/back-hdb monitor";
5596         c.argv = argv;
5597         c.argc = 3;
5598         c.fname = argv[0];
5599
5600         for ( i = 0; s_oid[ i ].name; i++ ) {
5601                 c.lineno = i;
5602                 argv[ 1 ] = s_oid[ i ].name;
5603                 argv[ 2 ] = s_oid[ i ].oid;
5604
5605                 if ( parse_oidm( &c, 0, NULL ) != 0 ) {
5606                         Debug( LDAP_DEBUG_ANY, "pcache_initialize: "
5607                                 "unable to add objectIdentifier \"%s=%s\"\n",
5608                                 s_oid[ i ].name, s_oid[ i ].oid, 0 );
5609                         return 1;
5610                 }
5611         }
5612
5613         for ( i = 0; s_ad[i].desc != NULL; i++ ) {
5614                 code = register_at( s_ad[i].desc, s_ad[i].adp, 0 );
5615                 if ( code ) {
5616                         Debug( LDAP_DEBUG_ANY,
5617                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
5618                         return code;
5619                 }
5620                 (*s_ad[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
5621         }
5622
5623         for ( i = 0; s_oc[i].desc != NULL; i++ ) {
5624                 code = register_oc( s_oc[i].desc, s_oc[i].ocp, 0 );
5625                 if ( code ) {
5626                         Debug( LDAP_DEBUG_ANY,
5627                                 "pcache_initialize: register_oc #%d failed\n", i, 0, 0 );
5628                         return code;
5629                 }
5630                 (*s_oc[i].ocp)->soc_flags |= SLAP_OC_HIDE;
5631         }
5632
5633         pcache.on_bi.bi_type = "pcache";
5634         pcache.on_bi.bi_obsolete_names = obsolete_names;
5635         pcache.on_bi.bi_db_init = pcache_db_init;
5636         pcache.on_bi.bi_db_config = pcache_db_config;
5637         pcache.on_bi.bi_db_open = pcache_db_open;
5638         pcache.on_bi.bi_db_close = pcache_db_close;
5639         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
5640
5641         pcache.on_bi.bi_op_search = pcache_op_search;
5642         pcache.on_bi.bi_op_bind = pcache_op_bind;
5643 #ifdef PCACHE_CONTROL_PRIVDB
5644         pcache.on_bi.bi_op_compare = pcache_op_privdb;
5645         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
5646         pcache.on_bi.bi_op_modify = pcache_op_privdb;
5647         pcache.on_bi.bi_op_add = pcache_op_privdb;
5648         pcache.on_bi.bi_op_delete = pcache_op_privdb;
5649 #endif /* PCACHE_CONTROL_PRIVDB */
5650         pcache.on_bi.bi_extended = pcache_op_extended;
5651
5652         pcache.on_bi.bi_entry_release_rw = pcache_entry_release;
5653         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
5654
5655         pcache.on_bi.bi_cf_ocs = pcocs;
5656
5657         code = config_register_schema( pccfg, pcocs );
5658         if ( code ) return code;
5659
5660         return overlay_register( &pcache );
5661 }
5662
5663 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5664 int init_module(int argc, char *argv[]) {
5665         return pcache_initialize();
5666 }
5667 #endif
5668
5669 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */