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