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