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