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