]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
Additional fix for ITS#4991. _cleanup callback was always executed when
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003-2007 The OpenLDAP Foundation.
5  * Portions Copyright 2003 IBM Corporation.
6  * Portions Copyright 2003 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 "config.h"
37
38 #ifdef LDAP_DEVEL
39 /*
40  * Control that allows to access the private DB
41  * instead of the public one
42  */
43 #define PCACHE_CONTROL_PRIVDB           "1.3.6.1.4.1.4203.666.11.9.5.1"
44
45 /*
46  * Extended Operation that allows to remove a query from the cache
47  */
48 #define PCACHE_EXOP_QUERY_DELETE        "1.3.6.1.4.1.4203.666.11.9.6.1"
49 #endif
50
51 /* query cache structs */
52 /* query */
53
54 typedef struct Query_s {
55         Filter*         filter;         /* Search Filter */
56         struct berval   base;           /* Search Base */
57         int             scope;          /* Search scope */
58 } Query;
59
60 struct query_template_s;
61
62 typedef struct Qbase_s {
63         Avlnode *scopes[4];             /* threaded AVL trees of cached queries */
64         struct berval base;
65         int queries;
66 } Qbase;
67
68 /* struct representing a cached query */
69 typedef struct cached_query_s {
70         Filter                                  *filter;
71         Filter                                  *first;
72         Qbase                                   *qbase;
73         int                                             scope;
74         struct berval                   q_uuid;         /* query identifier */
75         struct query_template_s         *qtemp; /* template of the query */
76         time_t                          expiry_time;    /* time till the query is considered valid */
77         struct cached_query_s           *next;          /* next query in the template */
78         struct cached_query_s           *prev;          /* previous query in the template */
79         struct cached_query_s           *lru_up;        /* previous query in the LRU list */
80         struct cached_query_s           *lru_down;      /* next query in the LRU list */
81 } CachedQuery;
82
83 /*
84  * URL representation:
85  *
86  * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
87  *
88  * <base> ::= CachedQuery.qbase->base
89  * <scope> ::= CachedQuery.scope
90  * <filter> ::= filter2bv(CachedQuery.filter)
91  * <uuid> ::= CachedQuery.q_uuid
92  * <attrset> ::= CachedQuery.qtemp->attr_set_index
93  * <expiry> ::= CachedQuery.expiry_time
94  *
95  * quick hack: parse URI, call add_query() and then fix
96  * CachedQuery.expiry_time and CachedQuery.q_uuid
97  */
98
99 /*
100  * Represents a set of projected attributes.
101  */
102
103 struct attr_set {
104         struct query_template_s *templates;
105         AttributeName*  attrs;          /* specifies the set */
106         unsigned        flags;
107 #define PC_CONFIGURED   (0x1)
108 #define PC_REFERENCED   (0x2)
109 #define PC_GOT_OC               (0x4)
110         int             count;          /* number of attributes */
111 };
112
113 /* struct representing a query template
114  * e.g. template string = &(cn=)(mail=)
115  */
116 typedef struct query_template_s {
117         struct query_template_s *qtnext;
118         struct query_template_s *qmnext;
119
120         Avlnode*                qbase;
121         CachedQuery*    query;          /* most recent query cached for the template */
122         CachedQuery*    query_last;     /* oldest query cached for the template */
123         ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
124         struct berval   querystr;       /* Filter string corresponding to the QT */
125
126         int             attr_set_index; /* determines the projected attributes */
127         int             no_of_queries;  /* Total number of queries in the template */
128         time_t          ttl;            /* TTL for the queries of this template */
129         time_t          negttl;         /* TTL for negative results */
130         struct attr_set t_attrs;        /* filter attrs + attr_set */
131 } QueryTemplate;
132
133 struct query_manager_s;
134
135 /* prototypes for functions for 1) query containment
136  * 2) query addition, 3) cache replacement
137  */
138 typedef CachedQuery *   (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
139 typedef CachedQuery *   (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
140 typedef void    (CRfunc)(struct query_manager_s*, struct berval * );
141
142 /* LDAP query cache */
143 typedef struct query_manager_s {
144         struct attr_set*        attr_sets;              /* possible sets of projected attributes */
145         QueryTemplate*          templates;              /* cacheable templates */
146
147         CachedQuery*            lru_top;                /* top and bottom of LRU list */
148         CachedQuery*            lru_bottom;
149
150         ldap_pvt_thread_mutex_t         lru_mutex;      /* mutex for accessing LRU list */
151
152         /* Query cache methods */
153         QCfunc                  *qcfunc;                        /* Query containment*/
154         CRfunc                  *crfunc;                        /* cache replacement */
155         AddQueryfunc    *addfunc;                       /* add query */
156 } query_manager;
157
158 /* LDAP query cache manager */
159 typedef struct cache_manager_s {
160         BackendDB       db;     /* underlying database */
161         unsigned long   num_cached_queries;             /* total number of cached queries */
162         unsigned long   max_queries;                    /* upper bound on # of cached queries */
163         int             save_queries;                   /* save cached queries across restarts */
164         int     numattrsets;                    /* number of attribute sets */
165         int     cur_entries;                    /* current number of entries cached */
166         int     max_entries;                    /* max number of entries cached */
167         int     num_entries_limit;              /* max # of entries in a cacheable query */
168
169         char    response_cb;                    /* install the response callback
170                                                  * at the tail of the callback list */
171 #define PCACHE_RESPONSE_CB_HEAD 0
172 #define PCACHE_RESPONSE_CB_TAIL 1
173
174         time_t  cc_period;              /* interval between successive consistency checks (sec) */
175         int     cc_paused;
176         void    *cc_arg;
177
178         ldap_pvt_thread_mutex_t         cache_mutex;
179
180         query_manager*   qm;    /* query cache managed by the cache manager */
181 } cache_manager;
182
183 static int pcache_debug;
184
185 #ifdef PCACHE_CONTROL_PRIVDB
186 static int privDB_cid;
187 #endif /* PCACHE_CONTROL_PRIVDB */
188
189 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
190 static struct {
191         char    *desc;
192         AttributeDescription **adp;
193 } as[] = {
194         { "( 1.3.6.1.4.1.4203.666.11.9.1.1 "
195                 "NAME 'queryId' "
196                 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
197                 "EQUALITY octetStringMatch "
198                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
199                 "NO-USER-MODIFICATION "
200                 "USAGE directoryOperation )",
201                 &ad_queryId },
202         { "( 1.3.6.1.4.1.4203.666.11.9.1.2 "
203                 "NAME 'cachedQueryURL' "
204                 "DESC 'URI describing a cached query' "
205                 "EQUALITY caseExactMatch "
206                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
207                 "NO-USER-MODIFICATION "
208                 "USAGE directoryOperation )",
209                 &ad_cachedQueryURL },
210         { NULL }
211 };
212
213 static int
214 filter2template(
215         Operation               *op,
216         Filter                  *f,
217         struct                  berval *fstr,
218         AttributeName**         filter_attrs,
219         int*                    filter_cnt,
220         int*                    filter_got_oc );
221
222 static CachedQuery *
223 add_query(
224         Operation *op,
225         query_manager* qm,
226         Query* query,
227         QueryTemplate *templ,
228         int positive);
229
230 static int
231 remove_query_data(
232         Operation       *op,
233         SlapReply       *rs,
234         struct berval   *query_uuid );
235
236 /*
237  * Turn a cached query into its URL representation
238  */
239 static int
240 query2url( Operation *op, CachedQuery *q, struct berval *urlbv )
241 {
242         struct berval   bv_scope,
243                         bv_filter;
244         char            attrset_buf[ 32 ],
245                         expiry_buf[ 32 ],
246                         *ptr;
247         ber_len_t       attrset_len,
248                         expiry_len;
249
250         ldap_pvt_scope2bv( q->scope, &bv_scope );
251         filter2bv_x( op, q->filter, &bv_filter );
252         attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
253                 "%lu", (unsigned long)q->qtemp->attr_set_index );
254         expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
255                 "%lu", (unsigned long)q->expiry_time );
256
257         urlbv->bv_len = STRLENOF( "ldap:///" )
258                 + q->qbase->base.bv_len
259                 + STRLENOF( "??" )
260                 + bv_scope.bv_len
261                 + STRLENOF( "?" )
262                 + bv_filter.bv_len
263                 + STRLENOF( "?x-uuid=" )
264                 + q->q_uuid.bv_len
265                 + STRLENOF( ",x-attrset=" )
266                 + attrset_len
267                 + STRLENOF( ",x-expiry=" )
268                 + expiry_len;
269         ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
270         ptr = lutil_strcopy( ptr, "ldap:///" );
271         ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
272         ptr = lutil_strcopy( ptr, "??" );
273         ptr = lutil_strcopy( ptr, bv_scope.bv_val );
274         ptr = lutil_strcopy( ptr, "?" );
275         ptr = lutil_strcopy( ptr, bv_filter.bv_val );
276         ptr = lutil_strcopy( ptr, "?x-uuid=" );
277         ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
278         ptr = lutil_strcopy( ptr, ",x-attrset=" );
279         ptr = lutil_strcopy( ptr, attrset_buf );
280         ptr = lutil_strcopy( ptr, ",x-expiry=" );
281         ptr = lutil_strcopy( ptr, expiry_buf );
282
283         ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
284
285         return 0;
286 }
287
288 /*
289  * Turn an URL representing a formerly cached query into a cached query,
290  * and try to cache it
291  */
292 static int
293 url2query(
294         char            *url,
295         Operation       *op,
296         query_manager   *qm )
297 {
298         Query           query = { 0 };
299         QueryTemplate   *qt;
300         CachedQuery     *cq;
301         LDAPURLDesc     *lud = NULL;
302         struct berval   base,
303                         tempstr = BER_BVNULL,
304                         uuid;
305         int             attrset;
306         time_t          expiry_time;
307         int             i,
308                         got_uuid = 0,
309                         got_attrset = 0,
310                         got_expiry = 0,
311                         rc = 0;
312
313         rc = ldap_url_parse( url, &lud );
314         if ( rc != LDAP_URL_SUCCESS ) {
315                 return -1;
316         }
317
318         /* non-allowed fields */
319         if ( lud->lud_host != NULL ) {
320                 rc = 1;
321                 goto error;
322         }
323
324         if ( lud->lud_attrs != NULL ) {
325                 rc = 1;
326                 goto error;
327         }
328
329         /* be pedantic */
330         if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
331                 rc = 1;
332                 goto error;
333         }
334
335         /* required fields */
336         if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
337                 rc = 1;
338                 goto error;
339         }
340
341         switch ( lud->lud_scope ) {
342         case LDAP_SCOPE_BASE:
343         case LDAP_SCOPE_ONELEVEL:
344         case LDAP_SCOPE_SUBTREE:
345         case LDAP_SCOPE_SUBORDINATE:
346                 break;
347
348         default:
349                 rc = 1;
350                 goto error;
351         }
352
353         if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
354                 rc = 1;
355                 goto error;
356         }
357
358         if ( lud->lud_exts == NULL ) {
359                 rc = 1;
360                 goto error;
361         }
362
363         for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
364                 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
365                         struct berval   tmpUUID;
366                         Syntax          *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
367
368                         ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
369                         rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
370                         if ( rc != LDAP_SUCCESS ) {
371                                 goto error;
372                         }
373                         got_uuid = 1;
374
375                 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
376                         rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
377                         if ( rc ) {
378                                 goto error;
379                         }
380                         got_attrset = 1;
381
382                 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
383                         unsigned long l;
384
385                         rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
386                         if ( rc ) {
387                                 goto error;
388                         }
389                         expiry_time = (time_t)l;
390                         got_expiry = 1;
391
392                 } else {
393                         rc = -1;
394                         goto error;
395                 }
396         }
397
398         if ( !got_uuid ) {
399                 rc = 1;
400                 goto error;
401         }
402
403         if ( !got_attrset ) {
404                 rc = 1;
405                 goto error;
406         }
407
408         if ( !got_expiry ) {
409                 rc = 1;
410                 goto error;
411         }
412
413         /* ignore expired queries */
414         if ( expiry_time <= slap_get_time()) {
415                 Operation       op2 = *op;
416                 SlapReply       rs2 = { 0 };
417
418                 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
419
420                 (void)remove_query_data( &op2, &rs2, &uuid );
421
422                 rc = 0;
423
424         } else {
425                 ber_str2bv( lud->lud_dn, 0, 0, &base );
426                 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
427                 if ( rc != LDAP_SUCCESS ) {
428                         goto error;
429                 }
430                 query.scope = lud->lud_scope;
431                 query.filter = str2filter( lud->lud_filter );
432
433                 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
434                 tempstr.bv_len = 0;
435                 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
436                         ch_free( tempstr.bv_val );
437                         rc = -1;
438                         goto error;
439                 }
440
441                 /* check for query containment */
442                 qt = qm->attr_sets[attrset].templates;
443                 for ( ; qt; qt = qt->qtnext ) {
444                         /* find if template i can potentially answer tempstr */
445                         if ( bvmatch( &qt->querystr, &tempstr ) ) {
446                                 break;
447                         }
448                 }
449
450                 if ( qt == NULL ) {
451                         rc = 1;
452                         goto error;
453                 }
454
455                 cq = add_query( op, qm, &query, qt, 1 );
456                 if ( cq != NULL ) {
457                         cq->expiry_time = expiry_time;
458                         cq->q_uuid = uuid;
459
460                         /* it's now into cq->filter */
461                         BER_BVZERO( &uuid );
462                         query.filter = NULL;
463
464                 } else {
465                         rc = 1;
466                 }
467         }
468
469 error:;
470         if ( query.filter != NULL ) filter_free( query.filter );
471         if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
472         if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
473         if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
474         if ( lud != NULL ) ldap_free_urldesc( lud );
475
476         return rc;
477 }
478
479 /* Return 1 for an added entry, else 0 */
480 static int
481 merge_entry(
482         Operation               *op,
483         Entry                   *e,
484         struct berval*          query_uuid )
485 {
486         int             rc;
487         Modifications* modlist = NULL;
488         const char*     text = NULL;
489         Attribute               *attr;
490         char                    textbuf[SLAP_TEXT_BUFLEN];
491         size_t                  textlen = sizeof(textbuf);
492
493         SlapReply sreply = {REP_RESULT};
494
495         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
496
497         attr = e->e_attrs;
498         e->e_attrs = NULL;
499
500         /* add queryId attribute */
501         attr_merge_one( e, ad_queryId, query_uuid, NULL );
502
503         /* append the attribute list from the fetched entry */
504         e->e_attrs->a_next = attr;
505
506         op->o_tag = LDAP_REQ_ADD;
507         op->o_protocol = LDAP_VERSION3;
508         op->o_callback = &cb;
509         op->o_time = slap_get_time();
510         op->o_do_not_cache = 1;
511
512         op->ora_e = e;
513         op->o_req_dn = e->e_name;
514         op->o_req_ndn = e->e_nname;
515         rc = op->o_bd->be_add( op, &sreply );
516
517         if ( rc != LDAP_SUCCESS ) {
518                 if ( rc == LDAP_ALREADY_EXISTS ) {
519                         slap_entry2mods( e, &modlist, &text, textbuf, textlen );
520                         modlist->sml_op = LDAP_MOD_ADD;
521                         op->o_tag = LDAP_REQ_MODIFY;
522                         op->orm_modlist = modlist;
523                         op->o_bd->be_modify( op, &sreply );
524                         slap_mods_free( modlist, 1 );
525                 } else if ( rc == LDAP_REFERRAL ||
526                                         rc == LDAP_NO_SUCH_OBJECT ) {
527                         syncrepl_add_glue( op, e );
528                         e = NULL;
529                         rc = 1;
530                 }
531                 if ( e ) {
532                         entry_free( e );
533                         rc = 0;
534                 }
535         } else {
536                 if ( op->ora_e == e )
537                         be_entry_release_w( op, e );
538                 rc = 1;
539         }
540
541         return rc;
542 }
543
544 /* Length-ordered sort on normalized DNs */
545 static int pcache_dn_cmp( const void *v1, const void *v2 )
546 {
547         const Qbase *q1 = v1, *q2 = v2;
548
549         int rc = q1->base.bv_len - q2->base.bv_len;
550         if ( rc == 0 )
551                 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
552         return rc;
553 }
554
555 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
556 {
557         int len, dif;
558         dif = bv1->bv_len - bv2->bv_len;
559         len = bv1->bv_len;
560         if ( dif > 0 ) len -= dif;
561         len = memcmp( bv1->bv_val, bv2->bv_val, len );
562         if ( !len )
563                 len = dif;
564         return len;
565 }
566
567 /* compare the first value in each filter */
568 static int pcache_filter_cmp( const void *v1, const void *v2 )
569 {
570         const CachedQuery *q1 = v1, *q2 =v2;
571         int rc, weight1, weight2;
572
573         switch( q1->first->f_choice ) {
574         case LDAP_FILTER_PRESENT:
575                 weight1 = 0;
576                 break;
577         case LDAP_FILTER_EQUALITY:
578         case LDAP_FILTER_GE:
579         case LDAP_FILTER_LE:
580                 weight1 = 1;
581                 break;
582         default:
583                 weight1 = 2;
584         }
585         switch( q2->first->f_choice ) {
586         case LDAP_FILTER_PRESENT:
587                 weight2 = 0;
588                 break;
589         case LDAP_FILTER_EQUALITY:
590         case LDAP_FILTER_GE:
591         case LDAP_FILTER_LE:
592                 weight2 = 1;
593                 break;
594         default:
595                 weight2 = 2;
596         }
597         rc = weight1 - weight2;
598         if ( !rc ) {
599                 switch( weight1 ) {
600                 case 0: return 0;
601                 case 1:
602                         rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
603                         break;
604                 case 2:
605                         if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
606                                 rc = 0;
607                                 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
608                                         if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
609                                                 rc = lex_bvcmp( &q1->first->f_sub_initial,
610                                                         &q2->first->f_sub_initial );
611                                         } else {
612                                                 rc = 1;
613                                         }
614                                 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
615                                         rc = -1;
616                                 }
617                                 if ( rc ) break;
618                                 if ( q1->first->f_sub_any ) {
619                                         if ( q2->first->f_sub_any ) {
620                                                 rc = lex_bvcmp( q1->first->f_sub_any,
621                                                         q2->first->f_sub_any );
622                                         } else {
623                                                 rc = 1;
624                                         }
625                                 } else if ( q2->first->f_sub_any ) {
626                                         rc = -1;
627                                 }
628                                 if ( rc ) break;
629                                 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
630                                         if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
631                                                 rc = lex_bvcmp( &q1->first->f_sub_final,
632                                                         &q2->first->f_sub_final );
633                                         } else {
634                                                 rc = 1;
635                                         }
636                                 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
637                                         rc = -1;
638                                 }
639                         } else {
640                                 rc = lex_bvcmp( &q1->first->f_mr_value,
641                                         &q2->first->f_mr_value );
642                         }
643                         break;
644                 }
645         }
646
647         return rc;
648 }
649
650 /* add query on top of LRU list */
651 static void
652 add_query_on_top (query_manager* qm, CachedQuery* qc)
653 {
654         CachedQuery* top = qm->lru_top;
655
656         qm->lru_top = qc;
657
658         if (top)
659                 top->lru_up = qc;
660         else
661                 qm->lru_bottom = qc;
662
663         qc->lru_down = top;
664         qc->lru_up = NULL;
665         Debug( pcache_debug, "Base of added query = %s\n",
666                         qc->qbase->base.bv_val, 0, 0 );
667 }
668
669 /* remove_query from LRU list */
670
671 static void
672 remove_query (query_manager* qm, CachedQuery* qc)
673 {
674         CachedQuery* up;
675         CachedQuery* down;
676
677         if (!qc)
678                 return;
679
680         up = qc->lru_up;
681         down = qc->lru_down;
682
683         if (!up)
684                 qm->lru_top = down;
685
686         if (!down)
687                 qm->lru_bottom = up;
688
689         if (down)
690                 down->lru_up = up;
691
692         if (up)
693                 up->lru_down = down;
694
695         qc->lru_up = qc->lru_down = NULL;
696 }
697
698 /* find and remove string2 from string1
699  * from start if position = 1,
700  * from end if position = 3,
701  * from anywhere if position = 2
702  * string1 is overwritten if position = 2.
703  */
704
705 static int
706 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
707 {
708         int ret=0;
709
710         if ( !ber2->bv_val )
711                 return 1;
712         if ( !ber1->bv_val )
713                 return 0;
714
715         switch( position ) {
716         case 1:
717                 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
718                         ber2->bv_val, ber2->bv_len )) {
719                         ret = 1;
720                         ber1->bv_val += ber2->bv_len;
721                         ber1->bv_len -= ber2->bv_len;
722                 }
723                 break;
724         case 2: {
725                 char *temp;
726                 ber1->bv_val[ber1->bv_len] = '\0';
727                 temp = strstr( ber1->bv_val, ber2->bv_val );
728                 if ( temp ) {
729                         strcpy( temp, temp+ber2->bv_len );
730                         ber1->bv_len -= ber2->bv_len;
731                         ret = 1;
732                 }
733                 break;
734                 }
735         case 3:
736                 if ( ber1->bv_len >= ber2->bv_len &&
737                         !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
738                                 ber2->bv_len )) {
739                         ret = 1;
740                         ber1->bv_len -= ber2->bv_len;
741                 }
742                 break;
743         }
744         return ret;
745 }
746
747
748 static struct berval*
749 merge_init_final(Operation *op, struct berval* init, struct berval* any,
750         struct berval* final)
751 {
752         struct berval* merged, *temp;
753         int i, any_count, count;
754
755         for (any_count=0; any && any[any_count].bv_val; any_count++)
756                 ;
757
758         count = any_count;
759
760         if (init->bv_val)
761                 count++;
762         if (final->bv_val)
763                 count++;
764
765         merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
766                 op->o_tmpmemctx );
767         temp = merged;
768
769         if (init->bv_val) {
770                 ber_dupbv_x( temp, init, op->o_tmpmemctx );
771                 temp++;
772         }
773
774         for (i=0; i<any_count; i++) {
775                 ber_dupbv_x( temp, any, op->o_tmpmemctx );
776                 temp++; any++;
777         }
778
779         if (final->bv_val){
780                 ber_dupbv_x( temp, final, op->o_tmpmemctx );
781                 temp++;
782         }
783         BER_BVZERO( temp );
784         return merged;
785 }
786
787 /* Each element in stored must be found in incoming. Incoming is overwritten.
788  */
789 static int
790 strings_containment(struct berval* stored, struct berval* incoming)
791 {
792         struct berval* element;
793         int k=0;
794         int j, rc = 0;
795
796         for ( element=stored; element->bv_val != NULL; element++ ) {
797                 for (j = k; incoming[j].bv_val != NULL; j++) {
798                         if (find_and_remove(&(incoming[j]), element, 2)) {
799                                 k = j;
800                                 rc = 1;
801                                 break;
802                         }
803                         rc = 0;
804                 }
805                 if ( rc ) {
806                         continue;
807                 } else {
808                         return 0;
809                 }
810         }
811         return 1;
812 }
813
814 static int
815 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
816 {
817         int rc = 0;
818
819         struct berval init_incoming;
820         struct berval final_incoming;
821         struct berval *remaining_incoming = NULL;
822
823         if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
824            || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
825                 return 0;
826
827         init_incoming = incoming->f_sub_initial;
828         final_incoming =  incoming->f_sub_final;
829
830         if (find_and_remove(&init_incoming,
831                         &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
832                         &(stored->f_sub_final), 3))
833         {
834                 if (stored->f_sub_any == NULL) {
835                         rc = 1;
836                         goto final;
837                 }
838                 remaining_incoming = merge_init_final(op, &init_incoming,
839                                                 incoming->f_sub_any, &final_incoming);
840                 rc = strings_containment(stored->f_sub_any, remaining_incoming);
841                 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
842         }
843 final:
844         return rc;
845 }
846
847 static int
848 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
849 {
850         struct berval incoming_val[2];
851         int rc = 0;
852
853         incoming_val[1] = incoming->f_av_value;
854
855         if (find_and_remove(incoming_val+1,
856                         &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
857                         &(stored->f_sub_final), 3)) {
858                 if (stored->f_sub_any == NULL){
859                         rc = 1;
860                         goto final;
861                 }
862                 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
863                 BER_BVZERO( incoming_val+1 );
864                 rc = strings_containment(stored->f_sub_any, incoming_val);
865                 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
866         }
867 final:
868         return rc;
869 }
870
871 static Filter *
872 filter_first( Filter *f )
873 {
874         while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
875                 f = f->f_and;
876         return f;
877 }
878
879
880 static CachedQuery *
881 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
882 {
883         Filter* fs;
884         Filter* fi;
885         MatchingRule* mrule = NULL;
886         int res=0, eqpass= 0;
887         int ret, rc, dir;
888         Avlnode *ptr;
889         CachedQuery cq, *qc;
890
891         cq.filter = inputf;
892         cq.first = first;
893
894         /* substring matches sort to the end, and we just have to
895          * walk the entire list.
896          */
897         if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
898                 ptr = tavl_end( root, 1 );
899                 dir = TAVL_DIR_LEFT;
900         } else {
901                 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
902                 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
903                         TAVL_DIR_RIGHT;
904         }
905
906         while (ptr) {
907                 qc = ptr->avl_data;
908                 fi = inputf;
909                 fs = qc->filter;
910
911                 /* an incoming substr query can only be satisfied by a cached
912                  * substr query.
913                  */
914                 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
915                         qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
916                         break;
917
918                 /* an incoming eq query can be satisfied by a cached eq or substr
919                  * query
920                  */
921                 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
922                         if ( eqpass == 0 ) {
923                                 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
924 nextpass:                       eqpass = 1;
925                                         ptr = tavl_end( root, 1 );
926                                         dir = TAVL_DIR_LEFT;
927                                         continue;
928                                 }
929                         } else {
930                                 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
931                                         break;
932                         }
933                 }
934                 do {
935                         res=0;
936                         switch (fs->f_choice) {
937                         case LDAP_FILTER_EQUALITY:
938                                 if (fi->f_choice == LDAP_FILTER_EQUALITY)
939                                         mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
940                                 else
941                                         ret = 1;
942                                 break;
943                         case LDAP_FILTER_GE:
944                         case LDAP_FILTER_LE:
945                                 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
946                                 break;
947                         default:
948                                 mrule = NULL; 
949                         }
950                         if (mrule) {
951                                 const char *text;
952                                 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
953                                         SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
954                                         &(fi->f_ava->aa_value),
955                                         &(fs->f_ava->aa_value), &text);
956                                 if (rc != LDAP_SUCCESS) {
957                                         return NULL;
958                                 }
959                                 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
960                                         goto nextpass;
961                         }
962                         switch (fs->f_choice) {
963                         case LDAP_FILTER_OR:
964                         case LDAP_FILTER_AND:
965                                 fs = fs->f_and;
966                                 fi = fi->f_and;
967                                 res=1;
968                                 break;
969                         case LDAP_FILTER_SUBSTRINGS:
970                                 /* check if the equality query can be
971                                 * answered with cached substring query */
972                                 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
973                                         && substr_containment_equality( op,
974                                         fs, fi))
975                                         res=1;
976                                 /* check if the substring query can be
977                                 * answered with cached substring query */
978                                 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
979                                         ) && substr_containment_substr( op,
980                                         fs, fi))
981                                         res= 1;
982                                 fs=fs->f_next;
983                                 fi=fi->f_next;
984                                 break;
985                         case LDAP_FILTER_PRESENT:
986                                 res=1;
987                                 fs=fs->f_next;
988                                 fi=fi->f_next;
989                                 break;
990                         case LDAP_FILTER_EQUALITY:
991                                 if (ret == 0)
992                                         res = 1;
993                                 fs=fs->f_next;
994                                 fi=fi->f_next;
995                                 break;
996                         case LDAP_FILTER_GE:
997                                 if (mrule && ret >= 0)
998                                         res = 1;
999                                 fs=fs->f_next;
1000                                 fi=fi->f_next;
1001                                 break;
1002                         case LDAP_FILTER_LE:
1003                                 if (mrule && ret <= 0)
1004                                         res = 1;
1005                                 fs=fs->f_next;
1006                                 fi=fi->f_next;
1007                                 break;
1008                         case LDAP_FILTER_NOT:
1009                                 res=0;
1010                                 break;
1011                         default:
1012                                 break;
1013                         }
1014                 } while((res) && (fi != NULL) && (fs != NULL));
1015
1016                 if ( res )
1017                         return qc;
1018                 ptr = tavl_next( ptr, dir );
1019         }
1020         return NULL;
1021 }
1022
1023 /* check whether query is contained in any of
1024  * the cached queries in template
1025  */
1026 static CachedQuery *
1027 query_containment(Operation *op, query_manager *qm,
1028                   Query *query,
1029                   QueryTemplate *templa)
1030 {
1031         CachedQuery* qc;
1032         int depth = 0, tscope;
1033         Qbase qbase, *qbptr = NULL;
1034         struct berval pdn;
1035
1036         if (query->filter != NULL) {
1037                 Filter *first;
1038
1039                 Debug( pcache_debug, "Lock QC index = %p\n",
1040                                 (void *) templa, 0, 0 );
1041                 qbase.base = query->base;
1042
1043                 first = filter_first( query->filter );
1044
1045                 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1046                 for( ;; ) {
1047                         /* Find the base */
1048                         qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1049                         if ( qbptr ) {
1050                                 tscope = query->scope;
1051                                 /* Find a matching scope:
1052                                  * match at depth 0 OK
1053                                  * scope is BASE,
1054                                  *      one at depth 1 OK
1055                                  *  subord at depth > 0 OK
1056                                  *      subtree at any depth OK
1057                                  * scope is ONE,
1058                                  *  subtree or subord at any depth OK
1059                                  * scope is SUBORD,
1060                                  *  subtree or subord at any depth OK
1061                                  * scope is SUBTREE,
1062                                  *  subord at depth > 0 OK
1063                                  *  subtree at any depth OK
1064                                  */
1065                                 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1066                                         switch ( query->scope ) {
1067                                         case LDAP_SCOPE_BASE:
1068                                                 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1069                                                 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1070                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1071                                                 break;
1072                                         case LDAP_SCOPE_ONE:
1073                                                 if ( tscope == LDAP_SCOPE_BASE )
1074                                                         tscope = LDAP_SCOPE_ONE;
1075                                                 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1076                                                 if ( !depth ) break;
1077                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1078                                                         tscope = LDAP_SCOPE_SUBTREE;
1079                                                 break;
1080                                         case LDAP_SCOPE_SUBTREE:
1081                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1082                                                         tscope = LDAP_SCOPE_SUBTREE;
1083                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1084                                                 break;
1085                                         case LDAP_SCOPE_CHILDREN:
1086                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1087                                                         tscope = LDAP_SCOPE_SUBTREE;
1088                                                 break;
1089                                         }
1090                                         if ( !qbptr->scopes[tscope] ) continue;
1091
1092                                         /* Find filter */
1093                                         qc = find_filter( op, qbptr->scopes[tscope],
1094                                                         query->filter, first );
1095                                         if ( qc ) {
1096                                                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1097                                                 if (qm->lru_top != qc) {
1098                                                         remove_query(qm, qc);
1099                                                         add_query_on_top(qm, qc);
1100                                                 }
1101                                                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1102                                                 return qc;
1103                                         }
1104                                 }
1105                         }
1106                         if ( be_issuffix( op->o_bd, &qbase.base ))
1107                                 break;
1108                         /* Up a level */
1109                         dnParent( &qbase.base, &pdn );
1110                         qbase.base = pdn;
1111                         depth++;
1112                 }
1113
1114                 Debug( pcache_debug,
1115                         "Not answerable: Unlock QC index=%p\n",
1116                         (void *) templa, 0, 0 );
1117                 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1118         }
1119         return NULL;
1120 }
1121
1122 static void
1123 free_query (CachedQuery* qc)
1124 {
1125         free(qc->q_uuid.bv_val);
1126         filter_free(qc->filter);
1127         free(qc);
1128 }
1129
1130
1131 /* Add query to query cache */
1132 static CachedQuery *
1133 add_query(
1134         Operation *op,
1135         query_manager* qm,
1136         Query* query,
1137         QueryTemplate *templ,
1138         int positive)
1139 {
1140         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1141         Qbase *qbase, qb;
1142         Filter *first;
1143         int rc;
1144
1145         new_cached_query->qtemp = templ;
1146         BER_BVZERO( &new_cached_query->q_uuid );
1147         if ( positive ) {
1148                 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1149         } else {
1150                 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1151         }
1152         new_cached_query->lru_up = NULL;
1153         new_cached_query->lru_down = NULL;
1154         Debug( pcache_debug, "Added query expires at %ld\n",
1155                         (long) new_cached_query->expiry_time, 0, 0 );
1156
1157         new_cached_query->scope = query->scope;
1158         new_cached_query->filter = query->filter;
1159         new_cached_query->first = first = filter_first( query->filter );
1160
1161         qb.base = query->base;
1162
1163         /* Adding a query    */
1164         Debug( pcache_debug, "Lock AQ index = %p\n",
1165                         (void *) templ, 0, 0 );
1166         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1167         qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1168         if ( !qbase ) {
1169                 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1170                 qbase->base.bv_len = qb.base.bv_len;
1171                 qbase->base.bv_val = (char *)(qbase+1);
1172                 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1173                 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1174                 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1175         }
1176         new_cached_query->next = templ->query;
1177         new_cached_query->prev = NULL;
1178         new_cached_query->qbase = qbase;
1179         rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1180                 pcache_filter_cmp, avl_dup_error );
1181         if ( rc == 0 ) {
1182                 qbase->queries++;
1183                 if (templ->query == NULL)
1184                         templ->query_last = new_cached_query;
1185                 else
1186                         templ->query->prev = new_cached_query;
1187                 templ->query = new_cached_query;
1188                 templ->no_of_queries++;
1189         } else {
1190                 ch_free( new_cached_query );
1191                 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1192                                                         query->filter, first );
1193                 filter_free( query->filter );
1194         }
1195         Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1196                         (void *) templ, templ->no_of_queries, 0 );
1197
1198         Debug( pcache_debug, "Unlock AQ index = %p \n",
1199                         (void *) templ, 0, 0 );
1200         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1201
1202         /* Adding on top of LRU list  */
1203         if ( rc == 0 ) {
1204                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1205                 add_query_on_top(qm, new_cached_query);
1206                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1207         }
1208         return rc == 0 ? new_cached_query : NULL;
1209 }
1210
1211 static void
1212 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1213 {
1214         if (!qc->prev && !qc->next) {
1215                 template->query_last = template->query = NULL;
1216         } else if (qc->prev == NULL) {
1217                 qc->next->prev = NULL;
1218                 template->query = qc->next;
1219         } else if (qc->next == NULL) {
1220                 qc->prev->next = NULL;
1221                 template->query_last = qc->prev;
1222         } else {
1223                 qc->next->prev = qc->prev;
1224                 qc->prev->next = qc->next;
1225         }
1226         tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1227         qc->qbase->queries--;
1228         if ( qc->qbase->queries == 0 ) {
1229                 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1230                 ch_free( qc->qbase );
1231                 qc->qbase = NULL;
1232         }
1233
1234         template->no_of_queries--;
1235 }
1236
1237 /* remove bottom query of LRU list from the query cache */
1238 /*
1239  * NOTE: slight change in functionality.
1240  *
1241  * - if result->bv_val is NULL, the query at the bottom of the LRU
1242  *   is removed
1243  * - otherwise, the query whose UUID is *result is removed
1244  *      - if not found, result->bv_val is zeroed
1245  */
1246 static void
1247 cache_replacement(query_manager* qm, struct berval *result)
1248 {
1249         CachedQuery* bottom;
1250         QueryTemplate *temp;
1251
1252         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1253         if ( BER_BVISNULL( result ) ) {
1254                 bottom = qm->lru_bottom;
1255
1256                 if (!bottom) {
1257                         Debug ( pcache_debug,
1258                                 "Cache replacement invoked without "
1259                                 "any query in LRU list\n", 0, 0, 0 );
1260                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1261                         return;
1262                 }
1263
1264         } else {
1265                 for ( bottom = qm->lru_bottom;
1266                         bottom != NULL;
1267                         bottom = bottom->lru_up )
1268                 {
1269                         if ( bvmatch( result, &bottom->q_uuid ) ) {
1270                                 break;
1271                         }
1272                 }
1273
1274                 if ( !bottom ) {
1275                         Debug ( pcache_debug,
1276                                 "Could not find query with uuid=\"%s\""
1277                                 "in LRU list\n", result->bv_val, 0, 0 );
1278                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1279                         BER_BVZERO( result );
1280                         return;
1281                 }
1282         }
1283
1284         temp = bottom->qtemp;
1285         remove_query(qm, bottom);
1286         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1287
1288         *result = bottom->q_uuid;
1289         bottom->q_uuid.bv_val = NULL;
1290
1291         Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1292         ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1293         remove_from_template(bottom, temp);
1294         Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1295                 (void *) temp, temp->no_of_queries, 0 );
1296         Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1297         ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1298         free_query(bottom);
1299 }
1300
1301 struct query_info {
1302         struct query_info *next;
1303         struct berval xdn;
1304         int del;
1305 };
1306
1307 static int
1308 remove_func (
1309         Operation       *op,
1310         SlapReply       *rs
1311 )
1312 {
1313         Attribute *attr;
1314         struct query_info *qi;
1315         int count = 0;
1316
1317         if ( rs->sr_type != REP_SEARCH ) return 0;
1318
1319         attr = attr_find( rs->sr_entry->e_attrs,  ad_queryId );
1320         if ( attr == NULL ) return 0;
1321
1322         for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1323                 ;
1324         assert( count > 0 );
1325         qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1326         qi->next = op->o_callback->sc_private;
1327         op->o_callback->sc_private = qi;
1328         ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1329         qi->del = ( count == 1 );
1330
1331         return 0;
1332 }
1333
1334 static int
1335 remove_query_data(
1336         Operation       *op,
1337         SlapReply       *rs,
1338         struct berval   *query_uuid )
1339 {
1340         struct query_info       *qi, *qnext;
1341         char                    filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1342 #ifdef LDAP_COMP_MATCH
1343         AttributeAssertion      ava = { NULL, BER_BVNULL, NULL };
1344 #else
1345         AttributeAssertion      ava = { NULL, BER_BVNULL };
1346 #endif
1347         Filter                  filter = {LDAP_FILTER_EQUALITY};
1348         SlapReply               sreply = {REP_RESULT};
1349         slap_callback cb = { NULL, remove_func, NULL, NULL };
1350         int deleted = 0;
1351
1352         sreply.sr_entry = NULL;
1353         sreply.sr_nentries = 0;
1354         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1355                 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1356         filter.f_ava = &ava;
1357         filter.f_av_desc = ad_queryId;
1358         filter.f_av_value = *query_uuid;
1359
1360         op->o_tag = LDAP_REQ_SEARCH;
1361         op->o_protocol = LDAP_VERSION3;
1362         op->o_callback = &cb;
1363         op->o_time = slap_get_time();
1364         op->o_do_not_cache = 1;
1365
1366         op->o_req_dn = op->o_bd->be_suffix[0];
1367         op->o_req_ndn = op->o_bd->be_nsuffix[0];
1368         op->ors_scope = LDAP_SCOPE_SUBTREE;
1369         op->ors_deref = LDAP_DEREF_NEVER;
1370         op->ors_slimit = SLAP_NO_LIMIT;
1371         op->ors_tlimit = SLAP_NO_LIMIT;
1372         op->ors_filter = &filter;
1373         op->ors_filterstr.bv_val = filter_str;
1374         op->ors_filterstr.bv_len = strlen(filter_str);
1375         op->ors_attrs = NULL;
1376         op->ors_attrsonly = 0;
1377
1378         op->o_bd->be_search( op, &sreply );
1379
1380         for ( qi=cb.sc_private; qi; qi=qnext ) {
1381                 qnext = qi->next;
1382
1383                 op->o_req_dn = qi->xdn;
1384                 op->o_req_ndn = qi->xdn;
1385
1386                 if ( qi->del ) {
1387                         Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1388                                 query_uuid->bv_val, 0, 0 );
1389
1390                         op->o_tag = LDAP_REQ_DELETE;
1391
1392                         if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1393                                 deleted++;
1394                         }
1395
1396                 } else {
1397                         Modifications mod;
1398                         struct berval vals[2];
1399
1400                         vals[0] = *query_uuid;
1401                         vals[1].bv_val = NULL;
1402                         vals[1].bv_len = 0;
1403                         mod.sml_op = LDAP_MOD_DELETE;
1404                         mod.sml_flags = 0;
1405                         mod.sml_desc = ad_queryId;
1406                         mod.sml_type = ad_queryId->ad_cname;
1407                         mod.sml_values = vals;
1408                         mod.sml_nvalues = NULL;
1409                         mod.sml_next = NULL;
1410                         Debug( pcache_debug,
1411                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1412                                 query_uuid->bv_val, 0, 0 );
1413
1414                         op->orm_modlist = &mod;
1415
1416                         op->o_bd->be_modify( op, &sreply );
1417                 }
1418                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1419                 op->o_tmpfree( qi, op->o_tmpmemctx );
1420         }
1421         return deleted;
1422 }
1423
1424 static int
1425 get_attr_set(
1426         AttributeName* attrs,
1427         query_manager* qm,
1428         int num
1429 );
1430
1431 static int
1432 filter2template(
1433         Operation               *op,
1434         Filter                  *f,
1435         struct                  berval *fstr,
1436         AttributeName**         filter_attrs,
1437         int*                    filter_cnt,
1438         int*                    filter_got_oc )
1439 {
1440         AttributeDescription *ad;
1441
1442         switch ( f->f_choice ) {
1443         case LDAP_FILTER_EQUALITY:
1444                 ad = f->f_av_desc;
1445                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1446                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1447                 break;
1448
1449         case LDAP_FILTER_GE:
1450                 ad = f->f_av_desc;
1451                 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1452                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1453                 break;
1454
1455         case LDAP_FILTER_LE:
1456                 ad = f->f_av_desc;
1457                 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1458                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1459                 break;
1460
1461         case LDAP_FILTER_APPROX:
1462                 ad = f->f_av_desc;
1463                 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1464                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1465                 break;
1466
1467         case LDAP_FILTER_SUBSTRINGS:
1468                 ad = f->f_sub_desc;
1469                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1470                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1471                 break;
1472
1473         case LDAP_FILTER_PRESENT:
1474                 ad = f->f_desc;
1475                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1476                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1477                 break;
1478
1479         case LDAP_FILTER_AND:
1480         case LDAP_FILTER_OR:
1481         case LDAP_FILTER_NOT: {
1482                 int rc = 0;
1483                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1484                         f->f_choice == LDAP_FILTER_AND ? '&' :
1485                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1486                 fstr->bv_len += sizeof("(%") - 1;
1487
1488                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1489                         rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1490                                 filter_got_oc );
1491                         if ( rc ) break;
1492                 }
1493                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1494                 fstr->bv_len += sizeof(")") - 1;
1495
1496                 return rc;
1497                 }
1498
1499         default:
1500                 strcpy( fstr->bv_val, "(?=?)" );
1501                 fstr->bv_len += sizeof("(?=?)")-1;
1502                 return -1;
1503         }
1504
1505         if ( filter_attrs != NULL ) {
1506                 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1507                                 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1508
1509                 (*filter_attrs)[*filter_cnt].an_desc = ad;
1510                 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1511                 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1512                 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1513                 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1514                 (*filter_cnt)++;
1515                 if ( ad == slap_schema.si_ad_objectClass )
1516                         *filter_got_oc = 1;
1517         }
1518
1519         return 0;
1520 }
1521
1522 struct search_info {
1523         slap_overinst *on;
1524         Query query;
1525         QueryTemplate *qtemp;
1526         AttributeName*  save_attrs;     /* original attributes, saved for response */
1527         int max;
1528         int over;
1529         int count;
1530         Entry *head, *tail;
1531 };
1532
1533 static void
1534 remove_query_and_data(
1535         Operation       *op,
1536         SlapReply       *rs,
1537         cache_manager   *cm,
1538         struct berval   *uuid )
1539 {
1540         query_manager*          qm = cm->qm;
1541
1542         qm->crfunc( qm, uuid );
1543         if ( !BER_BVISNULL( uuid ) ) {
1544                 int     return_val;
1545
1546                 Debug( pcache_debug,
1547                         "Removing query UUID %s\n",
1548                         uuid->bv_val, 0, 0 );
1549                 return_val = remove_query_data( op, rs, uuid );
1550                 Debug( pcache_debug,
1551                         "QUERY REMOVED, SIZE=%d\n",
1552                         return_val, 0, 0);
1553                 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1554                 cm->cur_entries -= return_val;
1555                 cm->num_cached_queries--;
1556                 Debug( pcache_debug,
1557                         "STORED QUERIES = %lu\n",
1558                         cm->num_cached_queries, 0, 0 );
1559                 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1560                 Debug( pcache_debug,
1561                         "QUERY REMOVED, CACHE ="
1562                         "%d entries\n",
1563                         cm->cur_entries, 0, 0 );
1564         }
1565 }
1566
1567 /*
1568  * Callback used to fetch queryId values based on entryUUID;
1569  * used by pcache_remove_entries_from_cache()
1570  */
1571 static int
1572 fetch_queryId_cb( Operation *op, SlapReply *rs )
1573 {
1574         int             rc = 0;
1575
1576         /* only care about searchEntry responses */
1577         if ( rs->sr_type != REP_SEARCH ) {
1578                 return 0;
1579         }
1580
1581         /* allow only one response per entryUUID */
1582         if ( op->o_callback->sc_private != NULL ) {
1583                 rc = 1;
1584
1585         } else {
1586                 Attribute       *a;
1587
1588                 /* copy all queryId values into callback's private data */
1589                 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1590                 if ( a != NULL ) {
1591                         BerVarray       vals = NULL;
1592
1593                         ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1594                         op->o_callback->sc_private = (void *)vals;
1595                 }
1596         }
1597
1598         /* clear entry if required */
1599         if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1600                 entry_free( rs->sr_entry );
1601                 rs->sr_entry = NULL;
1602                 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1603         }
1604
1605         return rc;
1606 }
1607
1608 /*
1609  * Call that allows to remove a set of entries from the cache,
1610  * by forcing the removal of all the related queries.
1611  */
1612 int
1613 pcache_remove_entries_from_cache(
1614         Operation       *op,
1615         cache_manager   *cm,
1616         BerVarray       entryUUIDs )
1617 {
1618         Connection      conn = { 0 };
1619         OperationBuffer opbuf;
1620         Operation       op2;
1621         slap_callback   sc = { 0 };
1622         SlapReply       rs = { REP_RESULT };
1623         Filter          f = { 0 };
1624         char            filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1625 #ifdef LDAP_COMP_MATCH
1626         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1627 #else
1628         AttributeAssertion ava = { NULL, BER_BVNULL };
1629 #endif
1630         AttributeName   attrs[ 2 ] = { 0 };
1631         int             s, rc;
1632
1633         if ( op == NULL ) {
1634                 void    *thrctx = ldap_pvt_thread_pool_context();
1635
1636                 connection_fake_init( &conn, &opbuf, thrctx );
1637                 op = &opbuf.ob_op;
1638
1639         } else {
1640                 op2 = *op;
1641                 op = &op2;
1642         }
1643
1644         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1645         op->ors_scope = LDAP_SCOPE_SUBTREE;
1646         op->ors_deref = LDAP_DEREF_NEVER;
1647         f.f_choice = LDAP_FILTER_EQUALITY;
1648         f.f_ava = &ava;
1649         ava.aa_desc = slap_schema.si_ad_entryUUID;
1650         op->ors_filter = &f;
1651         op->ors_slimit = 1;
1652         op->ors_tlimit = SLAP_NO_LIMIT;
1653         attrs[ 0 ].an_desc = ad_queryId;
1654         attrs[ 0 ].an_name = ad_queryId->ad_cname;
1655         op->ors_attrs = attrs;
1656         op->ors_attrsonly = 0;
1657
1658         op->o_req_dn = cm->db.be_suffix[ 0 ];
1659         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1660
1661         op->o_tag = LDAP_REQ_SEARCH;
1662         op->o_protocol = LDAP_VERSION3;
1663         op->o_managedsait = SLAP_CONTROL_CRITICAL;
1664         op->o_bd = &cm->db;
1665         op->o_dn = op->o_bd->be_rootdn;
1666         op->o_ndn = op->o_bd->be_rootndn;
1667         sc.sc_response = fetch_queryId_cb;
1668         op->o_callback = &sc;
1669
1670         for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1671                 BerVarray       vals = NULL;
1672
1673                 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1674                         "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1675                 op->ors_filterstr.bv_val = filtbuf;
1676                 ava.aa_value = entryUUIDs[ s ];
1677
1678                 rc = op->o_bd->be_search( op, &rs );
1679                 if ( rc != LDAP_SUCCESS ) {
1680                         continue;
1681                 }
1682
1683                 vals = (BerVarray)op->o_callback->sc_private;
1684                 if ( vals != NULL ) {
1685                         int             i;
1686
1687                         for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1688                                 struct berval   val = vals[ i ];
1689
1690                                 remove_query_and_data( op, &rs, cm, &val );
1691
1692                                 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1693                                         ch_free( val.bv_val );
1694                                 }
1695                         }
1696
1697                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1698                         op->o_callback->sc_private = NULL;
1699                 }
1700         }
1701
1702         return 0;
1703 }
1704
1705 /*
1706  * Call that allows to remove a query from the cache.
1707  */
1708 int
1709 pcache_remove_query_from_cache(
1710         Operation       *op,
1711         cache_manager   *cm,
1712         struct berval   *queryid )
1713 {
1714         Operation       op2 = *op;
1715         SlapReply       rs2 = { 0 };
1716
1717         op2.o_bd = &cm->db;
1718
1719         /* remove the selected query */
1720         remove_query_and_data( &op2, &rs2, cm, queryid );
1721
1722         return LDAP_SUCCESS;
1723 }
1724
1725 /*
1726  * Call that allows to remove a set of queries related to an entry 
1727  * from the cache; if queryid is not null, the entry must belong to
1728  * the query indicated by queryid.
1729  */
1730 int
1731 pcache_remove_entry_queries_from_cache(
1732         Operation       *op,
1733         cache_manager   *cm,
1734         struct berval   *ndn,
1735         struct berval   *queryid )
1736 {
1737         Connection              conn = { 0 };
1738         OperationBuffer         opbuf;
1739         Operation               op2;
1740         slap_callback           sc = { 0 };
1741         SlapReply               rs = { REP_RESULT };
1742         Filter                  f = { 0 };
1743         char                    filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1744 #ifdef LDAP_COMP_MATCH
1745         AttributeAssertion      ava = { NULL, BER_BVNULL, NULL };
1746 #else
1747         AttributeAssertion      ava = { NULL, BER_BVNULL };
1748 #endif
1749         AttributeName           attrs[ 2 ] = { 0 };
1750         int                     rc;
1751
1752         BerVarray               vals = NULL;
1753
1754         if ( op == NULL ) {
1755                 void    *thrctx = ldap_pvt_thread_pool_context();
1756
1757                 connection_fake_init( &conn, &opbuf, thrctx );
1758                 op = &opbuf.ob_op;
1759
1760         } else {
1761                 op2 = *op;
1762                 op = &op2;
1763         }
1764
1765         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1766         op->ors_scope = LDAP_SCOPE_BASE;
1767         op->ors_deref = LDAP_DEREF_NEVER;
1768         if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1769                 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1770                 f.f_choice = LDAP_FILTER_PRESENT;
1771                 f.f_desc = slap_schema.si_ad_objectClass;
1772
1773         } else {
1774                 op->ors_filterstr.bv_len = snprintf( filter_str,
1775                         sizeof( filter_str ), "(%s=%s)",
1776                         ad_queryId->ad_cname.bv_val, queryid->bv_val );
1777                 f.f_choice = LDAP_FILTER_EQUALITY;
1778                 f.f_ava = &ava;
1779                 f.f_av_desc = ad_queryId;
1780                 f.f_av_value = *queryid;
1781         }
1782         op->ors_filter = &f;
1783         op->ors_slimit = 1;
1784         op->ors_tlimit = SLAP_NO_LIMIT;
1785         attrs[ 0 ].an_desc = ad_queryId;
1786         attrs[ 0 ].an_name = ad_queryId->ad_cname;
1787         op->ors_attrs = attrs;
1788         op->ors_attrsonly = 0;
1789
1790         op->o_req_dn = *ndn;
1791         op->o_req_ndn = *ndn;
1792
1793         op->o_tag = LDAP_REQ_SEARCH;
1794         op->o_protocol = LDAP_VERSION3;
1795         op->o_managedsait = SLAP_CONTROL_CRITICAL;
1796         op->o_bd = &cm->db;
1797         op->o_dn = op->o_bd->be_rootdn;
1798         op->o_ndn = op->o_bd->be_rootndn;
1799         sc.sc_response = fetch_queryId_cb;
1800         op->o_callback = &sc;
1801
1802         rc = op->o_bd->be_search( op, &rs );
1803         if ( rc != LDAP_SUCCESS ) {
1804                 return rc;
1805         }
1806
1807         vals = (BerVarray)op->o_callback->sc_private;
1808         if ( vals != NULL ) {
1809                 int             i;
1810
1811                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1812                         struct berval   val = vals[ i ];
1813
1814                         remove_query_and_data( op, &rs, cm, &val );
1815
1816                         if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1817                                 ch_free( val.bv_val );
1818                         }
1819                 }
1820
1821                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1822         }
1823
1824         return LDAP_SUCCESS;
1825 }
1826
1827 static int
1828 cache_entries(
1829         Operation       *op,
1830         SlapReply       *rs,
1831         struct berval *query_uuid )
1832 {
1833         struct search_info *si = op->o_callback->sc_private;
1834         slap_overinst *on = si->on;
1835         cache_manager *cm = on->on_bi.bi_private;
1836         int             return_val = 0;
1837         Entry           *e;
1838         struct berval   crp_uuid;
1839         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1840         Operation op_tmp = *op;
1841
1842         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1843         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1844
1845         op_tmp.o_bd = &cm->db;
1846         op_tmp.o_dn = cm->db.be_rootdn;
1847         op_tmp.o_ndn = cm->db.be_rootndn;
1848
1849         Debug( pcache_debug, "UUID for query being added = %s\n",
1850                         uuidbuf, 0, 0 );
1851
1852         for ( e=si->head; e; e=si->head ) {
1853                 si->head = e->e_private;
1854                 e->e_private = NULL;
1855                 while ( cm->cur_entries > (cm->max_entries) ) {
1856                         BER_BVZERO( &crp_uuid );
1857                         remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1858                 }
1859
1860                 return_val = merge_entry(&op_tmp, e, query_uuid);
1861                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1862                 cm->cur_entries += return_val;
1863                 Debug( pcache_debug,
1864                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1865                         cm->cur_entries, 0, 0 );
1866                 return_val = 0;
1867                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1868         }
1869
1870         return return_val;
1871 }
1872
1873 static int
1874 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1875         slap_callback   *cb = op->o_callback;
1876         struct search_info *si = cb->sc_private;
1877         if ( rs->sr_type == REP_RESULT || op->o_abandon || 
1878                         rs->sr_err == SLAPD_ABANDON ) {
1879                 if ( si->save_attrs != NULL ) {
1880                         rs->sr_attrs = si->save_attrs;
1881                         op->ors_attrs = si->save_attrs;
1882                 }
1883                 op->o_callback = op->o_callback->sc_next;
1884                 op->o_tmpfree( cb, op->o_tmpmemctx );
1885         }
1886         return SLAP_CB_CONTINUE;
1887 }
1888
1889 static int
1890 pcache_response(
1891         Operation       *op,
1892         SlapReply       *rs )
1893 {
1894         struct search_info *si = op->o_callback->sc_private;
1895         slap_overinst *on = si->on;
1896         cache_manager *cm = on->on_bi.bi_private;
1897         query_manager*          qm = cm->qm;
1898
1899         if ( si->save_attrs != NULL ) {
1900                 rs->sr_attrs = si->save_attrs;
1901                 op->ors_attrs = si->save_attrs;
1902         }
1903
1904         if ( rs->sr_type == REP_SEARCH ) {
1905                 Entry *e;
1906                 /* If we haven't exceeded the limit for this query,
1907                  * build a chain of answers to store. If we hit the
1908                  * limit, empty the chain and ignore the rest.
1909                  */
1910                 if ( !si->over ) {
1911                         if ( si->count < si->max ) {
1912                                 si->count++;
1913                                 e = entry_dup( rs->sr_entry );
1914                                 if ( !si->head ) si->head = e;
1915                                 if ( si->tail ) si->tail->e_private = e;
1916                                 si->tail = e;
1917                         } else {
1918                                 si->over = 1;
1919                                 si->count = 0;
1920                                 for (;si->head; si->head=e) {
1921                                         e = si->head->e_private;
1922                                         si->head->e_private = NULL;
1923                                         entry_free(si->head);
1924                                 }
1925                                 si->tail = NULL;
1926                         }
1927                 }
1928
1929         } else if ( rs->sr_type == REP_RESULT ) {
1930                 if ( si->count ||
1931                         ( si->qtemp->negttl && !si->count && !si->over &&
1932                                 rs->sr_err == LDAP_SUCCESS )) {
1933                         CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1934                                 si->count);
1935
1936                         if ( qc != NULL ) {
1937                                 if ( si->count )
1938                                         cache_entries( op, rs, &qc->q_uuid );
1939                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1940                                 cm->num_cached_queries++;
1941                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1942                                                 cm->num_cached_queries, 0, 0 );
1943                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1944
1945                                 /* If the consistency checker suspended itself,
1946                                  * wake it back up
1947                                  */
1948                                 if ( cm->cc_paused ) {
1949                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1950                                         if ( cm->cc_paused ) {
1951                                                 cm->cc_paused = 0;
1952                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1953                                         }
1954                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1955                                 }
1956                         } else if ( si->count ) {
1957                                 /* duplicate query, free it */
1958                                 Entry *e;
1959                                 for (;si->head; si->head=e) {
1960                                         e = si->head->e_private;
1961                                         si->head->e_private = NULL;
1962                                         entry_free(si->head);
1963                                 }
1964                         }
1965                 } else {
1966                         filter_free( si->query.filter );
1967                 }
1968         }
1969         return SLAP_CB_CONTINUE;
1970 }
1971
1972 static int
1973 add_filter_attrs(
1974         Operation *op,
1975         AttributeName** new_attrs,
1976         struct attr_set *attrs,
1977         AttributeName* filter_attrs,
1978         int fattr_cnt,
1979         int fattr_got_oc)
1980 {
1981         int alluser = 0;
1982         int allop = 0;
1983         int i, j;
1984         int count;
1985         int addoc = 0;
1986
1987         /* duplicate attrs */
1988         count = attrs->count + fattr_cnt;
1989         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1990                 addoc = 1;
1991                 count++;
1992         }
1993
1994         *new_attrs = (AttributeName*)ch_calloc( count + 1,
1995                 sizeof(AttributeName) );
1996         for (i=0; i<attrs->count; i++) {
1997                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1998                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1999         }
2000         BER_BVZERO( &(*new_attrs)[i].an_name );
2001         alluser = an_find(*new_attrs, &AllUser);
2002         allop = an_find(*new_attrs, &AllOper);
2003
2004         j = i;
2005         for ( i=0; i<fattr_cnt; i++ ) {
2006                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2007                         continue;
2008                 }
2009                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2010                         if ( allop ) {
2011                                 continue;
2012                         }
2013                 } else if ( alluser ) {
2014                         continue;
2015                 }
2016                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2017                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2018                 (*new_attrs)[j].an_oc = NULL;
2019                 (*new_attrs)[j].an_oc_exclude = 0;
2020                 j++;
2021         }
2022         if ( addoc ) {
2023                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2024                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2025                 (*new_attrs)[j].an_oc = NULL;
2026                 (*new_attrs)[j].an_oc_exclude = 0;
2027                 j++;
2028         }
2029         BER_BVZERO( &(*new_attrs)[j].an_name );
2030
2031         return count;
2032 }
2033
2034 /* NOTE: this is a quick workaround to let pcache minimally interact
2035  * with pagedResults.  A more articulated solutions would be to
2036  * perform the remote query without control and cache all results,
2037  * performing the pagedResults search only within the client
2038  * and the proxy.  This requires pcache to understand pagedResults. */
2039 static int
2040 pcache_chk_controls(
2041         Operation       *op,
2042         SlapReply       *rs )
2043 {
2044         const char      *non = "";
2045         const char      *stripped = "";
2046
2047         switch( op->o_pagedresults ) {
2048         case SLAP_CONTROL_NONCRITICAL:
2049                 non = "non-";
2050                 stripped = "; stripped";
2051                 /* fallthru */
2052
2053         case SLAP_CONTROL_CRITICAL:
2054                 Debug( pcache_debug, "%s: "
2055                         "%scritical pagedResults control "
2056                         "disabled with proxy cache%s.\n",
2057                         op->o_log_prefix, non, stripped );
2058                 
2059                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2060                 break;
2061
2062         default:
2063                 rs->sr_err = SLAP_CB_CONTINUE;
2064                 break;
2065         }
2066
2067         return rs->sr_err;
2068 }
2069
2070 #ifdef PCACHE_CONTROL_PRIVDB
2071 static int
2072 pcache_op_privdb(
2073         Operation               *op,
2074         SlapReply               *rs )
2075 {
2076         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
2077         cache_manager   *cm = on->on_bi.bi_private;
2078         slap_callback   *save_cb;
2079         slap_op_t       type;
2080
2081         /* skip if control is unset */
2082         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2083                 return SLAP_CB_CONTINUE;
2084         }
2085
2086         /* FIXME: might be a little bit exaggerated... */
2087         if ( !be_isroot( op ) ) {
2088                 save_cb = op->o_callback;
2089                 op->o_callback = NULL;
2090                 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2091                         "pcachePrivDB: operation not allowed" );
2092                 op->o_callback = save_cb;
2093
2094                 return rs->sr_err;
2095         }
2096
2097         /* map tag to operation */
2098         type = slap_req2op( op->o_tag );
2099         if ( type != SLAP_OP_LAST ) {
2100                 BI_op_func      **func;
2101                 int             rc;
2102
2103                 /* execute, if possible */
2104                 func = &cm->db.be_bind;
2105                 if ( func[ type ] != NULL ) {
2106                         Operation       op2 = *op;
2107         
2108                         op2.o_bd = &cm->db;
2109
2110                         rc = func[ type ]( &op2, rs );
2111                         if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2112                                 op->o_conn->c_authz_cookie = cm->db.be_private;
2113                         }
2114                 }
2115         }
2116
2117         /* otherwise fall back to error */
2118         save_cb = op->o_callback;
2119         op->o_callback = NULL;
2120         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2121                 "operation not supported with pcachePrivDB control" );
2122         op->o_callback = save_cb;
2123
2124         return rs->sr_err;
2125 }
2126 #endif /* PCACHE_CONTROL_PRIVDB */
2127
2128 static int
2129 pcache_op_search(
2130         Operation       *op,
2131         SlapReply       *rs )
2132 {
2133         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2134         cache_manager *cm = on->on_bi.bi_private;
2135         query_manager*          qm = cm->qm;
2136
2137         int i = -1;
2138
2139         AttributeName   *filter_attrs = NULL;
2140
2141         Query           query;
2142         QueryTemplate   *qtemp = NULL;
2143
2144         int             attr_set = -1;
2145         CachedQuery     *answerable = NULL;
2146         int             cacheable = 0;
2147         int             fattr_cnt=0;
2148         int             fattr_got_oc = 0;
2149
2150         struct berval   tempstr;
2151
2152 #ifdef PCACHE_CONTROL_PRIVDB
2153         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2154                 return pcache_op_privdb( op, rs );
2155         }
2156 #endif /* PCACHE_CONTROL_PRIVDB */
2157
2158         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2159         tempstr.bv_len = 0;
2160         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2161                 &fattr_cnt, &fattr_got_oc )) {
2162                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2163                 return SLAP_CB_CONTINUE;
2164         }
2165
2166         Debug( pcache_debug, "query template of incoming query = %s\n",
2167                                         tempstr.bv_val, 0, 0 );
2168
2169         /* FIXME: cannot cache/answer requests with pagedResults control */
2170
2171         /* find attr set */
2172         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2173
2174         query.filter = op->ors_filter;
2175         query.base = op->o_req_ndn;
2176         query.scope = op->ors_scope;
2177
2178         /* check for query containment */
2179         if (attr_set > -1) {
2180                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2181                 for (; qt; qt = qt->qtnext ) {
2182                         /* find if template i can potentially answer tempstr */
2183                         if (qt->querystr.bv_len != tempstr.bv_len ||
2184                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2185                                 continue;
2186                         cacheable = 1;
2187                         qtemp = qt;
2188                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
2189                                         op->ors_filterstr.bv_val, 0, 0 );
2190                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2191
2192                         if (answerable)
2193                                 break;
2194                 }
2195         }
2196         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2197
2198         if (answerable) {
2199                 /* Need to clear the callbacks of the original operation,
2200                  * in case there are other overlays */
2201                 BackendDB       *save_bd = op->o_bd;
2202                 slap_callback   *save_cb = op->o_callback;
2203
2204                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2205                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2206                 if ( BER_BVISNULL( &answerable->q_uuid )) {
2207                         /* No entries cached, just an empty result set */
2208                         i = rs->sr_err = 0;
2209                         send_ldap_result( op, rs );
2210                 } else {
2211                         op->o_bd = &cm->db;
2212                         op->o_callback = NULL;
2213                         i = cm->db.bd_info->bi_op_search( op, rs );
2214                 }
2215                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2216                 op->o_bd = save_bd;
2217                 op->o_callback = save_cb;
2218                 return i;
2219         }
2220
2221         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2222
2223         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2224         if (cm->num_cached_queries >= cm->max_queries) {
2225                 cacheable = 0;
2226         }
2227         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2228
2229         if (op->ors_attrsonly)
2230                 cacheable = 0;
2231
2232         if (cacheable) {
2233                 slap_callback           *cb;
2234                 struct search_info      *si;
2235
2236                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2237                 query.filter = filter_dup(op->ors_filter, NULL);
2238                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2239                 if ( !qtemp->t_attrs.count ) {
2240                         qtemp->t_attrs.count = add_filter_attrs(op,
2241                                 &qtemp->t_attrs.attrs,
2242                                 &qm->attr_sets[attr_set],
2243                                 filter_attrs, fattr_cnt, fattr_got_oc);
2244                 }
2245                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2246
2247                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2248                 cb->sc_response = pcache_response;
2249                 cb->sc_cleanup = pcache_op_cleanup;
2250                 cb->sc_private = (cb+1);
2251                 si = cb->sc_private;
2252                 si->on = on;
2253                 si->query = query;
2254                 si->qtemp = qtemp;
2255                 si->max = cm->num_entries_limit ;
2256                 si->over = 0;
2257                 si->count = 0;
2258                 si->head = NULL;
2259                 si->tail = NULL;
2260                 si->save_attrs = op->ors_attrs;
2261
2262                 op->ors_attrs = qtemp->t_attrs.attrs;
2263
2264                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2265                         cb->sc_next = op->o_callback;
2266                         op->o_callback = cb;
2267
2268                 } else {
2269                         slap_callback           **pcb;
2270
2271                         /* need to move the callback at the end, in case other
2272                          * overlays are present, so that the final entry is
2273                          * actually cached */
2274                         cb->sc_next = NULL;
2275                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2276                         *pcb = cb;
2277                 }
2278
2279         } else {
2280                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2281                                         0, 0, 0);
2282         }
2283
2284         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2285
2286         return SLAP_CB_CONTINUE;
2287 }
2288
2289 static int
2290 get_attr_set(
2291         AttributeName* attrs,
2292         query_manager* qm,
2293         int num )
2294 {
2295         int i;
2296         int count = 0;
2297
2298         if ( attrs ) {
2299                 for ( ; attrs[count].an_name.bv_val; count++ );
2300         }
2301
2302         /* recognize a single "*" or a "1.1" */
2303         if ( count == 0 ) {
2304                 count = 1;
2305                 attrs = slap_anlist_all_user_attributes;
2306
2307         } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2308                 count = 0;
2309                 attrs = NULL;
2310         }
2311
2312         for ( i = 0; i < num; i++ ) {
2313                 AttributeName *a2;
2314                 int found = 1;
2315
2316                 if ( count > qm->attr_sets[i].count ) {
2317                         continue;
2318                 }
2319
2320                 if ( !count ) {
2321                         if ( !qm->attr_sets[i].count ) {
2322                                 break;
2323                         }
2324                         continue;
2325                 }
2326
2327                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2328                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2329                                 found = 0;
2330                                 break;
2331                         }
2332                 }
2333
2334                 if ( found ) {
2335                         break;
2336                 }
2337         }
2338
2339         if ( i == num ) {
2340                 i = -1;
2341         }
2342
2343         return i;
2344 }
2345
2346 static void*
2347 consistency_check(
2348         void *ctx,
2349         void *arg )
2350 {
2351         struct re_s *rtask = arg;
2352         slap_overinst *on = rtask->arg;
2353         cache_manager *cm = on->on_bi.bi_private;
2354         query_manager *qm = cm->qm;
2355         Connection conn = {0};
2356         OperationBuffer opbuf;
2357         Operation *op;
2358
2359         SlapReply rs = {REP_RESULT};
2360         CachedQuery* query;
2361         int return_val, pause = 1;
2362         QueryTemplate* templ;
2363
2364         connection_fake_init( &conn, &opbuf, ctx );
2365         op = &opbuf.ob_op;
2366
2367         op->o_bd = &cm->db;
2368         op->o_dn = cm->db.be_rootdn;
2369         op->o_ndn = cm->db.be_rootndn;
2370
2371         cm->cc_arg = arg;
2372
2373         for (templ = qm->templates; templ; templ=templ->qmnext) {
2374                 query = templ->query_last;
2375                 if ( query ) pause = 0;
2376                 op->o_time = slap_get_time();
2377                 while (query && (query->expiry_time < op->o_time)) {
2378                         int rem = 0;
2379                         Debug( pcache_debug, "Lock CR index = %p\n",
2380                                         (void *) templ, 0, 0 );
2381                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2382                         if ( query == templ->query_last ) {
2383                                 rem = 1;
2384                                 remove_from_template(query, templ);
2385                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2386                                                 (void *) templ, templ->no_of_queries, 0 );
2387                                 Debug( pcache_debug, "Unlock CR index = %p\n",
2388                                                 (void *) templ, 0, 0 );
2389                         }
2390                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2391                         if ( !rem ) {
2392                                 query = templ->query_last;
2393                                 continue;
2394                         }
2395                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2396                         remove_query(qm, query);
2397                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2398                         if ( BER_BVISNULL( &query->q_uuid ))
2399                                 return_val = 0;
2400                         else
2401                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
2402                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2403                                                 return_val, 0, 0 );
2404                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2405                         cm->cur_entries -= return_val;
2406                         cm->num_cached_queries--;
2407                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
2408                                         cm->num_cached_queries, 0, 0 );
2409                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2410                         Debug( pcache_debug,
2411                                 "STALE QUERY REMOVED, CACHE ="
2412                                 "%d entries\n",
2413                                 cm->cur_entries, 0, 0 );
2414                         free_query(query);
2415                         query = templ->query_last;
2416                 }
2417         }
2418         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2419         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2420                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2421         }
2422         /* If there were no queries, defer processing for a while */
2423         cm->cc_paused = pause;
2424         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2425
2426         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2427         return NULL;
2428 }
2429
2430
2431 #define MAX_ATTR_SETS 500
2432
2433 enum {
2434         PC_MAIN = 1,
2435         PC_ATTR,
2436         PC_TEMP,
2437         PC_RESP,
2438         PC_QUERIES
2439 };
2440
2441 static ConfigDriver pc_cf_gen;
2442 static ConfigLDAPadd pc_ldadd;
2443 static ConfigCfAdd pc_cfadd;
2444
2445 static ConfigTable pccfg[] = {
2446         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2447                                 "<cycle_time",
2448                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2449                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2450                         "DESC 'ProxyCache basic parameters' "
2451                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2452         { "proxyattrset", "index> <attributes...",
2453                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2454                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2455                         "DESC 'A set of attributes to cache' "
2456                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2457         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2458                 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2459                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2460                         "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2461                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2462         { "response-callback", "head|tail(default)",
2463                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2464                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2465                         "DESC 'Response callback position in overlay stack' "
2466                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2467         { "proxyCacheQueries", "queries",
2468                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2469                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2470                         "DESC 'Maximum number of queries to cache' "
2471                         "SYNTAX OMsInteger )", NULL, NULL },
2472         { "proxySaveQueries", "TRUE|FALSE",
2473                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2474                 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2475                         "DESC 'Save cached queries for hot restart' "
2476                         "SYNTAX OMsBoolean )", NULL, NULL },
2477
2478         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2479 };
2480
2481 static ConfigOCs pcocs[] = {
2482         { "( OLcfgOvOc:2.1 "
2483                 "NAME 'olcPcacheConfig' "
2484                 "DESC 'ProxyCache configuration' "
2485                 "SUP olcOverlayConfig "
2486                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2487                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2488                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2489         { "( OLcfgOvOc:2.2 "
2490                 "NAME 'olcPcacheDatabase' "
2491                 "DESC 'Cache database configuration' "
2492                 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2493         { NULL, 0, NULL }
2494 };
2495
2496 static int
2497 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2498 {
2499         slap_overinst *on;
2500         cache_manager *cm;
2501
2502         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2503                 p->ce_bi->bi_cf_ocs != pcocs )
2504                 return LDAP_CONSTRAINT_VIOLATION;
2505
2506         on = (slap_overinst *)p->ce_bi;
2507         cm = on->on_bi.bi_private;
2508         ca->be = &cm->db;
2509         return LDAP_SUCCESS;
2510 }
2511
2512 static int
2513 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2514 {
2515         CfEntryInfo *pe = p->e_private;
2516         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2517         cache_manager *cm = on->on_bi.bi_private;
2518         struct berval bv;
2519
2520         /* FIXME: should not hardcode "olcDatabase" here */
2521         bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2522         bv.bv_val = ca->cr_msg;
2523         ca->be = &cm->db;
2524
2525         /* We can only create this entry if the database is table-driven
2526          */
2527         if ( cm->db.bd_info->bi_cf_ocs )
2528                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2529                         &pcocs[1] );
2530
2531         return 0;
2532 }
2533
2534 static int
2535 pc_cf_gen( ConfigArgs *c )
2536 {
2537         slap_overinst   *on = (slap_overinst *)c->bi;
2538         cache_manager*  cm = on->on_bi.bi_private;
2539         query_manager*  qm = cm->qm;
2540         QueryTemplate*  temp;
2541         AttributeName*  attr_name;
2542         AttributeName*  attrarray;
2543         const char*     text=NULL;
2544         int             i, num, rc = 0;
2545         char            *ptr;
2546         unsigned long   t;
2547
2548         if ( c->op == SLAP_CONFIG_EMIT ) {
2549                 struct berval bv;
2550                 switch( c->type ) {
2551                 case PC_MAIN:
2552                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2553                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2554                                 cm->num_entries_limit, cm->cc_period );
2555                         bv.bv_val = c->cr_msg;
2556                         value_add_one( &c->rvalue_vals, &bv );
2557                         break;
2558                 case PC_ATTR:
2559                         for (i=0; i<cm->numattrsets; i++) {
2560                                 if ( !qm->attr_sets[i].count ) continue;
2561
2562                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2563
2564                                 /* count the attr length */
2565                                 for ( attr_name = qm->attr_sets[i].attrs;
2566                                         attr_name->an_name.bv_val; attr_name++ )
2567                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2568
2569                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2570                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2571                                 for ( attr_name = qm->attr_sets[i].attrs;
2572                                         attr_name->an_name.bv_val; attr_name++ ) {
2573                                         *ptr++ = ' ';
2574                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2575                                 }
2576                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2577                         }
2578                         if ( !c->rvalue_vals )
2579                                 rc = 1;
2580                         break;
2581                 case PC_TEMP:
2582                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2583                                 if ( temp->negttl ) {
2584                                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2585                                                 " %d %ld %ld",
2586                                                 temp->attr_set_index,
2587                                                 temp->ttl,
2588                                                 temp->negttl );
2589                                 } else {
2590                                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2591                                                 temp->attr_set_index,
2592                                                 temp->ttl );
2593                                 }
2594                                 bv.bv_len += temp->querystr.bv_len + 2;
2595                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2596                                 ptr = bv.bv_val;
2597                                 *ptr++ = '"';
2598                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2599                                 *ptr++ = '"';
2600                                 strcpy( ptr, c->cr_msg );
2601                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2602                         }
2603                         if ( !c->rvalue_vals )
2604                                 rc = 1;
2605                         break;
2606                 case PC_RESP:
2607                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2608                                 BER_BVSTR( &bv, "head" );
2609                         } else {
2610                                 BER_BVSTR( &bv, "tail" );
2611                         }
2612                         value_add_one( &c->rvalue_vals, &bv );
2613                         break;
2614                 case PC_QUERIES:
2615                         c->value_int = cm->max_queries;
2616                         break;
2617                 }
2618                 return rc;
2619         } else if ( c->op == LDAP_MOD_DELETE ) {
2620                 return 1;       /* FIXME */
2621 #if 0
2622                 switch( c->type ) {
2623                 case PC_ATTR:
2624                 case PC_TEMP:
2625                 }
2626                 return rc;
2627 #endif
2628         }
2629
2630         switch( c->type ) {
2631         case PC_MAIN:
2632                 if ( cm->numattrsets > 0 ) {
2633                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2634                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2635                         return( 1 );
2636                 }
2637
2638                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2639                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2640                                 c->argv[3] );
2641                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2642                         return( 1 );
2643                 }
2644                 if ( cm->numattrsets <= 0 ) {
2645                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2646                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2647                         return( 1 );
2648                 }
2649                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2650                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2651                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2652                         return( 1 );
2653                 }
2654
2655                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2656                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2657                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2658                         return( 1 );
2659                 }
2660
2661                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2662                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2663                                 c->argv[2] );
2664                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2665                         return( 1 );
2666                 }
2667                 if ( cm->max_entries <= 0 ) {
2668                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2669                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2670                         return( 1 );
2671                 }
2672
2673                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2674                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2675                                 c->argv[4] );
2676                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2677                         return( 1 );
2678                 }
2679                 if ( cm->num_entries_limit <= 0 ) {
2680                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2681                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2682                         return( 1 );
2683                 }
2684                 if ( cm->num_entries_limit > cm->max_entries ) {
2685                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2686                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2687                         return( 1 );
2688                 }
2689
2690                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2691                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2692                                 c->argv[5] );
2693                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2694                         return( 1 );
2695                 }
2696                 cm->cc_period = (time_t)t;
2697                 Debug( pcache_debug,
2698                                 "Total # of attribute sets to be cached = %d.\n",
2699                                 cm->numattrsets, 0, 0 );
2700                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2701                                                 sizeof( struct attr_set ) );
2702                 break;
2703         case PC_ATTR:
2704                 if ( cm->numattrsets == 0 ) {
2705                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2706                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2707                         return( 1 );
2708                 }
2709                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2710                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2711                                 c->argv[1] );
2712                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2713                         return( 1 );
2714                 }
2715
2716                 if ( num < 0 || num >= cm->numattrsets ) {
2717                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2718                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2719                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2720                         return 1;
2721                 }
2722                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2723                 if ( c->argc == 2 ) {
2724                         /* assume "1.1" */
2725                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2726                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2727                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2728                         return 1;
2729
2730                 } else if ( c->argc == 3 ) {
2731                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2732                                 qm->attr_sets[num].count = 1;
2733                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2734                                         sizeof( AttributeName ) );
2735                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2736                                 break;
2737
2738                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2739                                 qm->attr_sets[num].count = 1;
2740                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2741                                         sizeof( AttributeName ) );
2742                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2743                                 break;
2744
2745                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2746                                 break;
2747                         }
2748                         /* else: fallthru */
2749
2750                 } else if ( c->argc == 4 ) {
2751                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2752                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2753                         {
2754                                 qm->attr_sets[num].count = 2;
2755                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2756                                         sizeof( AttributeName ) );
2757                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2758                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2759                                 break;
2760                         }
2761                         /* else: fallthru */
2762                 }
2763
2764                 if ( c->argc > 2 ) {
2765                         int all_user = 0, all_op = 0;
2766
2767                         qm->attr_sets[num].count = c->argc - 2;
2768                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2769                                 sizeof( AttributeName ) );
2770                         attr_name = qm->attr_sets[num].attrs;
2771                         for ( i = 2; i < c->argc; i++ ) {
2772                                 attr_name->an_desc = NULL;
2773                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2774                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2775                                                 "invalid attr #%d \"%s\" in attrlist",
2776                                                 i - 2, c->argv[i] );
2777                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2778                                         ch_free( qm->attr_sets[num].attrs );
2779                                         qm->attr_sets[num].attrs = NULL;
2780                                         qm->attr_sets[num].count = 0;
2781                                         return 1;
2782                                 }
2783                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2784                                         all_user = 1;
2785                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2786                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2787                                         all_op = 1;
2788                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2789                                 } else {
2790                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2791                                                 strcpy( c->cr_msg, text );
2792                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2793                                                 ch_free( qm->attr_sets[num].attrs );
2794                                                 qm->attr_sets[num].attrs = NULL;
2795                                                 qm->attr_sets[num].count = 0;
2796                                                 return 1;
2797                                         }
2798                                         attr_name->an_name = attr_name->an_desc->ad_cname;
2799                                 }
2800                                 attr_name->an_oc = NULL;
2801                                 attr_name->an_oc_exclude = 0;
2802                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2803                                         qm->attr_sets[num].flags |= PC_GOT_OC;
2804                                 attr_name++;
2805                                 BER_BVZERO( &attr_name->an_name );
2806                         }
2807
2808                         /* warn if list contains both "*" and "+" */
2809                         if ( i > 4 && all_user && all_op ) {
2810                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2811                                         "warning: attribute list contains \"*\" and \"+\"" );
2812                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2813                         }
2814                 }
2815                 break;
2816         case PC_TEMP:
2817                 if ( cm->numattrsets == 0 ) {
2818                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2819                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2820                         return( 1 );
2821                 }
2822                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2823                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2824                                 c->argv[2] );
2825                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2826                         return( 1 );
2827                 }
2828
2829                 if ( i < 0 || i >= cm->numattrsets || 
2830                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2831                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2832                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2833                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2834                         return 1;
2835                 }
2836                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2837                 temp->qmnext = qm->templates;
2838                 qm->templates = temp;
2839                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2840                 temp->query = temp->query_last = NULL;
2841                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2842                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2843                                 c->argv[3] );
2844                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2845                         return( 1 );
2846                 }
2847                 temp->ttl = (time_t)t;
2848                 if ( c->argc == 5 ) {
2849                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2850                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2851                                         "unable to parse template negttl=\"%s\"",
2852                                         c->argv[4] );
2853                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2854                                         return( 1 );
2855                         }
2856                         temp->negttl = (time_t)t;
2857                 } else {
2858                         temp->negttl = 0;
2859                 }
2860
2861                 temp->no_of_queries = 0;
2862
2863                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2864                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2865                 Debug( pcache_debug, "  query template: %s\n",
2866                                 temp->querystr.bv_val, 0, 0 );
2867                 temp->attr_set_index = i;
2868                 qm->attr_sets[i].flags |= PC_REFERENCED;
2869                 temp->qtnext = qm->attr_sets[i].templates;
2870                 qm->attr_sets[i].templates = temp;
2871                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
2872                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2873                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
2874                                 Debug( pcache_debug, "\t%s\n",
2875                                         attrarray[i].an_name.bv_val, 0, 0 );
2876                 }
2877                 break;
2878         case PC_RESP:
2879                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2880                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2881
2882                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2883                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2884
2885                 } else {
2886                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2887                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2888                         return 1;
2889                 }
2890                 break;
2891         case PC_QUERIES:
2892                 if ( c->value_int <= 0 ) {
2893                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2894                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2895                         return( 1 );
2896                 }
2897                 cm->max_queries = c->value_int;
2898                 break;
2899         }
2900         return rc;
2901 }
2902
2903 static int
2904 pcache_db_config(
2905         BackendDB       *be,
2906         const char      *fname,
2907         int             lineno,
2908         int             argc,
2909         char            **argv
2910 )
2911 {
2912         slap_overinst   *on = (slap_overinst *)be->bd_info;
2913         cache_manager*  cm = on->on_bi.bi_private;
2914
2915         /* Something for the cache database? */
2916         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2917                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2918                         argc, argv );
2919         return SLAP_CONF_UNKNOWN;
2920 }
2921
2922 static int
2923 pcache_db_init(
2924         BackendDB *be,
2925         ConfigReply *cr)
2926 {
2927         slap_overinst *on = (slap_overinst *)be->bd_info;
2928         cache_manager *cm;
2929         query_manager *qm;
2930
2931         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2932         on->on_bi.bi_private = cm;
2933
2934         qm = (query_manager*)ch_malloc(sizeof(query_manager));
2935
2936         cm->db = *be;
2937         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2938         cm->db.be_private = NULL;
2939         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2940         cm->qm = qm;
2941         cm->numattrsets = 0;
2942         cm->num_entries_limit = 5;
2943         cm->num_cached_queries = 0;
2944         cm->max_entries = 0;
2945         cm->cur_entries = 0;
2946         cm->max_queries = 10000;
2947         cm->save_queries = 0;
2948         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2949         cm->cc_period = 1000;
2950         cm->cc_paused = 0;
2951
2952         qm->attr_sets = NULL;
2953         qm->templates = NULL;
2954         qm->lru_top = NULL;
2955         qm->lru_bottom = NULL;
2956
2957         qm->qcfunc = query_containment;
2958         qm->crfunc = cache_replacement;
2959         qm->addfunc = add_query;
2960         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2961
2962         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2963         return 0;
2964 }
2965
2966 static int
2967 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2968 {
2969         assert( op->o_tag == LDAP_REQ_SEARCH );
2970
2971         if ( rs->sr_type == REP_SEARCH ) {
2972                 Attribute       *a;
2973
2974                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2975                 if ( a != NULL ) {
2976                         BerVarray       *valsp;
2977
2978                         assert( a->a_nvals != NULL );
2979
2980                         valsp = op->o_callback->sc_private;
2981                         assert( *valsp == NULL );
2982
2983                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2984                 }
2985         }
2986
2987         return 0;
2988 }
2989
2990 static int
2991 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
2992 {
2993         assert( op->o_tag == LDAP_REQ_SEARCH );
2994
2995         if ( rs->sr_type == REP_SEARCH ) {
2996                 int     *countp = (int *)op->o_callback->sc_private;
2997
2998                 (*countp)++;
2999         }
3000
3001         return 0;
3002 }
3003
3004 static int
3005 pcache_db_open(
3006         BackendDB *be,
3007         ConfigReply *cr )
3008 {
3009         slap_overinst   *on = (slap_overinst *)be->bd_info;
3010         cache_manager   *cm = on->on_bi.bi_private;
3011         query_manager*  qm = cm->qm;
3012         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3013
3014         /* check attr sets */
3015         for ( i = 0; i < cm->numattrsets; i++) {
3016                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3017                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3018                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3019                                 rf++;
3020
3021                         } else {
3022                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3023                         }
3024                         ncf++;
3025
3026                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3027                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3028                         nrf++;
3029                 }
3030         }
3031
3032         if ( ncf || rf || nrf ) {
3033                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3034                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3035                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3036
3037                 if ( rf > 0 ) {
3038                         return 1;
3039                 }
3040         }
3041
3042         /* need to inherit something from the original database... */
3043         cm->db.be_def_limit = be->be_def_limit;
3044         cm->db.be_limits = be->be_limits;
3045         cm->db.be_acl = be->be_acl;
3046         cm->db.be_dfltaccess = be->be_dfltaccess;
3047
3048         if ( SLAP_DBMONITORING( be ) ) {
3049                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3050
3051         } else {
3052                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3053         }
3054
3055         rc = backend_startup_one( &cm->db, NULL );
3056
3057         /* There is no runqueue in TOOL mode */
3058         if ( slapMode & SLAP_SERVER_MODE ) {
3059                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3060                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3061                         consistency_check, on,
3062                         "pcache_consistency", be->be_suffix[0].bv_val );
3063                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3064
3065                 /* Cached database must have the rootdn */
3066                 if ( BER_BVISNULL( &cm->db.be_rootndn )
3067                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3068                 {
3069                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3070                                 "underlying database of type \"%s\"\n"
3071                                 "    serving naming context \"%s\"\n"
3072                                 "    has no \"rootdn\", required by \"proxycache\".\n",
3073                                 on->on_info->oi_orig->bi_type,
3074                                 cm->db.be_suffix[0].bv_val, 0 );
3075                         return 1;
3076                 }
3077
3078                 if ( cm->save_queries ) {
3079                         void            *thrctx = ldap_pvt_thread_pool_context();
3080                         Connection      conn = { 0 };
3081                         OperationBuffer opbuf;
3082                         Operation       *op;
3083                         slap_callback   cb = { 0 };
3084                         SlapReply       rs = { 0 };
3085                         BerVarray       vals = NULL;
3086                         Filter          f = { 0 }, f2 = { 0 };
3087 #ifdef LDAP_COMP_MATCH
3088                         AttributeAssertion      ava = { NULL, BER_BVNULL, NULL };
3089 #else
3090                         AttributeAssertion      ava = { NULL, BER_BVNULL };
3091 #endif
3092                         AttributeName   attrs[ 2 ] = { 0 };
3093
3094                         connection_fake_init( &conn, &opbuf, thrctx );
3095                         op = &opbuf.ob_op;
3096
3097                         op->o_bd = &cm->db;
3098
3099                         op->o_tag = LDAP_REQ_SEARCH;
3100                         op->o_protocol = LDAP_VERSION3;
3101                         cb.sc_response = pcache_cachedquery_open_cb;
3102                         cb.sc_private = &vals;
3103                         op->o_callback = &cb;
3104                         op->o_time = slap_get_time();
3105                         op->o_do_not_cache = 1;
3106                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
3107
3108                         op->o_dn = cm->db.be_rootdn;
3109                         op->o_ndn = cm->db.be_rootndn;
3110                         op->o_req_dn = cm->db.be_suffix[ 0 ];
3111                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3112
3113                         op->ors_scope = LDAP_SCOPE_BASE;
3114                         op->ors_deref = LDAP_DEREF_NEVER;
3115                         op->ors_slimit = 1;
3116                         op->ors_tlimit = SLAP_NO_LIMIT;
3117                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3118                         f.f_choice = LDAP_FILTER_PRESENT;
3119                         f.f_desc = ad_cachedQueryURL;
3120                         op->ors_filter = &f;
3121                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
3122                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3123                         op->ors_attrs = attrs;
3124                         op->ors_attrsonly = 0;
3125
3126                         rc = op->o_bd->be_search( op, &rs );
3127                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
3128                                 int     i;
3129
3130                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3131                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3132                                                 cm->num_cached_queries++;
3133                                         }
3134                                 }
3135
3136                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3137                         }
3138
3139                         /* count cached entries */
3140                         f.f_choice = LDAP_FILTER_NOT;
3141                         f.f_not = &f2;
3142                         f2.f_choice = LDAP_FILTER_EQUALITY;
3143                         f2.f_ava = &ava;
3144                         f2.f_av_desc = slap_schema.si_ad_objectClass;
3145                         BER_BVSTR( &f2.f_av_value, "glue" );
3146                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3147
3148                         op->ors_slimit = SLAP_NO_LIMIT;
3149                         op->ors_scope = LDAP_SCOPE_SUBTREE;
3150                         op->ors_attrs = slap_anlist_no_attrs;
3151
3152                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
3153                         rs.sr_nentries = 0;
3154                         op->o_callback->sc_private = &rs.sr_nentries;
3155
3156                         rc = op->o_bd->be_search( op, &rs );
3157
3158                         cm->cur_entries = rs.sr_nentries;
3159
3160                         /* ignore errors */
3161                         rc = 0;
3162                 }
3163         }
3164
3165         return rc;
3166 }
3167
3168 static void
3169 pcache_free_qbase( void *v )
3170 {
3171         Qbase *qb = v;
3172         int i;
3173
3174         for (i=0; i<3; i++)
3175                 tavl_free( qb->scopes[i], NULL );
3176         ch_free( qb );
3177 }
3178
3179 static int
3180 pcache_db_close(
3181         BackendDB *be,
3182         ConfigReply *cr
3183 )
3184 {
3185         slap_overinst *on = (slap_overinst *)be->bd_info;
3186         cache_manager *cm = on->on_bi.bi_private;
3187         query_manager *qm = cm->qm;
3188         QueryTemplate *tm;
3189         int i, rc = 0;
3190
3191         if ( cm->save_queries ) {
3192                 CachedQuery     *qc;
3193                 BerVarray       vals = NULL;
3194
3195                 void            *thrctx;
3196                 Connection      conn = { 0 };
3197                 OperationBuffer opbuf;
3198                 Operation       *op;
3199                 slap_callback   cb = { 0 };
3200
3201                 SlapReply       rs = { REP_RESULT };
3202                 Modifications   mod = { 0 };
3203
3204                 thrctx = ldap_pvt_thread_pool_context();
3205
3206                 connection_fake_init( &conn, &opbuf, thrctx );
3207                 op = &opbuf.ob_op;
3208
3209                 if ( qm->templates != NULL ) {
3210                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3211                                 for ( qc = tm->query; qc; qc = qc->next ) {
3212                                         struct berval   bv;
3213
3214                                         if ( query2url( op, qc, &bv ) == 0 ) {
3215                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3216                                         }
3217                                 }
3218                         }
3219                 }
3220
3221                 op->o_bd = &cm->db;
3222                 op->o_dn = cm->db.be_rootdn;
3223                 op->o_ndn = cm->db.be_rootndn;
3224
3225                 op->o_tag = LDAP_REQ_MODIFY;
3226                 op->o_protocol = LDAP_VERSION3;
3227                 cb.sc_response = slap_null_cb;
3228                 op->o_callback = &cb;
3229                 op->o_time = slap_get_time();
3230                 op->o_do_not_cache = 1;
3231                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3232
3233                 op->o_req_dn = op->o_bd->be_suffix[0];
3234                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3235
3236                 mod.sml_op = LDAP_MOD_REPLACE;
3237                 mod.sml_flags = 0;
3238                 mod.sml_desc = ad_cachedQueryURL;
3239                 mod.sml_type = ad_cachedQueryURL->ad_cname;
3240                 mod.sml_values = vals;
3241                 mod.sml_nvalues = NULL;
3242                 mod.sml_next = NULL;
3243                 Debug( pcache_debug,
3244                         "%sSETTING CACHED QUERY URLS\n",
3245                         vals == NULL ? "RE" : "", 0, 0 );
3246
3247                 op->orm_modlist = &mod;
3248
3249                 op->o_bd->be_modify( op, &rs );
3250
3251                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3252         }
3253
3254         /* cleanup stuff inherited from the original database... */
3255         cm->db.be_limits = NULL;
3256         cm->db.be_acl = NULL;
3257
3258         /* stop the thread ... */
3259         if ( cm->cc_arg ) {
3260                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3261                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3262                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3263                 }
3264                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3265                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3266         }
3267
3268         if ( cm->db.bd_info->bi_db_close ) {
3269                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3270         }
3271         while ( (tm = qm->templates) != NULL ) {
3272                 CachedQuery *qc, *qn;
3273                 qm->templates = tm->qmnext;
3274                 for ( qc = tm->query; qc; qc = qn ) {
3275                         qn = qc->next;
3276                         free_query( qc );
3277                 }
3278                 avl_free( tm->qbase, pcache_free_qbase );
3279                 free( tm->querystr.bv_val );
3280                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3281                 free( tm->t_attrs.attrs );
3282                 free( tm );
3283         }
3284
3285         for ( i=0; i<cm->numattrsets; i++ ) {
3286                 free( qm->attr_sets[i].attrs );
3287         }
3288         free( qm->attr_sets );
3289         qm->attr_sets = NULL;
3290
3291         return rc;
3292 }
3293
3294 static int
3295 pcache_db_destroy(
3296         BackendDB *be,
3297         ConfigReply *cr
3298 )
3299 {
3300         slap_overinst *on = (slap_overinst *)be->bd_info;
3301         cache_manager *cm = on->on_bi.bi_private;
3302         query_manager *qm = cm->qm;
3303
3304         if ( cm->db.be_private != NULL ) {
3305                 backend_stopdown_one( &cm->db );
3306         }
3307
3308         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3309         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3310         free( qm );
3311         free( cm );
3312
3313         return 0;
3314 }
3315
3316 #ifdef PCACHE_CONTROL_PRIVDB
3317 /*
3318         Control ::= SEQUENCE {
3319              controlType             LDAPOID,
3320              criticality             BOOLEAN DEFAULT FALSE,
3321              controlValue            OCTET STRING OPTIONAL }
3322
3323         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3324
3325  * criticality must be TRUE; controlValue must be absent.
3326  */
3327 static int
3328 parse_privdb_ctrl(
3329         Operation       *op,
3330         SlapReply       *rs,
3331         LDAPControl     *ctrl )
3332 {
3333         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3334                 rs->sr_text = "privateDB control specified multiple times";
3335                 return LDAP_PROTOCOL_ERROR;
3336         }
3337
3338         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3339                 rs->sr_text = "privateDB control value not absent";
3340                 return LDAP_PROTOCOL_ERROR;
3341         }
3342
3343         if ( !ctrl->ldctl_iscritical ) {
3344                 rs->sr_text = "privateDB control criticality required";
3345                 return LDAP_PROTOCOL_ERROR;
3346         }
3347
3348         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3349
3350         return LDAP_SUCCESS;
3351 }
3352
3353 static char *extops[] = {
3354         LDAP_EXOP_MODIFY_PASSWD,
3355         NULL
3356 };
3357 #endif /* PCACHE_CONTROL_PRIVDB */
3358
3359 #ifdef PCACHE_EXOP_QUERY_DELETE
3360 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3361
3362 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3363 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3364 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3365
3366 /*
3367         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3368              requestName      [0] LDAPOID,
3369              requestValue     [1] OCTET STRING OPTIONAL }
3370
3371         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3372
3373         requestValue ::= SEQUENCE { CHOICE {
3374                   baseDN           [0] LDAPDN
3375                   entryDN          [1] LDAPDN },
3376              queryID          [2] OCTET STRING (SIZE(16))
3377                   -- constrained to UUID }
3378
3379  * Either baseDN or entryDN must be present, to allow database selection.
3380  *
3381  * 1. if baseDN and queryID are present, then the query corresponding
3382  *    to queryID is deleted;
3383  * 2. if baseDN is present and queryID is absent, then all queries
3384  *    are deleted;
3385  * 3. if entryDN is present and queryID is absent, then all queries
3386  *    corresponding to the queryID values present in entryDN are deleted;
3387  * 4. if entryDN and queryID are present, then all queries
3388  *    corresponding to the queryID values present in entryDN are deleted,
3389  *    but only if the value of queryID is contained in the entry;
3390  *
3391  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
3392  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3393  * or by removing the database files.
3394
3395         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3396              COMPONENTS OF LDAPResult,
3397              responseName     [10] LDAPOID OPTIONAL,
3398              responseValue    [11] OCTET STRING OPTIONAL }
3399
3400  * responseName and responseValue must be absent.
3401  */
3402
3403 /*
3404  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3405  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3406  * - if ndn != NULL, it is set to the normalized DN in the request
3407  *   corresponding to either the baseDN or the entryDN, according
3408  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
3409  *   be freed by the caller.
3410  * - if uuid != NULL, it is set to point to the normalized UUID;
3411  *   memory is malloc'ed on the Operation's slab, and must
3412  *   be freed by the caller.
3413  */
3414 static int
3415 pcache_parse_query_delete(
3416         struct berval   *in,
3417         ber_tag_t       *tagp,
3418         struct berval   *ndn,
3419         struct berval   *uuid,
3420         const char      **text,
3421         void            *ctx )
3422 {
3423         int                     rc = LDAP_SUCCESS;
3424         ber_tag_t               tag;
3425         ber_len_t               len = -1;
3426         BerElementBuffer        berbuf;
3427         BerElement              *ber = (BerElement *)&berbuf;
3428         struct berval           reqdata = BER_BVNULL;
3429
3430         *text = NULL;
3431
3432         if ( ndn ) {
3433                 BER_BVZERO( ndn );
3434         }
3435
3436         if ( uuid ) {
3437                 BER_BVZERO( uuid );
3438         }
3439
3440         if ( in == NULL || in->bv_len == 0 ) {
3441                 *text = "empty request data field in queryDelete exop";
3442                 return LDAP_PROTOCOL_ERROR;
3443         }
3444
3445         ber_dupbv_x( &reqdata, in, ctx );
3446
3447         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3448         ber_init2( ber, &reqdata, 0 );
3449
3450         tag = ber_scanf( ber, "{" /*}*/ );
3451
3452         if ( tag == LBER_ERROR ) {
3453                 Debug( LDAP_DEBUG_TRACE,
3454                         "pcache_parse_query_delete: decoding error.\n",
3455                         0, 0, 0 );
3456                 goto decoding_error;
3457         }
3458
3459         tag = ber_peek_tag( ber, &len );
3460         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3461                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3462         {
3463                 *tagp = tag;
3464
3465                 if ( ndn != NULL ) {
3466                         struct berval   dn;
3467
3468                         tag = ber_scanf( ber, "m", &dn );
3469                         if ( tag == LBER_ERROR ) {
3470                                 Debug( LDAP_DEBUG_TRACE,
3471                                         "pcache_parse_query_delete: DN parse failed.\n",
3472                                         0, 0, 0 );
3473                                 goto decoding_error;
3474                         }
3475
3476                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3477                         if ( rc != LDAP_SUCCESS ) {
3478                                 *text = "invalid DN in queryDelete exop request data";
3479                                 goto done;
3480                         }
3481
3482                 } else {
3483                         tag = ber_scanf( ber, "x" /* "m" */ );
3484                         if ( tag == LBER_DEFAULT ) {
3485                                 goto decoding_error;
3486                         }
3487                 }
3488
3489                 tag = ber_peek_tag( ber, &len );
3490         }
3491
3492         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3493                 if ( uuid != NULL ) {
3494                         struct berval   bv;
3495                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3496
3497                         tag = ber_scanf( ber, "m", &bv );
3498                         if ( tag == LBER_ERROR ) {
3499                                 Debug( LDAP_DEBUG_TRACE,
3500                                         "pcache_parse_query_delete: UUID parse failed.\n",
3501                                         0, 0, 0 );
3502                                 goto decoding_error;
3503                         }
3504
3505                         if ( bv.bv_len != 16 ) {
3506                                 Debug( LDAP_DEBUG_TRACE,
3507                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3508                                         (unsigned long)bv.bv_len, 0, 0 );
3509                                 goto decoding_error;
3510                         }
3511
3512                         rc = lutil_uuidstr_from_normalized(
3513                                 bv.bv_val, bv.bv_len,
3514                                 uuidbuf, sizeof( uuidbuf ) );
3515                         if ( rc == -1 ) {
3516                                 goto decoding_error;
3517                         }
3518                         ber_str2bv( uuidbuf, rc, 1, uuid );
3519                         rc = LDAP_SUCCESS;
3520
3521                 } else {
3522                         tag = ber_skip_tag( ber, &len );
3523                         if ( tag == LBER_DEFAULT ) {
3524                                 goto decoding_error;
3525                         }
3526
3527                         if ( len != 16 ) {
3528                                 Debug( LDAP_DEBUG_TRACE,
3529                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3530                                         (unsigned long)len, 0, 0 );
3531                                 goto decoding_error;
3532                         }
3533                 }
3534
3535                 tag = ber_peek_tag( ber, &len );
3536         }
3537
3538         if ( tag != LBER_DEFAULT || len != 0 ) {
3539 decoding_error:;
3540                 Debug( LDAP_DEBUG_TRACE,
3541                         "pcache_parse_query_delete: decoding error\n",
3542                         0, 0, 0 );
3543                 rc = LDAP_PROTOCOL_ERROR;
3544                 *text = "queryDelete data decoding error";
3545
3546 done:;
3547                 if ( ndn && !BER_BVISNULL( ndn ) ) {
3548                         slap_sl_free( ndn->bv_val, ctx );
3549                         BER_BVZERO( ndn );
3550                 }
3551
3552                 if ( uuid && !BER_BVISNULL( uuid ) ) {
3553                         slap_sl_free( uuid->bv_val, ctx );
3554                         BER_BVZERO( uuid );
3555                 }
3556         }
3557
3558         if ( !BER_BVISNULL( &reqdata ) ) {
3559                 ber_memfree_x( reqdata.bv_val, ctx );
3560         }
3561
3562         return rc;
3563 }
3564
3565 static int
3566 pcache_exop_query_delete(
3567         Operation       *op,
3568         SlapReply       *rs )
3569 {
3570         BackendDB       *bd = op->o_bd;
3571
3572         struct berval   uuid = BER_BVNULL,
3573                         *uuidp = NULL;
3574         char            buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3575         int             len = 0;
3576         ber_tag_t       tag = LBER_DEFAULT;
3577
3578         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3579                 uuidp = &uuid;
3580         }
3581
3582         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3583                 &tag, &op->o_req_ndn, uuidp,
3584                 &rs->sr_text, op->o_tmpmemctx );
3585         if ( rs->sr_err != LDAP_SUCCESS ) {
3586                 return rs->sr_err;
3587         }
3588
3589         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3590                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3591                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3592
3593                 if ( !BER_BVISNULL( &uuid ) ) {
3594                         snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3595                 }
3596
3597                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3598                         op->o_log_prefix, buf, 0 );
3599         }
3600         op->o_req_dn = op->o_req_ndn;
3601
3602         op->o_bd = select_backend( &op->o_req_ndn, 0 );
3603         rs->sr_err = backend_check_restrictions( op, rs,
3604                 (struct berval *)&pcache_exop_QUERY_DELETE );
3605         if ( rs->sr_err != LDAP_SUCCESS ) {
3606                 goto done;
3607         }
3608
3609         if ( op->o_bd->be_extended == NULL ) {
3610                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3611                         "backend does not support extended operations" );
3612                 goto done;
3613         }
3614
3615         op->o_bd->be_extended( op, rs );
3616
3617 done:;
3618         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3619                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3620                 BER_BVZERO( &op->o_req_ndn );
3621                 BER_BVZERO( &op->o_req_dn );
3622         }
3623
3624         if ( !BER_BVISNULL( &uuid ) ) {
3625                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3626         }
3627
3628         op->o_bd = bd;
3629
3630         return rs->sr_err;
3631 }
3632
3633 static int
3634 pcache_op_extended( Operation *op, SlapReply *rs )
3635 {
3636         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
3637         cache_manager   *cm = on->on_bi.bi_private;
3638
3639 #ifdef PCACHE_CONTROL_PRIVDB
3640         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3641                 return pcache_op_privdb( op, rs );
3642         }
3643 #endif /* PCACHE_CONTROL_PRIVDB */
3644
3645         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3646                 struct berval   uuid = BER_BVNULL;
3647                 ber_tag_t       tag = LBER_DEFAULT;
3648
3649                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3650                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3651                 assert( rs->sr_err == LDAP_SUCCESS );
3652
3653                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3654                         /* remove all queries related to the selected entry */
3655                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3656                                 cm, &op->o_req_ndn, &uuid );
3657
3658                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3659                         if ( !BER_BVISNULL( &uuid ) ) {
3660                                 /* remove the selected query */
3661                                 rs->sr_err = pcache_remove_query_from_cache( op,
3662                                         cm, &uuid );
3663
3664                         } else {
3665                                 /* TODO: remove all queries */
3666                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3667                                 rs->sr_text = "deletion of all queries not implemented";
3668                         }
3669                 }
3670
3671                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3672         }
3673
3674         return rs->sr_err;
3675 }
3676 #endif /* PCACHE_EXOP_QUERY_DELETE */
3677
3678 static slap_overinst pcache;
3679
3680 static char *obsolete_names[] = {
3681         "proxycache",
3682         NULL
3683 };
3684
3685 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3686 static
3687 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3688 int
3689 pcache_initialize()
3690 {
3691         int i, code;
3692         struct berval debugbv = BER_BVC("pcache");
3693
3694         code = slap_loglevel_get( &debugbv, &pcache_debug );
3695         if ( code ) {
3696                 return code;
3697         }
3698
3699 #ifdef PCACHE_CONTROL_PRIVDB
3700         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3701                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3702                 parse_privdb_ctrl, &privDB_cid );
3703         if ( code != LDAP_SUCCESS ) {
3704                 Debug( LDAP_DEBUG_ANY,
3705                         "pcache_initialize: failed to register control %s (%d)\n",
3706                         PCACHE_CONTROL_PRIVDB, code, 0 );
3707                 return code;
3708         }
3709 #endif /* PCACHE_CONTROL_PRIVDB */
3710
3711 #ifdef PCACHE_EXOP_QUERY_DELETE
3712         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3713                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3714                 0 );
3715         if ( code != LDAP_SUCCESS ) {
3716                 Debug( LDAP_DEBUG_ANY,
3717                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
3718                         code, 0, 0 );
3719                 return code;
3720         }
3721 #endif /* PCACHE_EXOP_QUERY_DELETE */
3722
3723         for ( i = 0; as[i].desc != NULL; i++ ) {
3724                 code = register_at( as[i].desc, as[i].adp, 0 );
3725                 if ( code ) {
3726                         Debug( LDAP_DEBUG_ANY,
3727                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3728                         return code;
3729                 }
3730         }
3731
3732         pcache.on_bi.bi_type = "pcache";
3733         pcache.on_bi.bi_obsolete_names = obsolete_names;
3734         pcache.on_bi.bi_db_init = pcache_db_init;
3735         pcache.on_bi.bi_db_config = pcache_db_config;
3736         pcache.on_bi.bi_db_open = pcache_db_open;
3737         pcache.on_bi.bi_db_close = pcache_db_close;
3738         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3739
3740         pcache.on_bi.bi_op_search = pcache_op_search;
3741 #ifdef PCACHE_CONTROL_PRIVDB
3742         pcache.on_bi.bi_op_bind = pcache_op_privdb;
3743         pcache.on_bi.bi_op_compare = pcache_op_privdb;
3744         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3745         pcache.on_bi.bi_op_modify = pcache_op_privdb;
3746         pcache.on_bi.bi_op_add = pcache_op_privdb;
3747         pcache.on_bi.bi_op_delete = pcache_op_privdb;
3748 #endif /* PCACHE_CONTROL_PRIVDB */
3749 #ifdef PCACHE_EXOP_QUERY_DELETE
3750         pcache.on_bi.bi_extended = pcache_op_extended;
3751 #elif defined( PCACHE_CONTROL_PRIVDB )
3752         pcache.on_bi.bi_extended = pcache_op_privdb;
3753 #endif
3754
3755         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3756
3757         pcache.on_bi.bi_cf_ocs = pcocs;
3758
3759         code = config_register_schema( pccfg, pcocs );
3760         if ( code ) return code;
3761
3762         return overlay_register( &pcache );
3763 }
3764
3765 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3766 int init_module(int argc, char *argv[]) {
3767         return pcache_initialize();
3768 }
3769 #endif
3770
3771 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */