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