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