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