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