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