]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
cleanup (related to ITS#5760)
[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 && 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                         if ( si->count < si->max ) {
1997                                 si->count++;
1998                                 e = entry_dup( rs->sr_entry );
1999                                 if ( !si->head ) si->head = e;
2000                                 if ( si->tail ) si->tail->e_private = e;
2001                                 si->tail = e;
2002
2003                         } else {
2004 over:;
2005                                 si->over = 1;
2006                                 si->count = 0;
2007                                 for (;si->head; si->head=e) {
2008                                         e = si->head->e_private;
2009                                         si->head->e_private = NULL;
2010                                         entry_free(si->head);
2011                                 }
2012                                 si->tail = NULL;
2013                         }
2014                 }
2015
2016         }
2017
2018         if ( rs->sr_type == REP_RESULT || 
2019                 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2020         {
2021                 if ( si->swap_saved_attrs ) {
2022                         rs->sr_attrs = si->save_attrs;
2023                         op->ors_attrs = si->save_attrs;
2024                 }
2025                 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) && 
2026                                 si->caching_reason == PC_IGNORE ) {
2027                         filter_free( si->query.filter );
2028                         if ( si->count ) {
2029                                 /* duplicate query, free it */
2030                                 Entry *e;
2031                                 for (;si->head; si->head=e) {
2032                                         e = si->head->e_private;
2033                                         si->head->e_private = NULL;
2034                                         entry_free(si->head);
2035                                 }
2036                         }
2037                         op->o_callback = op->o_callback->sc_next;
2038                         op->o_tmpfree( cb, op->o_tmpmemctx );
2039                 } else if ( si->caching_reason != PC_IGNORE ) {
2040                         CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2041                                 si->qtemp, si->caching_reason, 1 );
2042
2043                         if ( qc != NULL ) {
2044                                 switch ( si->caching_reason ) {
2045                                 case PC_POSITIVE:
2046                                         cache_entries( op, rs, &qc->q_uuid );
2047                                         break;
2048
2049                                 case PC_SIZELIMIT:
2050                                         qc->q_sizelimit = rs->sr_nentries;
2051                                         break;
2052
2053                                 case PC_NEGATIVE:
2054                                         break;
2055
2056                                 default:
2057                                         assert( 0 );
2058                                         break;
2059                                 }
2060                                 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2061                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2062                                 cm->num_cached_queries++;
2063                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2064                                                 cm->num_cached_queries, 0, 0 );
2065                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2066
2067                                 /* If the consistency checker suspended itself,
2068                                  * wake it back up
2069                                  */
2070                                 if ( cm->cc_paused ) {
2071                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2072                                         if ( cm->cc_paused ) {
2073                                                 cm->cc_paused = 0;
2074                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2075                                         }
2076                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2077                                 }
2078
2079                         } else if ( si->count ) {
2080                                 /* duplicate query, free it */
2081                                 Entry *e;
2082                                 for (;si->head; si->head=e) {
2083                                         e = si->head->e_private;
2084                                         si->head->e_private = NULL;
2085                                         entry_free(si->head);
2086                                 }
2087                         }
2088
2089                 } else {
2090                         filter_free( si->query.filter );
2091                 }
2092         }
2093
2094         return SLAP_CB_CONTINUE;
2095 }
2096
2097 static int
2098 pcache_response(
2099         Operation       *op,
2100         SlapReply       *rs )
2101 {
2102         struct search_info *si = op->o_callback->sc_private;
2103
2104         if ( si->swap_saved_attrs ) {
2105                 rs->sr_attrs = si->save_attrs;
2106                 op->ors_attrs = si->save_attrs;
2107         }
2108
2109         if ( rs->sr_type == REP_SEARCH ) {
2110                 /* don't return more entries than requested by the client */
2111                 if ( si->slimit_exceeded ) {
2112                         return 0;
2113                 }
2114
2115         } else if ( rs->sr_type == REP_RESULT ) {
2116
2117                 if ( si->count ) {
2118                         if ( rs->sr_err == LDAP_SUCCESS ) {
2119                                 si->caching_reason = PC_POSITIVE;
2120
2121                         } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2122                                 && si->qtemp->limitttl )
2123                         {
2124                                 si->caching_reason = PC_SIZELIMIT;
2125                         }
2126
2127                 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2128                                 rs->sr_err == LDAP_SUCCESS )
2129                 {
2130                         si->caching_reason = PC_NEGATIVE;
2131                 }
2132
2133
2134                 if ( si->slimit_exceeded ) {
2135                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2136                 }
2137         }
2138
2139         return SLAP_CB_CONTINUE;
2140 }
2141
2142 static int
2143 add_filter_attrs(
2144         Operation *op,
2145         AttributeName** new_attrs,
2146         struct attr_set *attrs,
2147         AttributeName* filter_attrs,
2148         int fattr_cnt,
2149         int fattr_got_oc)
2150 {
2151         int alluser = 0;
2152         int allop = 0;
2153         int i, j;
2154         int count;
2155         int addoc = 0;
2156
2157         /* duplicate attrs */
2158         count = attrs->count + fattr_cnt;
2159         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2160                 addoc = 1;
2161                 count++;
2162         }
2163
2164         *new_attrs = (AttributeName*)ch_calloc( count + 1,
2165                 sizeof(AttributeName) );
2166         for (i=0; i<attrs->count; i++) {
2167                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2168                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2169         }
2170         BER_BVZERO( &(*new_attrs)[i].an_name );
2171         alluser = an_find( *new_attrs, slap_bv_all_user_attrs );
2172         allop = an_find( *new_attrs, slap_bv_all_operational_attrs );
2173
2174         j = i;
2175         for ( i=0; i<fattr_cnt; i++ ) {
2176                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2177                         continue;
2178                 }
2179                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2180                         if ( allop ) {
2181                                 continue;
2182                         }
2183                 } else if ( alluser ) {
2184                         continue;
2185                 }
2186                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2187                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2188                 (*new_attrs)[j].an_oc = NULL;
2189                 (*new_attrs)[j].an_oc_exclude = 0;
2190                 j++;
2191         }
2192         if ( addoc ) {
2193                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2194                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2195                 (*new_attrs)[j].an_oc = NULL;
2196                 (*new_attrs)[j].an_oc_exclude = 0;
2197                 j++;
2198         }
2199         BER_BVZERO( &(*new_attrs)[j].an_name );
2200
2201         return j;
2202 }
2203
2204 /* NOTE: this is a quick workaround to let pcache minimally interact
2205  * with pagedResults.  A more articulated solutions would be to
2206  * perform the remote query without control and cache all results,
2207  * performing the pagedResults search only within the client
2208  * and the proxy.  This requires pcache to understand pagedResults. */
2209 static int
2210 pcache_chk_controls(
2211         Operation       *op,
2212         SlapReply       *rs )
2213 {
2214         const char      *non = "";
2215         const char      *stripped = "";
2216
2217         switch( op->o_pagedresults ) {
2218         case SLAP_CONTROL_NONCRITICAL:
2219                 non = "non-";
2220                 stripped = "; stripped";
2221                 /* fallthru */
2222
2223         case SLAP_CONTROL_CRITICAL:
2224                 Debug( pcache_debug, "%s: "
2225                         "%scritical pagedResults control "
2226                         "disabled with proxy cache%s.\n",
2227                         op->o_log_prefix, non, stripped );
2228                 
2229                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2230                 break;
2231
2232         default:
2233                 rs->sr_err = SLAP_CB_CONTINUE;
2234                 break;
2235         }
2236
2237         return rs->sr_err;
2238 }
2239
2240 #ifdef PCACHE_CONTROL_PRIVDB
2241 static int
2242 pcache_op_privdb(
2243         Operation               *op,
2244         SlapReply               *rs )
2245 {
2246         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
2247         cache_manager   *cm = on->on_bi.bi_private;
2248         slap_callback   *save_cb;
2249         slap_op_t       type;
2250
2251         /* skip if control is unset */
2252         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2253                 return SLAP_CB_CONTINUE;
2254         }
2255
2256         /* The cache DB isn't open yet */
2257         if ( cm->defer_db_open ) {
2258                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2259                         "pcachePrivDB: cacheDB not available" );
2260                 return rs->sr_err;
2261         }
2262
2263         /* FIXME: might be a little bit exaggerated... */
2264         if ( !be_isroot( op ) ) {
2265                 save_cb = op->o_callback;
2266                 op->o_callback = NULL;
2267                 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2268                         "pcachePrivDB: operation not allowed" );
2269                 op->o_callback = save_cb;
2270
2271                 return rs->sr_err;
2272         }
2273
2274         /* map tag to operation */
2275         type = slap_req2op( op->o_tag );
2276         if ( type != SLAP_OP_LAST ) {
2277                 BI_op_func      **func;
2278                 int             rc;
2279
2280                 /* execute, if possible */
2281                 func = &cm->db.be_bind;
2282                 if ( func[ type ] != NULL ) {
2283                         Operation       op2 = *op;
2284         
2285                         op2.o_bd = &cm->db;
2286
2287                         rc = func[ type ]( &op2, rs );
2288                         if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2289                                 op->o_conn->c_authz_cookie = cm->db.be_private;
2290                         }
2291                 }
2292         }
2293
2294         /* otherwise fall back to error */
2295         save_cb = op->o_callback;
2296         op->o_callback = NULL;
2297         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2298                 "operation not supported with pcachePrivDB control" );
2299         op->o_callback = save_cb;
2300
2301         return rs->sr_err;
2302 }
2303 #endif /* PCACHE_CONTROL_PRIVDB */
2304
2305 static int
2306 pcache_op_search(
2307         Operation       *op,
2308         SlapReply       *rs )
2309 {
2310         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2311         cache_manager *cm = on->on_bi.bi_private;
2312         query_manager*          qm = cm->qm;
2313
2314         int i = -1;
2315
2316         AttributeName   *filter_attrs = NULL;
2317
2318         Query           query;
2319         QueryTemplate   *qtemp = NULL;
2320
2321         int             attr_set = -1;
2322         CachedQuery     *answerable = NULL;
2323         int             cacheable = 0;
2324         int             fattr_cnt=0;
2325         int             fattr_got_oc = 0;
2326
2327         struct berval   tempstr;
2328
2329 #ifdef PCACHE_CONTROL_PRIVDB
2330         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2331                 return pcache_op_privdb( op, rs );
2332         }
2333 #endif /* PCACHE_CONTROL_PRIVDB */
2334
2335         /* The cache DB isn't open yet */
2336         if ( cm->defer_db_open ) {
2337                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2338                         "pcachePrivDB: cacheDB not available" );
2339                 return rs->sr_err;
2340         }
2341
2342         /* pickup runtime ACL changes */
2343         cm->db.be_acl = op->o_bd->be_acl;
2344
2345         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2346         tempstr.bv_len = 0;
2347         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2348                 &fattr_cnt, &fattr_got_oc )) {
2349                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2350                 return SLAP_CB_CONTINUE;
2351         }
2352
2353         Debug( pcache_debug, "query template of incoming query = %s\n",
2354                                         tempstr.bv_val, 0, 0 );
2355
2356         /* FIXME: cannot cache/answer requests with pagedResults control */
2357
2358         /* find attr set */
2359         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2360
2361         query.filter = op->ors_filter;
2362         query.base = op->o_req_ndn;
2363         query.scope = op->ors_scope;
2364
2365         /* check for query containment */
2366         if (attr_set > -1) {
2367                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2368                 for (; qt; qt = qt->qtnext ) {
2369                         /* find if template i can potentially answer tempstr */
2370                         if (qt->querystr.bv_len != tempstr.bv_len ||
2371                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2372                                 continue;
2373                         cacheable = 1;
2374                         qtemp = qt;
2375                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
2376                                         op->ors_filterstr.bv_val, 0, 0 );
2377                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2378
2379                         if (answerable)
2380                                 break;
2381                 }
2382         }
2383         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2384
2385         if (answerable) {
2386                 /* Need to clear the callbacks of the original operation,
2387                  * in case there are other overlays */
2388                 BackendDB       *save_bd = op->o_bd;
2389                 slap_callback   *save_cb = op->o_callback;
2390
2391                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2392                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2393                 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
2394                 if ( BER_BVISNULL( &answerable->q_uuid )) {
2395                         /* No entries cached, just an empty result set */
2396                         i = rs->sr_err = 0;
2397                         send_ldap_result( op, rs );
2398                 } else {
2399                         op->o_bd = &cm->db;
2400                         op->o_callback = NULL;
2401                         i = cm->db.bd_info->bi_op_search( op, rs );
2402                 }
2403                 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
2404                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2405                 op->o_bd = save_bd;
2406                 op->o_callback = save_cb;
2407                 return i;
2408         }
2409
2410         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2411
2412         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2413         if (cm->num_cached_queries >= cm->max_queries) {
2414                 cacheable = 0;
2415         }
2416         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2417
2418         if (op->ors_attrsonly)
2419                 cacheable = 0;
2420
2421         if (cacheable) {
2422                 slap_callback           *cb;
2423                 struct search_info      *si;
2424
2425                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2426                 query.filter = filter_dup(op->ors_filter, NULL);
2427                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2428                 if ( !qtemp->t_attrs.count ) {
2429                         qtemp->t_attrs.count = add_filter_attrs(op,
2430                                 &qtemp->t_attrs.attrs,
2431                                 &qm->attr_sets[attr_set],
2432                                 filter_attrs, fattr_cnt, fattr_got_oc);
2433                 }
2434                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2435
2436                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2437                 cb->sc_response = pcache_response;
2438                 cb->sc_cleanup = pcache_op_cleanup;
2439                 cb->sc_private = (cb+1);
2440                 si = cb->sc_private;
2441                 si->on = on;
2442                 si->query = query;
2443                 si->qtemp = qtemp;
2444                 si->max = cm->num_entries_limit ;
2445                 si->over = 0;
2446                 si->count = 0;
2447                 si->slimit = 0;
2448                 si->slimit_exceeded = 0;
2449                 si->caching_reason = PC_IGNORE;
2450                 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2451                         si->slimit = op->ors_slimit;
2452                         op->ors_slimit = cm->num_entries_limit;
2453                 }
2454                 si->head = NULL;
2455                 si->tail = NULL;
2456                 si->swap_saved_attrs = 1;
2457                 si->save_attrs = op->ors_attrs;
2458
2459                 op->ors_attrs = qtemp->t_attrs.attrs;
2460
2461                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2462                         cb->sc_next = op->o_callback;
2463                         op->o_callback = cb;
2464
2465                 } else {
2466                         slap_callback           **pcb;
2467
2468                         /* need to move the callback at the end, in case other
2469                          * overlays are present, so that the final entry is
2470                          * actually cached */
2471                         cb->sc_next = NULL;
2472                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2473                         *pcb = cb;
2474                 }
2475
2476         } else {
2477                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2478                                         0, 0, 0);
2479         }
2480
2481         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2482
2483         return SLAP_CB_CONTINUE;
2484 }
2485
2486 static int
2487 get_attr_set(
2488         AttributeName* attrs,
2489         query_manager* qm,
2490         int num )
2491 {
2492         int i;
2493         int count = 0;
2494
2495         if ( attrs ) {
2496                 for ( ; attrs[count].an_name.bv_val; count++ );
2497         }
2498
2499         /* recognize a single "*" or a "1.1" */
2500         if ( count == 0 ) {
2501                 count = 1;
2502                 attrs = slap_anlist_all_user_attributes;
2503
2504         } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2505                 count = 0;
2506                 attrs = NULL;
2507         }
2508
2509         for ( i = 0; i < num; i++ ) {
2510                 AttributeName *a2;
2511                 int found = 1;
2512
2513                 if ( count > qm->attr_sets[i].count ) {
2514                         continue;
2515                 }
2516
2517                 if ( !count ) {
2518                         if ( !qm->attr_sets[i].count ) {
2519                                 break;
2520                         }
2521                         continue;
2522                 }
2523
2524                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2525                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2526                                 found = 0;
2527                                 break;
2528                         }
2529                 }
2530
2531                 if ( found ) {
2532                         break;
2533                 }
2534         }
2535
2536         if ( i == num ) {
2537                 i = -1;
2538         }
2539
2540         return i;
2541 }
2542
2543 static void*
2544 consistency_check(
2545         void *ctx,
2546         void *arg )
2547 {
2548         struct re_s *rtask = arg;
2549         slap_overinst *on = rtask->arg;
2550         cache_manager *cm = on->on_bi.bi_private;
2551         query_manager *qm = cm->qm;
2552         Connection conn = {0};
2553         OperationBuffer opbuf;
2554         Operation *op;
2555
2556         SlapReply rs = {REP_RESULT};
2557         CachedQuery* query;
2558         int return_val, pause = 1;
2559         QueryTemplate* templ;
2560
2561         connection_fake_init( &conn, &opbuf, ctx );
2562         op = &opbuf.ob_op;
2563
2564         op->o_bd = &cm->db;
2565         op->o_dn = cm->db.be_rootdn;
2566         op->o_ndn = cm->db.be_rootndn;
2567
2568         cm->cc_arg = arg;
2569
2570         for (templ = qm->templates; templ; templ=templ->qmnext) {
2571                 query = templ->query_last;
2572                 if ( query ) pause = 0;
2573                 op->o_time = slap_get_time();
2574                 while (query && (query->expiry_time < op->o_time)) {
2575                         int rem = 0;
2576                         Debug( pcache_debug, "Lock CR index = %p\n",
2577                                         (void *) templ, 0, 0 );
2578                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2579                         if ( query == templ->query_last ) {
2580                                 rem = 1;
2581                                 remove_from_template(query, templ);
2582                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2583                                                 (void *) templ, templ->no_of_queries, 0 );
2584                                 Debug( pcache_debug, "Unlock CR index = %p\n",
2585                                                 (void *) templ, 0, 0 );
2586                         }
2587                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2588                         if ( !rem ) {
2589                                 query = templ->query_last;
2590                                 continue;
2591                         }
2592                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2593                         remove_query(qm, query);
2594                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2595                         if ( BER_BVISNULL( &query->q_uuid ))
2596                                 return_val = 0;
2597                         else
2598                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
2599                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2600                                                 return_val, 0, 0 );
2601                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2602                         cm->cur_entries -= return_val;
2603                         cm->num_cached_queries--;
2604                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
2605                                         cm->num_cached_queries, 0, 0 );
2606                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2607                         Debug( pcache_debug,
2608                                 "STALE QUERY REMOVED, CACHE ="
2609                                 "%d entries\n",
2610                                 cm->cur_entries, 0, 0 );
2611                         free_query(query);
2612                         query = templ->query_last;
2613                 }
2614         }
2615         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2616         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2617                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2618         }
2619         /* If there were no queries, defer processing for a while */
2620         cm->cc_paused = pause;
2621         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2622
2623         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2624         return NULL;
2625 }
2626
2627
2628 #define MAX_ATTR_SETS 500
2629
2630 enum {
2631         PC_MAIN = 1,
2632         PC_ATTR,
2633         PC_TEMP,
2634         PC_RESP,
2635         PC_QUERIES
2636 };
2637
2638 static ConfigDriver pc_cf_gen;
2639 static ConfigLDAPadd pc_ldadd;
2640 static ConfigCfAdd pc_cfadd;
2641
2642 static ConfigTable pccfg[] = {
2643         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2644                                 "<cycle_time",
2645                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2646                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2647                         "DESC 'ProxyCache basic parameters' "
2648                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2649         { "proxyattrset", "index> <attributes...",
2650                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2651                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2652                         "DESC 'A set of attributes to cache' "
2653                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2654         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2655                 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2656                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2657                         "DESC 'Filter template, attrset, cache TTL, "
2658                                 "optional negative TTL, optional sizelimit TTL' "
2659                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2660         { "response-callback", "head|tail(default)",
2661                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2662                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2663                         "DESC 'Response callback position in overlay stack' "
2664                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2665         { "proxyCacheQueries", "queries",
2666                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2667                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2668                         "DESC 'Maximum number of queries to cache' "
2669                         "SYNTAX OMsInteger )", NULL, NULL },
2670         { "proxySaveQueries", "TRUE|FALSE",
2671                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2672                 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2673                         "DESC 'Save cached queries for hot restart' "
2674                         "SYNTAX OMsBoolean )", NULL, NULL },
2675         { "proxyCheckCacheability", "TRUE|FALSE",
2676                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
2677                 "( OLcfgOvAt:2.7 NAME 'olcProxyCheckCacheability' "
2678                         "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
2679                         "SYNTAX OMsBoolean )", NULL, NULL },
2680
2681         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2682 };
2683
2684 static ConfigOCs pcocs[] = {
2685         { "( OLcfgOvOc:2.1 "
2686                 "NAME 'olcPcacheConfig' "
2687                 "DESC 'ProxyCache configuration' "
2688                 "SUP olcOverlayConfig "
2689                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2690                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries $ olcProxyCheckCacheability ) )",
2691                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2692         { "( OLcfgOvOc:2.2 "
2693                 "NAME 'olcPcacheDatabase' "
2694                 "DESC 'Cache database configuration' "
2695                 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
2696         { NULL, 0, NULL }
2697 };
2698
2699 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
2700
2701 static int
2702 pc_ldadd_cleanup( ConfigArgs *c )
2703 {
2704         slap_overinst *on = c->ca_private;
2705         return pcache_db_open2( on, &c->reply );
2706 }
2707
2708 static int
2709 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2710 {
2711         slap_overinst *on;
2712         cache_manager *cm;
2713
2714         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2715                 p->ce_bi->bi_cf_ocs != pcocs )
2716                 return LDAP_CONSTRAINT_VIOLATION;
2717
2718         on = (slap_overinst *)p->ce_bi;
2719         cm = on->on_bi.bi_private;
2720         ca->be = &cm->db;
2721         /* Defer open if this is an LDAPadd */
2722         if ( CONFIG_ONLINE_ADD( ca ))
2723                 ca->cleanup = pc_ldadd_cleanup;
2724         else
2725                 cm->defer_db_open = 0;
2726         ca->ca_private = on;
2727         return LDAP_SUCCESS;
2728 }
2729
2730 static int
2731 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2732 {
2733         CfEntryInfo *pe = p->e_private;
2734         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2735         cache_manager *cm = on->on_bi.bi_private;
2736         struct berval bv;
2737
2738         /* FIXME: should not hardcode "olcDatabase" here */
2739         bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
2740                 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
2741                 0, cm->db.bd_info->bi_type );
2742         if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
2743                 return -1;
2744         }
2745         bv.bv_val = ca->cr_msg;
2746         ca->be = &cm->db;
2747         cm->defer_db_open = 0;
2748
2749         /* We can only create this entry if the database is table-driven
2750          */
2751         if ( cm->db.bd_info->bi_cf_ocs )
2752                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2753                         &pcocs[1] );
2754
2755         return 0;
2756 }
2757
2758 static int
2759 pc_cf_gen( ConfigArgs *c )
2760 {
2761         slap_overinst   *on = (slap_overinst *)c->bi;
2762         cache_manager*  cm = on->on_bi.bi_private;
2763         query_manager*  qm = cm->qm;
2764         QueryTemplate*  temp;
2765         AttributeName*  attr_name;
2766         AttributeName*  attrarray;
2767         const char*     text=NULL;
2768         int             i, num, rc = 0;
2769         char            *ptr;
2770         unsigned long   t;
2771
2772         if ( c->op == SLAP_CONFIG_EMIT ) {
2773                 struct berval bv;
2774                 switch( c->type ) {
2775                 case PC_MAIN:
2776                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2777                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2778                                 cm->num_entries_limit, cm->cc_period );
2779                         bv.bv_val = c->cr_msg;
2780                         value_add_one( &c->rvalue_vals, &bv );
2781                         break;
2782                 case PC_ATTR:
2783                         for (i=0; i<cm->numattrsets; i++) {
2784                                 if ( !qm->attr_sets[i].count ) continue;
2785
2786                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2787
2788                                 /* count the attr length */
2789                                 for ( attr_name = qm->attr_sets[i].attrs;
2790                                         attr_name->an_name.bv_val; attr_name++ )
2791                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2792
2793                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2794                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2795                                 for ( attr_name = qm->attr_sets[i].attrs;
2796                                         attr_name->an_name.bv_val; attr_name++ ) {
2797                                         *ptr++ = ' ';
2798                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2799                                 }
2800                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2801                         }
2802                         if ( !c->rvalue_vals )
2803                                 rc = 1;
2804                         break;
2805                 case PC_TEMP:
2806                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2807                                 /* HEADS-UP: always print all;
2808                                  * if optional == 0, ignore */
2809                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2810                                         " %d %ld %ld %ld",
2811                                         temp->attr_set_index,
2812                                         temp->ttl,
2813                                         temp->negttl,
2814                                         temp->limitttl );
2815                                 bv.bv_len += temp->querystr.bv_len + 2;
2816                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2817                                 ptr = bv.bv_val;
2818                                 *ptr++ = '"';
2819                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2820                                 *ptr++ = '"';
2821                                 strcpy( ptr, c->cr_msg );
2822                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2823                         }
2824                         if ( !c->rvalue_vals )
2825                                 rc = 1;
2826                         break;
2827                 case PC_RESP:
2828                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2829                                 BER_BVSTR( &bv, "head" );
2830                         } else {
2831                                 BER_BVSTR( &bv, "tail" );
2832                         }
2833                         value_add_one( &c->rvalue_vals, &bv );
2834                         break;
2835                 case PC_QUERIES:
2836                         c->value_int = cm->max_queries;
2837                         break;
2838                 }
2839                 return rc;
2840         } else if ( c->op == LDAP_MOD_DELETE ) {
2841                 return 1;       /* FIXME */
2842 #if 0
2843                 switch( c->type ) {
2844                 case PC_ATTR:
2845                 case PC_TEMP:
2846                 }
2847                 return rc;
2848 #endif
2849         }
2850
2851         switch( c->type ) {
2852         case PC_MAIN:
2853                 if ( cm->numattrsets > 0 ) {
2854                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2855                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2856                         return( 1 );
2857                 }
2858
2859                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2860                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2861                                 c->argv[3] );
2862                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2863                         return( 1 );
2864                 }
2865                 if ( cm->numattrsets <= 0 ) {
2866                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2867                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2868                         return( 1 );
2869                 }
2870                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2871                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2872                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2873                         return( 1 );
2874                 }
2875
2876                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2877                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2878                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2879                         return( 1 );
2880                 }
2881
2882                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2883                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2884                                 c->argv[2] );
2885                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2886                         return( 1 );
2887                 }
2888                 if ( cm->max_entries <= 0 ) {
2889                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2890                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2891                         return( 1 );
2892                 }
2893
2894                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2895                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2896                                 c->argv[4] );
2897                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2898                         return( 1 );
2899                 }
2900                 if ( cm->num_entries_limit <= 0 ) {
2901                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2902                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2903                         return( 1 );
2904                 }
2905                 if ( cm->num_entries_limit > cm->max_entries ) {
2906                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2907                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2908                         return( 1 );
2909                 }
2910
2911                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2912                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2913                                 c->argv[5] );
2914                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2915                         return( 1 );
2916                 }
2917
2918                 cm->cc_period = (time_t)t;
2919                 Debug( pcache_debug,
2920                                 "Total # of attribute sets to be cached = %d.\n",
2921                                 cm->numattrsets, 0, 0 );
2922                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2923                                                 sizeof( struct attr_set ) );
2924                 break;
2925         case PC_ATTR:
2926                 if ( cm->numattrsets == 0 ) {
2927                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2928                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2929                         return( 1 );
2930                 }
2931                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2932                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2933                                 c->argv[1] );
2934                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2935                         return( 1 );
2936                 }
2937
2938                 if ( num < 0 || num >= cm->numattrsets ) {
2939                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2940                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2941                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2942                         return 1;
2943                 }
2944                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2945                 if ( c->argc == 2 ) {
2946                         /* assume "1.1" */
2947                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2948                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2949                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2950                         return 1;
2951
2952                 } else if ( c->argc == 3 ) {
2953                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2954                                 qm->attr_sets[num].count = 1;
2955                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2956                                         sizeof( AttributeName ) );
2957                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2958                                 break;
2959
2960                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2961                                 qm->attr_sets[num].count = 1;
2962                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2963                                         sizeof( AttributeName ) );
2964                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2965                                 break;
2966
2967                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2968                                 break;
2969                         }
2970                         /* else: fallthru */
2971
2972                 } else if ( c->argc == 4 ) {
2973                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2974                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2975                         {
2976                                 qm->attr_sets[num].count = 2;
2977                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2978                                         sizeof( AttributeName ) );
2979                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2980                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2981                                 break;
2982                         }
2983                         /* else: fallthru */
2984                 }
2985
2986                 if ( c->argc > 2 ) {
2987                         int all_user = 0, all_op = 0;
2988
2989                         qm->attr_sets[num].count = c->argc - 2;
2990                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2991                                 sizeof( AttributeName ) );
2992                         attr_name = qm->attr_sets[num].attrs;
2993                         for ( i = 2; i < c->argc; i++ ) {
2994                                 attr_name->an_desc = NULL;
2995                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2996                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2997                                                 "invalid attr #%d \"%s\" in attrlist",
2998                                                 i - 2, c->argv[i] );
2999                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3000                                         ch_free( qm->attr_sets[num].attrs );
3001                                         qm->attr_sets[num].attrs = NULL;
3002                                         qm->attr_sets[num].count = 0;
3003                                         return 1;
3004                                 }
3005                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3006                                         all_user = 1;
3007                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
3008                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3009                                         all_op = 1;
3010                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3011                                 } else {
3012                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
3013                                                 strcpy( c->cr_msg, text );
3014                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3015                                                 ch_free( qm->attr_sets[num].attrs );
3016                                                 qm->attr_sets[num].attrs = NULL;
3017                                                 qm->attr_sets[num].count = 0;
3018                                                 return 1;
3019                                         }
3020                                         attr_name->an_name = attr_name->an_desc->ad_cname;
3021                                 }
3022                                 attr_name->an_oc = NULL;
3023                                 attr_name->an_oc_exclude = 0;
3024                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
3025                                         qm->attr_sets[num].flags |= PC_GOT_OC;
3026                                 attr_name++;
3027                                 BER_BVZERO( &attr_name->an_name );
3028                         }
3029
3030                         /* warn if list contains both "*" and "+" */
3031                         if ( i > 4 && all_user && all_op ) {
3032                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3033                                         "warning: attribute list contains \"*\" and \"+\"" );
3034                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3035                         }
3036                 }
3037                 break;
3038         case PC_TEMP:
3039                 if ( cm->numattrsets == 0 ) {
3040                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3041                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3042                         return( 1 );
3043                 }
3044                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
3045                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
3046                                 c->argv[2] );
3047                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3048                         return( 1 );
3049                 }
3050
3051                 if ( i < 0 || i >= cm->numattrsets || 
3052                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
3053                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
3054                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3055                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3056                         return 1;
3057                 }
3058                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
3059                 temp->qmnext = qm->templates;
3060                 qm->templates = temp;
3061                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
3062                 temp->query = temp->query_last = NULL;
3063                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
3064                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3065                                 "unable to parse template ttl=\"%s\"",
3066                                 c->argv[3] );
3067                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3068                         return( 1 );
3069                 }
3070                 temp->ttl = (time_t)t;
3071                 temp->negttl = (time_t)0;
3072                 temp->limitttl = (time_t)0;
3073                 switch ( c->argc ) {
3074                 case 6:
3075                         if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3076                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3077                                         "unable to parse template sizelimit ttl=\"%s\"",
3078                                         c->argv[5] );
3079                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3080                                         return( 1 );
3081                         }
3082                         temp->limitttl = (time_t)t;
3083                         /* fallthru */
3084
3085                 case 5:
3086                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
3087                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3088                                         "unable to parse template negative ttl=\"%s\"",
3089                                         c->argv[4] );
3090                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3091                                         return( 1 );
3092                         }
3093                         temp->negttl = (time_t)t;
3094                         break;
3095                 }
3096
3097                 temp->no_of_queries = 0;
3098
3099                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3100                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3101                 Debug( pcache_debug, "  query template: %s\n",
3102                                 temp->querystr.bv_val, 0, 0 );
3103                 temp->attr_set_index = i;
3104                 qm->attr_sets[i].flags |= PC_REFERENCED;
3105                 temp->qtnext = qm->attr_sets[i].templates;
3106                 qm->attr_sets[i].templates = temp;
3107                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
3108                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3109                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
3110                                 Debug( pcache_debug, "\t%s\n",
3111                                         attrarray[i].an_name.bv_val, 0, 0 );
3112                 }
3113                 break;
3114         case PC_RESP:
3115                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3116                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3117
3118                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3119                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3120
3121                 } else {
3122                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3123                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3124                         return 1;
3125                 }
3126                 break;
3127         case PC_QUERIES:
3128                 if ( c->value_int <= 0 ) {
3129                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3130                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3131                         return( 1 );
3132                 }
3133                 cm->max_queries = c->value_int;
3134                 break;
3135         }
3136         return rc;
3137 }
3138
3139 static int
3140 pcache_db_config(
3141         BackendDB       *be,
3142         const char      *fname,
3143         int             lineno,
3144         int             argc,
3145         char            **argv
3146 )
3147 {
3148         slap_overinst   *on = (slap_overinst *)be->bd_info;
3149         cache_manager*  cm = on->on_bi.bi_private;
3150
3151         /* Something for the cache database? */
3152         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3153                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3154                         argc, argv );
3155         return SLAP_CONF_UNKNOWN;
3156 }
3157
3158 static int
3159 pcache_db_init(
3160         BackendDB *be,
3161         ConfigReply *cr)
3162 {
3163         slap_overinst *on = (slap_overinst *)be->bd_info;
3164         cache_manager *cm;
3165         query_manager *qm;
3166
3167         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3168         on->on_bi.bi_private = cm;
3169
3170         qm = (query_manager*)ch_malloc(sizeof(query_manager));
3171
3172         cm->db = *be;
3173         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3174         cm->db.be_private = NULL;
3175         cm->db.bd_self = &cm->db;
3176         cm->qm = qm;
3177         cm->numattrsets = 0;
3178         cm->num_entries_limit = 5;
3179         cm->num_cached_queries = 0;
3180         cm->max_entries = 0;
3181         cm->cur_entries = 0;
3182         cm->max_queries = 10000;
3183         cm->save_queries = 0;
3184         cm->check_cacheability = 0;
3185         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3186         cm->defer_db_open = 1;
3187         cm->cc_period = 1000;
3188         cm->cc_paused = 0;
3189         cm->cc_arg = NULL;
3190
3191         qm->attr_sets = NULL;
3192         qm->templates = NULL;
3193         qm->lru_top = NULL;
3194         qm->lru_bottom = NULL;
3195
3196         qm->qcfunc = query_containment;
3197         qm->crfunc = cache_replacement;
3198         qm->addfunc = add_query;
3199         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3200
3201         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3202         return 0;
3203 }
3204
3205 static int
3206 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3207 {
3208         assert( op->o_tag == LDAP_REQ_SEARCH );
3209
3210         if ( rs->sr_type == REP_SEARCH ) {
3211                 Attribute       *a;
3212
3213                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3214                 if ( a != NULL ) {
3215                         BerVarray       *valsp;
3216
3217                         assert( a->a_nvals != NULL );
3218
3219                         valsp = op->o_callback->sc_private;
3220                         assert( *valsp == NULL );
3221
3222                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3223                 }
3224         }
3225
3226         return 0;
3227 }
3228
3229 static int
3230 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3231 {
3232         assert( op->o_tag == LDAP_REQ_SEARCH );
3233
3234         if ( rs->sr_type == REP_SEARCH ) {
3235                 int     *countp = (int *)op->o_callback->sc_private;
3236
3237                 (*countp)++;
3238         }
3239
3240         return 0;
3241 }
3242
3243 static int
3244 pcache_db_open2(
3245         slap_overinst *on,
3246         ConfigReply *cr )
3247 {
3248         cache_manager   *cm = on->on_bi.bi_private;
3249         query_manager*  qm = cm->qm;
3250         int rc;
3251
3252         rc = backend_startup_one( &cm->db, cr );
3253         if ( rc == 0 ) {
3254                 cm->defer_db_open = 0;
3255         }
3256
3257         /* There is no runqueue in TOOL mode */
3258         if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
3259                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3260                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3261                         consistency_check, on,
3262                         "pcache_consistency", cm->db.be_suffix[0].bv_val );
3263                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3264
3265                 /* Cached database must have the rootdn */
3266                 if ( BER_BVISNULL( &cm->db.be_rootndn )
3267                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3268                 {
3269                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3270                                 "underlying database of type \"%s\"\n"
3271                                 "    serving naming context \"%s\"\n"
3272                                 "    has no \"rootdn\", required by \"proxycache\".\n",
3273                                 on->on_info->oi_orig->bi_type,
3274                                 cm->db.be_suffix[0].bv_val, 0 );
3275                         return 1;
3276                 }
3277
3278                 if ( cm->save_queries ) {
3279                         void            *thrctx = ldap_pvt_thread_pool_context();
3280                         Connection      conn = { 0 };
3281                         OperationBuffer opbuf;
3282                         Operation       *op;
3283                         slap_callback   cb = { 0 };
3284                         SlapReply       rs = { 0 };
3285                         BerVarray       vals = NULL;
3286                         Filter          f = { 0 }, f2 = { 0 };
3287                         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
3288                         AttributeName   attrs[ 2 ] = {{{ 0 }}};
3289
3290                         connection_fake_init( &conn, &opbuf, thrctx );
3291                         op = &opbuf.ob_op;
3292
3293                         op->o_bd = &cm->db;
3294
3295                         op->o_tag = LDAP_REQ_SEARCH;
3296                         op->o_protocol = LDAP_VERSION3;
3297                         cb.sc_response = pcache_cachedquery_open_cb;
3298                         cb.sc_private = &vals;
3299                         op->o_callback = &cb;
3300                         op->o_time = slap_get_time();
3301                         op->o_do_not_cache = 1;
3302                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
3303
3304                         op->o_dn = cm->db.be_rootdn;
3305                         op->o_ndn = cm->db.be_rootndn;
3306                         op->o_req_dn = cm->db.be_suffix[ 0 ];
3307                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3308
3309                         op->ors_scope = LDAP_SCOPE_BASE;
3310                         op->ors_deref = LDAP_DEREF_NEVER;
3311                         op->ors_slimit = 1;
3312                         op->ors_tlimit = SLAP_NO_LIMIT;
3313                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3314                         f.f_choice = LDAP_FILTER_PRESENT;
3315                         f.f_desc = ad_cachedQueryURL;
3316                         op->ors_filter = &f;
3317                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
3318                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3319                         op->ors_attrs = attrs;
3320                         op->ors_attrsonly = 0;
3321
3322                         rc = op->o_bd->be_search( op, &rs );
3323                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
3324                                 int     i;
3325
3326                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3327                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3328                                                 cm->num_cached_queries++;
3329                                         }
3330                                 }
3331
3332                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3333                         }
3334
3335                         /* count cached entries */
3336                         f.f_choice = LDAP_FILTER_NOT;
3337                         f.f_not = &f2;
3338                         f2.f_choice = LDAP_FILTER_EQUALITY;
3339                         f2.f_ava = &ava;
3340                         f2.f_av_desc = slap_schema.si_ad_objectClass;
3341                         BER_BVSTR( &f2.f_av_value, "glue" );
3342                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3343
3344                         op->ors_slimit = SLAP_NO_LIMIT;
3345                         op->ors_scope = LDAP_SCOPE_SUBTREE;
3346                         op->ors_attrs = slap_anlist_no_attrs;
3347
3348                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
3349                         rs.sr_nentries = 0;
3350                         op->o_callback->sc_private = &rs.sr_nentries;
3351
3352                         rc = op->o_bd->be_search( op, &rs );
3353
3354                         cm->cur_entries = rs.sr_nentries;
3355
3356                         /* ignore errors */
3357                         rc = 0;
3358                 }
3359         }
3360         return rc;
3361 }
3362
3363 static int
3364 pcache_db_open(
3365         BackendDB *be,
3366         ConfigReply *cr )
3367 {
3368         slap_overinst   *on = (slap_overinst *)be->bd_info;
3369         cache_manager   *cm = on->on_bi.bi_private;
3370         query_manager*  qm = cm->qm;
3371         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3372
3373         /* check attr sets */
3374         for ( i = 0; i < cm->numattrsets; i++) {
3375                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3376                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3377                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3378                                 rf++;
3379
3380                         } else {
3381                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3382                         }
3383                         ncf++;
3384
3385                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3386                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3387                         nrf++;
3388                 }
3389         }
3390
3391         if ( ncf || rf || nrf ) {
3392                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3393                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3394                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3395
3396                 if ( rf > 0 ) {
3397                         return 1;
3398                 }
3399         }
3400
3401         /* need to inherit something from the original database... */
3402         cm->db.be_def_limit = be->be_def_limit;
3403         cm->db.be_limits = be->be_limits;
3404         cm->db.be_acl = be->be_acl;
3405         cm->db.be_dfltaccess = be->be_dfltaccess;
3406
3407         if ( SLAP_DBMONITORING( be ) ) {
3408                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3409
3410         } else {
3411                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3412         }
3413
3414         if ( !cm->defer_db_open )
3415                 rc = pcache_db_open2( on, cr );
3416
3417         return rc;
3418 }
3419
3420 static void
3421 pcache_free_qbase( void *v )
3422 {
3423         Qbase *qb = v;
3424         int i;
3425
3426         for (i=0; i<3; i++)
3427                 tavl_free( qb->scopes[i], NULL );
3428         ch_free( qb );
3429 }
3430
3431 static int
3432 pcache_db_close(
3433         BackendDB *be,
3434         ConfigReply *cr
3435 )
3436 {
3437         slap_overinst *on = (slap_overinst *)be->bd_info;
3438         cache_manager *cm = on->on_bi.bi_private;
3439         query_manager *qm = cm->qm;
3440         QueryTemplate *tm;
3441         int i, rc = 0;
3442
3443         if ( cm->save_queries ) {
3444                 CachedQuery     *qc;
3445                 BerVarray       vals = NULL;
3446
3447                 void            *thrctx;
3448                 Connection      conn = { 0 };
3449                 OperationBuffer opbuf;
3450                 Operation       *op;
3451                 slap_callback   cb = { 0 };
3452
3453                 SlapReply       rs = { REP_RESULT };
3454                 Modifications   mod = {{ 0 }};
3455
3456                 thrctx = ldap_pvt_thread_pool_context();
3457
3458                 connection_fake_init( &conn, &opbuf, thrctx );
3459                 op = &opbuf.ob_op;
3460
3461                 if ( qm->templates != NULL ) {
3462                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3463                                 for ( qc = tm->query; qc; qc = qc->next ) {
3464                                         struct berval   bv;
3465
3466                                         if ( query2url( op, qc, &bv ) == 0 ) {
3467                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3468                                         }
3469                                 }
3470                         }
3471                 }
3472
3473                 op->o_bd = &cm->db;
3474                 op->o_dn = cm->db.be_rootdn;
3475                 op->o_ndn = cm->db.be_rootndn;
3476
3477                 op->o_tag = LDAP_REQ_MODIFY;
3478                 op->o_protocol = LDAP_VERSION3;
3479                 cb.sc_response = slap_null_cb;
3480                 op->o_callback = &cb;
3481                 op->o_time = slap_get_time();
3482                 op->o_do_not_cache = 1;
3483                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3484
3485                 op->o_req_dn = op->o_bd->be_suffix[0];
3486                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3487
3488                 mod.sml_op = LDAP_MOD_REPLACE;
3489                 mod.sml_flags = 0;
3490                 mod.sml_desc = ad_cachedQueryURL;
3491                 mod.sml_type = ad_cachedQueryURL->ad_cname;
3492                 mod.sml_values = vals;
3493                 mod.sml_nvalues = NULL;
3494                 mod.sml_numvals = 1;
3495                 mod.sml_next = NULL;
3496                 Debug( pcache_debug,
3497                         "%sSETTING CACHED QUERY URLS\n",
3498                         vals == NULL ? "RE" : "", 0, 0 );
3499
3500                 op->orm_modlist = &mod;
3501
3502                 op->o_bd->be_modify( op, &rs );
3503
3504                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3505         }
3506
3507         /* cleanup stuff inherited from the original database... */
3508         cm->db.be_limits = NULL;
3509         cm->db.be_acl = NULL;
3510
3511         /* stop the thread ... */
3512         if ( cm->cc_arg ) {
3513                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3514                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3515                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3516                 }
3517                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3518                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3519         }
3520
3521         if ( cm->db.bd_info->bi_db_close ) {
3522                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3523         }
3524         while ( (tm = qm->templates) != NULL ) {
3525                 CachedQuery *qc, *qn;
3526                 qm->templates = tm->qmnext;
3527                 for ( qc = tm->query; qc; qc = qn ) {
3528                         qn = qc->next;
3529                         free_query( qc );
3530                 }
3531                 avl_free( tm->qbase, pcache_free_qbase );
3532                 free( tm->querystr.bv_val );
3533                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3534                 free( tm->t_attrs.attrs );
3535                 free( tm );
3536         }
3537
3538         for ( i=0; i<cm->numattrsets; i++ ) {
3539                 free( qm->attr_sets[i].attrs );
3540         }
3541         free( qm->attr_sets );
3542         qm->attr_sets = NULL;
3543
3544         return rc;
3545 }
3546
3547 static int
3548 pcache_db_destroy(
3549         BackendDB *be,
3550         ConfigReply *cr
3551 )
3552 {
3553         slap_overinst *on = (slap_overinst *)be->bd_info;
3554         cache_manager *cm = on->on_bi.bi_private;
3555         query_manager *qm = cm->qm;
3556
3557         if ( cm->db.be_private != NULL ) {
3558                 backend_stopdown_one( &cm->db );
3559         }
3560
3561         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3562         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3563         free( qm );
3564         free( cm );
3565
3566         return 0;
3567 }
3568
3569 #ifdef PCACHE_CONTROL_PRIVDB
3570 /*
3571         Control ::= SEQUENCE {
3572              controlType             LDAPOID,
3573              criticality             BOOLEAN DEFAULT FALSE,
3574              controlValue            OCTET STRING OPTIONAL }
3575
3576         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3577
3578  * criticality must be TRUE; controlValue must be absent.
3579  */
3580 static int
3581 parse_privdb_ctrl(
3582         Operation       *op,
3583         SlapReply       *rs,
3584         LDAPControl     *ctrl )
3585 {
3586         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3587                 rs->sr_text = "privateDB control specified multiple times";
3588                 return LDAP_PROTOCOL_ERROR;
3589         }
3590
3591         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3592                 rs->sr_text = "privateDB control value not absent";
3593                 return LDAP_PROTOCOL_ERROR;
3594         }
3595
3596         if ( !ctrl->ldctl_iscritical ) {
3597                 rs->sr_text = "privateDB control criticality required";
3598                 return LDAP_PROTOCOL_ERROR;
3599         }
3600
3601         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3602
3603         return LDAP_SUCCESS;
3604 }
3605
3606 static char *extops[] = {
3607         LDAP_EXOP_MODIFY_PASSWD,
3608         NULL
3609 };
3610 #endif /* PCACHE_CONTROL_PRIVDB */
3611
3612 #ifdef PCACHE_EXOP_QUERY_DELETE
3613 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3614
3615 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3616 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3617 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3618
3619 /*
3620         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3621              requestName      [0] LDAPOID,
3622              requestValue     [1] OCTET STRING OPTIONAL }
3623
3624         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3625
3626         requestValue ::= SEQUENCE { CHOICE {
3627                   baseDN           [0] LDAPDN
3628                   entryDN          [1] LDAPDN },
3629              queryID          [2] OCTET STRING (SIZE(16))
3630                   -- constrained to UUID }
3631
3632  * Either baseDN or entryDN must be present, to allow database selection.
3633  *
3634  * 1. if baseDN and queryID are present, then the query corresponding
3635  *    to queryID is deleted;
3636  * 2. if baseDN is present and queryID is absent, then all queries
3637  *    are deleted;
3638  * 3. if entryDN is present and queryID is absent, then all queries
3639  *    corresponding to the queryID values present in entryDN are deleted;
3640  * 4. if entryDN and queryID are present, then all queries
3641  *    corresponding to the queryID values present in entryDN are deleted,
3642  *    but only if the value of queryID is contained in the entry;
3643  *
3644  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
3645  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3646  * or by removing the database files.
3647
3648         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3649              COMPONENTS OF LDAPResult,
3650              responseName     [10] LDAPOID OPTIONAL,
3651              responseValue    [11] OCTET STRING OPTIONAL }
3652
3653  * responseName and responseValue must be absent.
3654  */
3655
3656 /*
3657  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3658  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3659  * - if ndn != NULL, it is set to the normalized DN in the request
3660  *   corresponding to either the baseDN or the entryDN, according
3661  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
3662  *   be freed by the caller.
3663  * - if uuid != NULL, it is set to point to the normalized UUID;
3664  *   memory is malloc'ed on the Operation's slab, and must
3665  *   be freed by the caller.
3666  */
3667 static int
3668 pcache_parse_query_delete(
3669         struct berval   *in,
3670         ber_tag_t       *tagp,
3671         struct berval   *ndn,
3672         struct berval   *uuid,
3673         const char      **text,
3674         void            *ctx )
3675 {
3676         int                     rc = LDAP_SUCCESS;
3677         ber_tag_t               tag;
3678         ber_len_t               len = -1;
3679         BerElementBuffer        berbuf;
3680         BerElement              *ber = (BerElement *)&berbuf;
3681         struct berval           reqdata = BER_BVNULL;
3682
3683         *text = NULL;
3684
3685         if ( ndn ) {
3686                 BER_BVZERO( ndn );
3687         }
3688
3689         if ( uuid ) {
3690                 BER_BVZERO( uuid );
3691         }
3692
3693         if ( in == NULL || in->bv_len == 0 ) {
3694                 *text = "empty request data field in queryDelete exop";
3695                 return LDAP_PROTOCOL_ERROR;
3696         }
3697
3698         ber_dupbv_x( &reqdata, in, ctx );
3699
3700         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3701         ber_init2( ber, &reqdata, 0 );
3702
3703         tag = ber_scanf( ber, "{" /*}*/ );
3704
3705         if ( tag == LBER_ERROR ) {
3706                 Debug( LDAP_DEBUG_TRACE,
3707                         "pcache_parse_query_delete: decoding error.\n",
3708                         0, 0, 0 );
3709                 goto decoding_error;
3710         }
3711
3712         tag = ber_peek_tag( ber, &len );
3713         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3714                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3715         {
3716                 *tagp = tag;
3717
3718                 if ( ndn != NULL ) {
3719                         struct berval   dn;
3720
3721                         tag = ber_scanf( ber, "m", &dn );
3722                         if ( tag == LBER_ERROR ) {
3723                                 Debug( LDAP_DEBUG_TRACE,
3724                                         "pcache_parse_query_delete: DN parse failed.\n",
3725                                         0, 0, 0 );
3726                                 goto decoding_error;
3727                         }
3728
3729                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3730                         if ( rc != LDAP_SUCCESS ) {
3731                                 *text = "invalid DN in queryDelete exop request data";
3732                                 goto done;
3733                         }
3734
3735                 } else {
3736                         tag = ber_scanf( ber, "x" /* "m" */ );
3737                         if ( tag == LBER_DEFAULT ) {
3738                                 goto decoding_error;
3739                         }
3740                 }
3741
3742                 tag = ber_peek_tag( ber, &len );
3743         }
3744
3745         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3746                 if ( uuid != NULL ) {
3747                         struct berval   bv;
3748                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3749
3750                         tag = ber_scanf( ber, "m", &bv );
3751                         if ( tag == LBER_ERROR ) {
3752                                 Debug( LDAP_DEBUG_TRACE,
3753                                         "pcache_parse_query_delete: UUID parse failed.\n",
3754                                         0, 0, 0 );
3755                                 goto decoding_error;
3756                         }
3757
3758                         if ( bv.bv_len != 16 ) {
3759                                 Debug( LDAP_DEBUG_TRACE,
3760                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3761                                         (unsigned long)bv.bv_len, 0, 0 );
3762                                 goto decoding_error;
3763                         }
3764
3765                         rc = lutil_uuidstr_from_normalized(
3766                                 bv.bv_val, bv.bv_len,
3767                                 uuidbuf, sizeof( uuidbuf ) );
3768                         if ( rc == -1 ) {
3769                                 goto decoding_error;
3770                         }
3771                         ber_str2bv( uuidbuf, rc, 1, uuid );
3772                         rc = LDAP_SUCCESS;
3773
3774                 } else {
3775                         tag = ber_skip_tag( ber, &len );
3776                         if ( tag == LBER_DEFAULT ) {
3777                                 goto decoding_error;
3778                         }
3779
3780                         if ( len != 16 ) {
3781                                 Debug( LDAP_DEBUG_TRACE,
3782                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3783                                         (unsigned long)len, 0, 0 );
3784                                 goto decoding_error;
3785                         }
3786                 }
3787
3788                 tag = ber_peek_tag( ber, &len );
3789         }
3790
3791         if ( tag != LBER_DEFAULT || len != 0 ) {
3792 decoding_error:;
3793                 Debug( LDAP_DEBUG_TRACE,
3794                         "pcache_parse_query_delete: decoding error\n",
3795                         0, 0, 0 );
3796                 rc = LDAP_PROTOCOL_ERROR;
3797                 *text = "queryDelete data decoding error";
3798
3799 done:;
3800                 if ( ndn && !BER_BVISNULL( ndn ) ) {
3801                         slap_sl_free( ndn->bv_val, ctx );
3802                         BER_BVZERO( ndn );
3803                 }
3804
3805                 if ( uuid && !BER_BVISNULL( uuid ) ) {
3806                         slap_sl_free( uuid->bv_val, ctx );
3807                         BER_BVZERO( uuid );
3808                 }
3809         }
3810
3811         if ( !BER_BVISNULL( &reqdata ) ) {
3812                 ber_memfree_x( reqdata.bv_val, ctx );
3813         }
3814
3815         return rc;
3816 }
3817
3818 static int
3819 pcache_exop_query_delete(
3820         Operation       *op,
3821         SlapReply       *rs )
3822 {
3823         BackendDB       *bd = op->o_bd;
3824
3825         struct berval   uuid = BER_BVNULL,
3826                         *uuidp = NULL;
3827         char            buf[ SLAP_TEXT_BUFLEN ];
3828         unsigned        len;
3829         ber_tag_t       tag = LBER_DEFAULT;
3830
3831         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3832                 uuidp = &uuid;
3833         }
3834
3835         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3836                 &tag, &op->o_req_ndn, uuidp,
3837                 &rs->sr_text, op->o_tmpmemctx );
3838         if ( rs->sr_err != LDAP_SUCCESS ) {
3839                 return rs->sr_err;
3840         }
3841
3842         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3843                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3844                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3845
3846                 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
3847                         snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3848                 }
3849
3850                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3851                         op->o_log_prefix, buf, 0 );
3852         }
3853         op->o_req_dn = op->o_req_ndn;
3854
3855         op->o_bd = select_backend( &op->o_req_ndn, 0 );
3856         rs->sr_err = backend_check_restrictions( op, rs,
3857                 (struct berval *)&pcache_exop_QUERY_DELETE );
3858         if ( rs->sr_err != LDAP_SUCCESS ) {
3859                 goto done;
3860         }
3861
3862         if ( op->o_bd->be_extended == NULL ) {
3863                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3864                         "backend does not support extended operations" );
3865                 goto done;
3866         }
3867
3868         op->o_bd->be_extended( op, rs );
3869
3870 done:;
3871         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3872                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3873                 BER_BVZERO( &op->o_req_ndn );
3874                 BER_BVZERO( &op->o_req_dn );
3875         }
3876
3877         if ( !BER_BVISNULL( &uuid ) ) {
3878                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3879         }
3880
3881         op->o_bd = bd;
3882
3883         return rs->sr_err;
3884 }
3885
3886 static int
3887 pcache_op_extended( Operation *op, SlapReply *rs )
3888 {
3889         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
3890         cache_manager   *cm = on->on_bi.bi_private;
3891
3892 #ifdef PCACHE_CONTROL_PRIVDB
3893         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3894                 return pcache_op_privdb( op, rs );
3895         }
3896 #endif /* PCACHE_CONTROL_PRIVDB */
3897
3898         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3899                 struct berval   uuid = BER_BVNULL;
3900                 ber_tag_t       tag = LBER_DEFAULT;
3901
3902                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3903                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3904                 assert( rs->sr_err == LDAP_SUCCESS );
3905
3906                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3907                         /* remove all queries related to the selected entry */
3908                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3909                                 cm, &op->o_req_ndn, &uuid );
3910
3911                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3912                         if ( !BER_BVISNULL( &uuid ) ) {
3913                                 /* remove the selected query */
3914                                 rs->sr_err = pcache_remove_query_from_cache( op,
3915                                         cm, &uuid );
3916
3917                         } else {
3918                                 /* TODO: remove all queries */
3919                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3920                                 rs->sr_text = "deletion of all queries not implemented";
3921                         }
3922                 }
3923
3924                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3925         }
3926
3927         return rs->sr_err;
3928 }
3929 #endif /* PCACHE_EXOP_QUERY_DELETE */
3930
3931 static slap_overinst pcache;
3932
3933 static char *obsolete_names[] = {
3934         "proxycache",
3935         NULL
3936 };
3937
3938 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3939 static
3940 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3941 int
3942 pcache_initialize()
3943 {
3944         int i, code;
3945         struct berval debugbv = BER_BVC("pcache");
3946
3947         code = slap_loglevel_get( &debugbv, &pcache_debug );
3948         if ( code ) {
3949                 return code;
3950         }
3951
3952 #ifdef PCACHE_CONTROL_PRIVDB
3953         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3954                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3955                 parse_privdb_ctrl, &privDB_cid );
3956         if ( code != LDAP_SUCCESS ) {
3957                 Debug( LDAP_DEBUG_ANY,
3958                         "pcache_initialize: failed to register control %s (%d)\n",
3959                         PCACHE_CONTROL_PRIVDB, code, 0 );
3960                 return code;
3961         }
3962 #endif /* PCACHE_CONTROL_PRIVDB */
3963
3964 #ifdef PCACHE_EXOP_QUERY_DELETE
3965         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3966                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3967                 0 );
3968         if ( code != LDAP_SUCCESS ) {
3969                 Debug( LDAP_DEBUG_ANY,
3970                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
3971                         code, 0, 0 );
3972                 return code;
3973         }
3974 #endif /* PCACHE_EXOP_QUERY_DELETE */
3975
3976         for ( i = 0; as[i].desc != NULL; i++ ) {
3977                 code = register_at( as[i].desc, as[i].adp, 0 );
3978                 if ( code ) {
3979                         Debug( LDAP_DEBUG_ANY,
3980                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3981                         return code;
3982                 }
3983                 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3984         }
3985
3986         pcache.on_bi.bi_type = "pcache";
3987         pcache.on_bi.bi_obsolete_names = obsolete_names;
3988         pcache.on_bi.bi_db_init = pcache_db_init;
3989         pcache.on_bi.bi_db_config = pcache_db_config;
3990         pcache.on_bi.bi_db_open = pcache_db_open;
3991         pcache.on_bi.bi_db_close = pcache_db_close;
3992         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3993
3994         pcache.on_bi.bi_op_search = pcache_op_search;
3995 #ifdef PCACHE_CONTROL_PRIVDB
3996         pcache.on_bi.bi_op_bind = pcache_op_privdb;
3997         pcache.on_bi.bi_op_compare = pcache_op_privdb;
3998         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3999         pcache.on_bi.bi_op_modify = pcache_op_privdb;
4000         pcache.on_bi.bi_op_add = pcache_op_privdb;
4001         pcache.on_bi.bi_op_delete = pcache_op_privdb;
4002 #endif /* PCACHE_CONTROL_PRIVDB */
4003 #ifdef PCACHE_EXOP_QUERY_DELETE
4004         pcache.on_bi.bi_extended = pcache_op_extended;
4005 #elif defined( PCACHE_CONTROL_PRIVDB )
4006         pcache.on_bi.bi_extended = pcache_op_privdb;
4007 #endif
4008
4009         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
4010
4011         pcache.on_bi.bi_cf_ocs = pcocs;
4012
4013         code = config_register_schema( pccfg, pcocs );
4014         if ( code ) return code;
4015
4016         return overlay_register( &pcache );
4017 }
4018
4019 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4020 int init_module(int argc, char *argv[]) {
4021         return pcache_initialize();
4022 }
4023 #endif
4024
4025 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */