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