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