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