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