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