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