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