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