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