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