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