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