]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
vlv implemented, untested
[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         ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1179         memset(qc, 0, sizeof(*qc));
1180         free(qc);
1181 }
1182
1183
1184 /* Add query to query cache, the returned Query is locked for writing */
1185 static CachedQuery *
1186 add_query(
1187         Operation *op,
1188         query_manager* qm,
1189         Query* query,
1190         QueryTemplate *templ,
1191         pc_caching_reason_t why,
1192         int wlock)
1193 {
1194         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1195         Qbase *qbase, qb;
1196         Filter *first;
1197         int rc;
1198         time_t ttl = 0;;
1199
1200         new_cached_query->qtemp = templ;
1201         BER_BVZERO( &new_cached_query->q_uuid );
1202         new_cached_query->q_sizelimit = 0;
1203
1204         switch ( why ) {
1205         case PC_POSITIVE:
1206                 ttl = templ->ttl;
1207                 break;
1208
1209         case PC_NEGATIVE:
1210                 ttl = templ->negttl;
1211                 break;
1212
1213         case PC_SIZELIMIT:
1214                 ttl = templ->limitttl;
1215                 break;
1216
1217         default:
1218                 assert( 0 );
1219                 break;
1220         }
1221         new_cached_query->expiry_time = slap_get_time() + ttl;
1222         new_cached_query->lru_up = NULL;
1223         new_cached_query->lru_down = NULL;
1224         Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1225                         (long) new_cached_query->expiry_time,
1226                         pc_caching_reason_str[ why ], 0 );
1227
1228         new_cached_query->scope = query->scope;
1229         new_cached_query->filter = query->filter;
1230         new_cached_query->first = first = filter_first( query->filter );
1231         
1232         ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1233         if (wlock)
1234                 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1235
1236         qb.base = query->base;
1237
1238         /* Adding a query    */
1239         Debug( pcache_debug, "Lock AQ index = %p\n",
1240                         (void *) templ, 0, 0 );
1241         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1242         qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1243         if ( !qbase ) {
1244                 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1245                 qbase->base.bv_len = qb.base.bv_len;
1246                 qbase->base.bv_val = (char *)(qbase+1);
1247                 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1248                 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1249                 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1250         }
1251         new_cached_query->next = templ->query;
1252         new_cached_query->prev = NULL;
1253         new_cached_query->qbase = qbase;
1254         rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1255                 pcache_query_cmp, avl_dup_error );
1256         if ( rc == 0 ) {
1257                 qbase->queries++;
1258                 if (templ->query == NULL)
1259                         templ->query_last = new_cached_query;
1260                 else
1261                         templ->query->prev = new_cached_query;
1262                 templ->query = new_cached_query;
1263                 templ->no_of_queries++;
1264         } else {
1265                 ch_free( new_cached_query );
1266                 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1267                                                         query->filter, first );
1268                 filter_free( query->filter );
1269                 query->filter = NULL;
1270         }
1271         Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1272                         (void *) templ, templ->no_of_queries, 0 );
1273
1274         Debug( pcache_debug, "Unlock AQ index = %p \n",
1275                         (void *) templ, 0, 0 );
1276         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1277
1278         /* Adding on top of LRU list  */
1279         if ( rc == 0 ) {
1280                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1281                 add_query_on_top(qm, new_cached_query);
1282                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1283         }
1284         return rc == 0 ? new_cached_query : NULL;
1285 }
1286
1287 static void
1288 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1289 {
1290         if (!qc->prev && !qc->next) {
1291                 template->query_last = template->query = NULL;
1292         } else if (qc->prev == NULL) {
1293                 qc->next->prev = NULL;
1294                 template->query = qc->next;
1295         } else if (qc->next == NULL) {
1296                 qc->prev->next = NULL;
1297                 template->query_last = qc->prev;
1298         } else {
1299                 qc->next->prev = qc->prev;
1300                 qc->prev->next = qc->next;
1301         }
1302         tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1303         qc->qbase->queries--;
1304         if ( qc->qbase->queries == 0 ) {
1305                 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1306                 ch_free( qc->qbase );
1307                 qc->qbase = NULL;
1308         }
1309
1310         template->no_of_queries--;
1311 }
1312
1313 /* remove bottom query of LRU list from the query cache */
1314 /*
1315  * NOTE: slight change in functionality.
1316  *
1317  * - if result->bv_val is NULL, the query at the bottom of the LRU
1318  *   is removed
1319  * - otherwise, the query whose UUID is *result is removed
1320  *      - if not found, result->bv_val is zeroed
1321  */
1322 static void
1323 cache_replacement(query_manager* qm, struct berval *result)
1324 {
1325         CachedQuery* bottom;
1326         QueryTemplate *temp;
1327
1328         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1329         if ( BER_BVISNULL( result ) ) {
1330                 bottom = qm->lru_bottom;
1331
1332                 if (!bottom) {
1333                         Debug ( pcache_debug,
1334                                 "Cache replacement invoked without "
1335                                 "any query in LRU list\n", 0, 0, 0 );
1336                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1337                         return;
1338                 }
1339
1340         } else {
1341                 for ( bottom = qm->lru_bottom;
1342                         bottom != NULL;
1343                         bottom = bottom->lru_up )
1344                 {
1345                         if ( bvmatch( result, &bottom->q_uuid ) ) {
1346                                 break;
1347                         }
1348                 }
1349
1350                 if ( !bottom ) {
1351                         Debug ( pcache_debug,
1352                                 "Could not find query with uuid=\"%s\""
1353                                 "in LRU list\n", result->bv_val, 0, 0 );
1354                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1355                         BER_BVZERO( result );
1356                         return;
1357                 }
1358         }
1359
1360         temp = bottom->qtemp;
1361         remove_query(qm, bottom);
1362         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1363
1364         *result = bottom->q_uuid;
1365         BER_BVZERO( &bottom->q_uuid );
1366
1367         Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1368         ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1369         remove_from_template(bottom, temp);
1370         Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1371                 (void *) temp, temp->no_of_queries, 0 );
1372         Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1373         ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1374         free_query(bottom);
1375 }
1376
1377 struct query_info {
1378         struct query_info *next;
1379         struct berval xdn;
1380         int del;
1381 };
1382
1383 static int
1384 remove_func (
1385         Operation       *op,
1386         SlapReply       *rs
1387 )
1388 {
1389         Attribute *attr;
1390         struct query_info *qi;
1391         int count = 0;
1392
1393         if ( rs->sr_type != REP_SEARCH ) return 0;
1394
1395         attr = attr_find( rs->sr_entry->e_attrs,  ad_queryId );
1396         if ( attr == NULL ) return 0;
1397
1398         count = attr->a_numvals;
1399         assert( count > 0 );
1400         qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1401         qi->next = op->o_callback->sc_private;
1402         op->o_callback->sc_private = qi;
1403         ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1404         qi->del = ( count == 1 );
1405
1406         return 0;
1407 }
1408
1409 static int
1410 remove_query_data(
1411         Operation       *op,
1412         SlapReply       *rs,
1413         struct berval   *query_uuid )
1414 {
1415         struct query_info       *qi, *qnext;
1416         char                    filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1417         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
1418         Filter                  filter = {LDAP_FILTER_EQUALITY};
1419         SlapReply               sreply = {REP_RESULT};
1420         slap_callback cb = { NULL, remove_func, NULL, NULL };
1421         int deleted = 0;
1422
1423         sreply.sr_entry = NULL;
1424         sreply.sr_nentries = 0;
1425         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1426                 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1427         filter.f_ava = &ava;
1428         filter.f_av_desc = ad_queryId;
1429         filter.f_av_value = *query_uuid;
1430
1431         op->o_tag = LDAP_REQ_SEARCH;
1432         op->o_protocol = LDAP_VERSION3;
1433         op->o_callback = &cb;
1434         op->o_time = slap_get_time();
1435         op->o_do_not_cache = 1;
1436
1437         op->o_req_dn = op->o_bd->be_suffix[0];
1438         op->o_req_ndn = op->o_bd->be_nsuffix[0];
1439         op->ors_scope = LDAP_SCOPE_SUBTREE;
1440         op->ors_deref = LDAP_DEREF_NEVER;
1441         op->ors_slimit = SLAP_NO_LIMIT;
1442         op->ors_tlimit = SLAP_NO_LIMIT;
1443         op->ors_filter = &filter;
1444         op->ors_filterstr.bv_val = filter_str;
1445         op->ors_filterstr.bv_len = strlen(filter_str);
1446         op->ors_attrs = NULL;
1447         op->ors_attrsonly = 0;
1448
1449         op->o_bd->be_search( op, &sreply );
1450
1451         for ( qi=cb.sc_private; qi; qi=qnext ) {
1452                 qnext = qi->next;
1453
1454                 op->o_req_dn = qi->xdn;
1455                 op->o_req_ndn = qi->xdn;
1456
1457                 if ( qi->del ) {
1458                         Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1459                                 query_uuid->bv_val, 0, 0 );
1460
1461                         op->o_tag = LDAP_REQ_DELETE;
1462
1463                         if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1464                                 deleted++;
1465                         }
1466
1467                 } else {
1468                         Modifications mod;
1469                         struct berval vals[2];
1470
1471                         vals[0] = *query_uuid;
1472                         vals[1].bv_val = NULL;
1473                         vals[1].bv_len = 0;
1474                         mod.sml_op = LDAP_MOD_DELETE;
1475                         mod.sml_flags = 0;
1476                         mod.sml_desc = ad_queryId;
1477                         mod.sml_type = ad_queryId->ad_cname;
1478                         mod.sml_values = vals;
1479                         mod.sml_nvalues = NULL;
1480                         mod.sml_numvals = 1;
1481                         mod.sml_next = NULL;
1482                         Debug( pcache_debug,
1483                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1484                                 query_uuid->bv_val, 0, 0 );
1485
1486                         op->orm_modlist = &mod;
1487
1488                         op->o_bd->be_modify( op, &sreply );
1489                 }
1490                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1491                 op->o_tmpfree( qi, op->o_tmpmemctx );
1492         }
1493         return deleted;
1494 }
1495
1496 static int
1497 get_attr_set(
1498         AttributeName* attrs,
1499         query_manager* qm,
1500         int num
1501 );
1502
1503 static int
1504 filter2template(
1505         Operation               *op,
1506         Filter                  *f,
1507         struct                  berval *fstr,
1508         AttributeName**         filter_attrs,
1509         int*                    filter_cnt,
1510         int*                    filter_got_oc )
1511 {
1512         AttributeDescription *ad;
1513         int len, ret;
1514
1515         switch ( f->f_choice ) {
1516         case LDAP_FILTER_EQUALITY:
1517                 ad = f->f_av_desc;
1518                 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1519                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1520                 assert( ret == len );
1521                 fstr->bv_len += len;
1522                 break;
1523
1524         case LDAP_FILTER_GE:
1525                 ad = f->f_av_desc;
1526                 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1527                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1528                 assert( ret == len );
1529                 fstr->bv_len += len;
1530                 break;
1531
1532         case LDAP_FILTER_LE:
1533                 ad = f->f_av_desc;
1534                 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1535                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1536                 assert( ret == len );
1537                 fstr->bv_len += len;
1538                 break;
1539
1540         case LDAP_FILTER_APPROX:
1541                 ad = f->f_av_desc;
1542                 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1543                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1544                 assert( ret == len );
1545                 fstr->bv_len += len;
1546                 break;
1547
1548         case LDAP_FILTER_SUBSTRINGS:
1549                 ad = f->f_sub_desc;
1550                 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1551                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1552                 assert( ret == len );
1553                 fstr->bv_len += len;
1554                 break;
1555
1556         case LDAP_FILTER_PRESENT:
1557                 ad = f->f_desc;
1558                 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1559                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1560                 assert( ret == len );
1561                 fstr->bv_len += len;
1562                 break;
1563
1564         case LDAP_FILTER_AND:
1565         case LDAP_FILTER_OR:
1566         case LDAP_FILTER_NOT: {
1567                 int rc = 0;
1568                 fstr->bv_val[fstr->bv_len++] = '(';
1569                 switch ( f->f_choice ) {
1570                 case LDAP_FILTER_AND:
1571                         fstr->bv_val[fstr->bv_len] = '&';
1572                         break;
1573                 case LDAP_FILTER_OR:
1574                         fstr->bv_val[fstr->bv_len] = '|';
1575                         break;
1576                 case LDAP_FILTER_NOT:
1577                         fstr->bv_val[fstr->bv_len] = '!';
1578                         break;
1579                 }
1580                 fstr->bv_len++;
1581
1582                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1583                         rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1584                                 filter_got_oc );
1585                         if ( rc ) break;
1586                 }
1587                 fstr->bv_val[fstr->bv_len++] = ')';
1588                 fstr->bv_val[fstr->bv_len] = '\0';
1589
1590                 return rc;
1591                 }
1592
1593         default:
1594                 /* a filter should at least have room for "()",
1595                  * an "=" and for a 1-char attr */
1596                 strcpy( fstr->bv_val, "(?=)" );
1597                 fstr->bv_len += STRLENOF("(?=)");
1598                 return -1;
1599         }
1600
1601         if ( filter_attrs != NULL ) {
1602                 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1603                                 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1604
1605                 (*filter_attrs)[*filter_cnt].an_desc = ad;
1606                 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1607                 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1608                 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1609                 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1610                 (*filter_cnt)++;
1611                 if ( ad == slap_schema.si_ad_objectClass )
1612                         *filter_got_oc = 1;
1613         }
1614
1615         return 0;
1616 }
1617
1618 struct search_info {
1619         slap_overinst *on;
1620         Query query;
1621         QueryTemplate *qtemp;
1622         AttributeName*  save_attrs;     /* original attributes, saved for response */
1623         int swap_saved_attrs;
1624         int max;
1625         int over;
1626         int count;
1627         int slimit;
1628         int slimit_exceeded;
1629         pc_caching_reason_t caching_reason;
1630         Entry *head, *tail;
1631 };
1632
1633 static void
1634 remove_query_and_data(
1635         Operation       *op,
1636         SlapReply       *rs,
1637         cache_manager   *cm,
1638         struct berval   *uuid )
1639 {
1640         query_manager*          qm = cm->qm;
1641
1642         qm->crfunc( qm, uuid );
1643         if ( !BER_BVISNULL( uuid ) ) {
1644                 int     return_val;
1645
1646                 Debug( pcache_debug,
1647                         "Removing query UUID %s\n",
1648                         uuid->bv_val, 0, 0 );
1649                 return_val = remove_query_data( op, rs, uuid );
1650                 Debug( pcache_debug,
1651                         "QUERY REMOVED, SIZE=%d\n",
1652                         return_val, 0, 0);
1653                 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1654                 cm->cur_entries -= return_val;
1655                 cm->num_cached_queries--;
1656                 Debug( pcache_debug,
1657                         "STORED QUERIES = %lu\n",
1658                         cm->num_cached_queries, 0, 0 );
1659                 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1660                 Debug( pcache_debug,
1661                         "QUERY REMOVED, CACHE ="
1662                         "%d entries\n",
1663                         cm->cur_entries, 0, 0 );
1664         }
1665 }
1666
1667 /*
1668  * Callback used to fetch queryId values based on entryUUID;
1669  * used by pcache_remove_entries_from_cache()
1670  */
1671 static int
1672 fetch_queryId_cb( Operation *op, SlapReply *rs )
1673 {
1674         int             rc = 0;
1675
1676         /* only care about searchEntry responses */
1677         if ( rs->sr_type != REP_SEARCH ) {
1678                 return 0;
1679         }
1680
1681         /* allow only one response per entryUUID */
1682         if ( op->o_callback->sc_private != NULL ) {
1683                 rc = 1;
1684
1685         } else {
1686                 Attribute       *a;
1687
1688                 /* copy all queryId values into callback's private data */
1689                 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1690                 if ( a != NULL ) {
1691                         BerVarray       vals = NULL;
1692
1693                         ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1694                         op->o_callback->sc_private = (void *)vals;
1695                 }
1696         }
1697
1698         /* clear entry if required */
1699         if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1700                 entry_free( rs->sr_entry );
1701                 rs->sr_entry = NULL;
1702                 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1703         }
1704
1705         return rc;
1706 }
1707
1708 /*
1709  * Call that allows to remove a set of entries from the cache,
1710  * by forcing the removal of all the related queries.
1711  */
1712 int
1713 pcache_remove_entries_from_cache(
1714         Operation       *op,
1715         cache_manager   *cm,
1716         BerVarray       entryUUIDs )
1717 {
1718         Connection      conn = { 0 };
1719         OperationBuffer opbuf;
1720         Operation       op2;
1721         slap_callback   sc = { 0 };
1722         SlapReply       rs = { REP_RESULT };
1723         Filter          f = { 0 };
1724         char            filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1725         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1726         AttributeName   attrs[ 2 ] = {{{ 0 }}};
1727         int             s, rc;
1728
1729         if ( op == NULL ) {
1730                 void    *thrctx = ldap_pvt_thread_pool_context();
1731
1732                 connection_fake_init( &conn, &opbuf, thrctx );
1733                 op = &opbuf.ob_op;
1734
1735         } else {
1736                 op2 = *op;
1737                 op = &op2;
1738         }
1739
1740         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1741         op->ors_scope = LDAP_SCOPE_SUBTREE;
1742         op->ors_deref = LDAP_DEREF_NEVER;
1743         f.f_choice = LDAP_FILTER_EQUALITY;
1744         f.f_ava = &ava;
1745         ava.aa_desc = slap_schema.si_ad_entryUUID;
1746         op->ors_filter = &f;
1747         op->ors_slimit = 1;
1748         op->ors_tlimit = SLAP_NO_LIMIT;
1749         attrs[ 0 ].an_desc = ad_queryId;
1750         attrs[ 0 ].an_name = ad_queryId->ad_cname;
1751         op->ors_attrs = attrs;
1752         op->ors_attrsonly = 0;
1753
1754         op->o_req_dn = cm->db.be_suffix[ 0 ];
1755         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1756
1757         op->o_tag = LDAP_REQ_SEARCH;
1758         op->o_protocol = LDAP_VERSION3;
1759         op->o_managedsait = SLAP_CONTROL_CRITICAL;
1760         op->o_bd = &cm->db;
1761         op->o_dn = op->o_bd->be_rootdn;
1762         op->o_ndn = op->o_bd->be_rootndn;
1763         sc.sc_response = fetch_queryId_cb;
1764         op->o_callback = &sc;
1765
1766         for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1767                 BerVarray       vals = NULL;
1768
1769                 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1770                         "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1771                 op->ors_filterstr.bv_val = filtbuf;
1772                 ava.aa_value = entryUUIDs[ s ];
1773
1774                 rc = op->o_bd->be_search( op, &rs );
1775                 if ( rc != LDAP_SUCCESS ) {
1776                         continue;
1777                 }
1778
1779                 vals = (BerVarray)op->o_callback->sc_private;
1780                 if ( vals != NULL ) {
1781                         int             i;
1782
1783                         for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1784                                 struct berval   val = vals[ i ];
1785
1786                                 remove_query_and_data( op, &rs, cm, &val );
1787
1788                                 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1789                                         ch_free( val.bv_val );
1790                                 }
1791                         }
1792
1793                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1794                         op->o_callback->sc_private = NULL;
1795                 }
1796         }
1797
1798         return 0;
1799 }
1800
1801 /*
1802  * Call that allows to remove a query from the cache.
1803  */
1804 int
1805 pcache_remove_query_from_cache(
1806         Operation       *op,
1807         cache_manager   *cm,
1808         struct berval   *queryid )
1809 {
1810         Operation       op2 = *op;
1811         SlapReply       rs2 = { 0 };
1812
1813         op2.o_bd = &cm->db;
1814
1815         /* remove the selected query */
1816         remove_query_and_data( &op2, &rs2, cm, queryid );
1817
1818         return LDAP_SUCCESS;
1819 }
1820
1821 /*
1822  * Call that allows to remove a set of queries related to an entry 
1823  * from the cache; if queryid is not null, the entry must belong to
1824  * the query indicated by queryid.
1825  */
1826 int
1827 pcache_remove_entry_queries_from_cache(
1828         Operation       *op,
1829         cache_manager   *cm,
1830         struct berval   *ndn,
1831         struct berval   *queryid )
1832 {
1833         Connection              conn = { 0 };
1834         OperationBuffer         opbuf;
1835         Operation               op2;
1836         slap_callback           sc = { 0 };
1837         SlapReply               rs = { REP_RESULT };
1838         Filter                  f = { 0 };
1839         char                    filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1840         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
1841         AttributeName           attrs[ 2 ] = {{{ 0 }}};
1842         int                     rc;
1843
1844         BerVarray               vals = NULL;
1845
1846         if ( op == NULL ) {
1847                 void    *thrctx = ldap_pvt_thread_pool_context();
1848
1849                 connection_fake_init( &conn, &opbuf, thrctx );
1850                 op = &opbuf.ob_op;
1851
1852         } else {
1853                 op2 = *op;
1854                 op = &op2;
1855         }
1856
1857         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1858         op->ors_scope = LDAP_SCOPE_BASE;
1859         op->ors_deref = LDAP_DEREF_NEVER;
1860         if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1861                 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1862                 f.f_choice = LDAP_FILTER_PRESENT;
1863                 f.f_desc = slap_schema.si_ad_objectClass;
1864
1865         } else {
1866                 op->ors_filterstr.bv_len = snprintf( filter_str,
1867                         sizeof( filter_str ), "(%s=%s)",
1868                         ad_queryId->ad_cname.bv_val, queryid->bv_val );
1869                 f.f_choice = LDAP_FILTER_EQUALITY;
1870                 f.f_ava = &ava;
1871                 f.f_av_desc = ad_queryId;
1872                 f.f_av_value = *queryid;
1873         }
1874         op->ors_filter = &f;
1875         op->ors_slimit = 1;
1876         op->ors_tlimit = SLAP_NO_LIMIT;
1877         attrs[ 0 ].an_desc = ad_queryId;
1878         attrs[ 0 ].an_name = ad_queryId->ad_cname;
1879         op->ors_attrs = attrs;
1880         op->ors_attrsonly = 0;
1881
1882         op->o_req_dn = *ndn;
1883         op->o_req_ndn = *ndn;
1884
1885         op->o_tag = LDAP_REQ_SEARCH;
1886         op->o_protocol = LDAP_VERSION3;
1887         op->o_managedsait = SLAP_CONTROL_CRITICAL;
1888         op->o_bd = &cm->db;
1889         op->o_dn = op->o_bd->be_rootdn;
1890         op->o_ndn = op->o_bd->be_rootndn;
1891         sc.sc_response = fetch_queryId_cb;
1892         op->o_callback = &sc;
1893
1894         rc = op->o_bd->be_search( op, &rs );
1895         if ( rc != LDAP_SUCCESS ) {
1896                 return rc;
1897         }
1898
1899         vals = (BerVarray)op->o_callback->sc_private;
1900         if ( vals != NULL ) {
1901                 int             i;
1902
1903                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1904                         struct berval   val = vals[ i ];
1905
1906                         remove_query_and_data( op, &rs, cm, &val );
1907
1908                         if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1909                                 ch_free( val.bv_val );
1910                         }
1911                 }
1912
1913                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1914         }
1915
1916         return LDAP_SUCCESS;
1917 }
1918
1919 static int
1920 cache_entries(
1921         Operation       *op,
1922         SlapReply       *rs,
1923         struct berval *query_uuid )
1924 {
1925         struct search_info *si = op->o_callback->sc_private;
1926         slap_overinst *on = si->on;
1927         cache_manager *cm = on->on_bi.bi_private;
1928         int             return_val = 0;
1929         Entry           *e;
1930         struct berval   crp_uuid;
1931         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1932         Operation       *op_tmp;
1933         Connection      conn = {0};
1934         OperationBuffer opbuf;
1935         void            *thrctx = ldap_pvt_thread_pool_context();
1936
1937         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1938         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1939
1940         connection_fake_init2( &conn, &opbuf, thrctx, 0 );
1941         op_tmp = &opbuf.ob_op;
1942         op_tmp->o_bd = &cm->db;
1943         op_tmp->o_dn = cm->db.be_rootdn;
1944         op_tmp->o_ndn = cm->db.be_rootndn;
1945
1946         Debug( pcache_debug, "UUID for query being added = %s\n",
1947                         uuidbuf, 0, 0 );
1948
1949         for ( e=si->head; e; e=si->head ) {
1950                 si->head = e->e_private;
1951                 e->e_private = NULL;
1952                 while ( cm->cur_entries > (cm->max_entries) ) {
1953                         BER_BVZERO( &crp_uuid );
1954                         remove_query_and_data( op_tmp, rs, cm, &crp_uuid );
1955                 }
1956
1957                 return_val = merge_entry(op_tmp, e, query_uuid);
1958                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1959                 cm->cur_entries += return_val;
1960                 Debug( pcache_debug,
1961                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1962                         cm->cur_entries, 0, 0 );
1963                 return_val = 0;
1964                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1965         }
1966
1967         return return_val;
1968 }
1969
1970 static int
1971 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1972         slap_callback   *cb = op->o_callback;
1973         struct search_info *si = cb->sc_private;
1974         slap_overinst *on = si->on;
1975         cache_manager *cm = on->on_bi.bi_private;
1976         query_manager*          qm = cm->qm;
1977
1978         if ( rs->sr_type == REP_SEARCH ) {
1979                 Entry *e;
1980
1981                 /* don't return more entries than requested by the client */
1982                 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
1983                         si->slimit_exceeded = 1;
1984                 }
1985
1986                 /* If we haven't exceeded the limit for this query,
1987                  * build a chain of answers to store. If we hit the
1988                  * limit, empty the chain and ignore the rest.
1989                  */
1990                 if ( !si->over ) {
1991                         /* check if the entry contains undefined
1992                          * attributes/objectClasses (ITS#5680) */
1993                         if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
1994                                 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
1995                                         op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
1996                                 goto over;
1997                         }
1998
1999                         /* check for malformed entries: attrs with no values */
2000                         {
2001                                 Attribute *a = rs->sr_entry->e_attrs;
2002                                 for (; a; a=a->a_next) {
2003                                         if ( !a->a_numvals ) {
2004                                                 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2005                                                 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2006                                                 a->a_desc->ad_cname.bv_val );
2007                                                 goto over;
2008                                         }
2009                                 }
2010                         }
2011
2012                         if ( si->count < si->max ) {
2013                                 si->count++;
2014                                 e = entry_dup( rs->sr_entry );
2015                                 if ( !si->head ) si->head = e;
2016                                 if ( si->tail ) si->tail->e_private = e;
2017                                 si->tail = e;
2018
2019                         } else {
2020 over:;
2021                                 si->over = 1;
2022                                 si->count = 0;
2023                                 for (;si->head; si->head=e) {
2024                                         e = si->head->e_private;
2025                                         si->head->e_private = NULL;
2026                                         entry_free(si->head);
2027                                 }
2028                                 si->tail = NULL;
2029                         }
2030                 }
2031
2032         }
2033
2034         if ( rs->sr_type == REP_RESULT || 
2035                 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2036         {
2037                 if ( si->swap_saved_attrs ) {
2038                         rs->sr_attrs = si->save_attrs;
2039                         op->ors_attrs = si->save_attrs;
2040                 }
2041                 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) && 
2042                                 si->caching_reason == PC_IGNORE ) {
2043                         filter_free( si->query.filter );
2044                         if ( si->count ) {
2045                                 /* duplicate query, free it */
2046                                 Entry *e;
2047                                 for (;si->head; si->head=e) {
2048                                         e = si->head->e_private;
2049                                         si->head->e_private = NULL;
2050                                         entry_free(si->head);
2051                                 }
2052                         }
2053                         op->o_callback = op->o_callback->sc_next;
2054                         op->o_tmpfree( cb, op->o_tmpmemctx );
2055                 } else if ( si->caching_reason != PC_IGNORE ) {
2056                         CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2057                                 si->qtemp, si->caching_reason, 1 );
2058
2059                         if ( qc != NULL ) {
2060                                 switch ( si->caching_reason ) {
2061                                 case PC_POSITIVE:
2062                                         cache_entries( op, rs, &qc->q_uuid );
2063                                         break;
2064
2065                                 case PC_SIZELIMIT:
2066                                         qc->q_sizelimit = rs->sr_nentries;
2067                                         break;
2068
2069                                 case PC_NEGATIVE:
2070                                         break;
2071
2072                                 default:
2073                                         assert( 0 );
2074                                         break;
2075                                 }
2076                                 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2077                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2078                                 cm->num_cached_queries++;
2079                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2080                                                 cm->num_cached_queries, 0, 0 );
2081                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2082
2083                                 /* If the consistency checker suspended itself,
2084                                  * wake it back up
2085                                  */
2086                                 if ( cm->cc_paused ) {
2087                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2088                                         if ( cm->cc_paused ) {
2089                                                 cm->cc_paused = 0;
2090                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2091                                         }
2092                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2093                                 }
2094
2095                         } else if ( si->count ) {
2096                                 /* duplicate query, free it */
2097                                 Entry *e;
2098                                 for (;si->head; si->head=e) {
2099                                         e = si->head->e_private;
2100                                         si->head->e_private = NULL;
2101                                         entry_free(si->head);
2102                                 }
2103                         }
2104
2105                 } else {
2106                         filter_free( si->query.filter );
2107                 }
2108         }
2109
2110         return SLAP_CB_CONTINUE;
2111 }
2112
2113 static int
2114 pcache_response(
2115         Operation       *op,
2116         SlapReply       *rs )
2117 {
2118         struct search_info *si = op->o_callback->sc_private;
2119
2120         if ( si->swap_saved_attrs ) {
2121                 rs->sr_attrs = si->save_attrs;
2122                 op->ors_attrs = si->save_attrs;
2123         }
2124
2125         if ( rs->sr_type == REP_SEARCH ) {
2126                 /* don't return more entries than requested by the client */
2127                 if ( si->slimit_exceeded ) {
2128                         return 0;
2129                 }
2130
2131         } else if ( rs->sr_type == REP_RESULT ) {
2132
2133                 if ( si->count ) {
2134                         if ( rs->sr_err == LDAP_SUCCESS ) {
2135                                 si->caching_reason = PC_POSITIVE;
2136
2137                         } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2138                                 && si->qtemp->limitttl )
2139                         {
2140                                 si->caching_reason = PC_SIZELIMIT;
2141                         }
2142
2143                 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2144                                 rs->sr_err == LDAP_SUCCESS )
2145                 {
2146                         si->caching_reason = PC_NEGATIVE;
2147                 }
2148
2149
2150                 if ( si->slimit_exceeded ) {
2151                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2152                 }
2153         }
2154
2155         return SLAP_CB_CONTINUE;
2156 }
2157
2158 static int
2159 add_filter_attrs(
2160         Operation *op,
2161         AttributeName** new_attrs,
2162         struct attr_set *attrs,
2163         AttributeName* filter_attrs,
2164         int fattr_cnt,
2165         int fattr_got_oc)
2166 {
2167         int alluser = 0;
2168         int allop = 0;
2169         int i, j;
2170         int count;
2171         int addoc = 0;
2172
2173         /* duplicate attrs */
2174         count = attrs->count + fattr_cnt;
2175         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2176                 addoc = 1;
2177                 count++;
2178         }
2179
2180         *new_attrs = (AttributeName*)ch_calloc( count + 1,
2181                 sizeof(AttributeName) );
2182         for (i=0; i<attrs->count; i++) {
2183                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2184                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2185         }
2186         BER_BVZERO( &(*new_attrs)[i].an_name );
2187         alluser = an_find( *new_attrs, slap_bv_all_user_attrs );
2188         allop = an_find( *new_attrs, slap_bv_all_operational_attrs );
2189
2190         j = i;
2191         for ( i=0; i<fattr_cnt; i++ ) {
2192                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2193                         continue;
2194                 }
2195                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2196                         if ( allop ) {
2197                                 continue;
2198                         }
2199                 } else if ( alluser ) {
2200                         continue;
2201                 }
2202                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2203                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2204                 (*new_attrs)[j].an_oc = NULL;
2205                 (*new_attrs)[j].an_oc_exclude = 0;
2206                 j++;
2207         }
2208         if ( addoc ) {
2209                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2210                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2211                 (*new_attrs)[j].an_oc = NULL;
2212                 (*new_attrs)[j].an_oc_exclude = 0;
2213                 j++;
2214         }
2215         BER_BVZERO( &(*new_attrs)[j].an_name );
2216
2217         return j;
2218 }
2219
2220 /* NOTE: this is a quick workaround to let pcache minimally interact
2221  * with pagedResults.  A more articulated solutions would be to
2222  * perform the remote query without control and cache all results,
2223  * performing the pagedResults search only within the client
2224  * and the proxy.  This requires pcache to understand pagedResults. */
2225 static int
2226 pcache_chk_controls(
2227         Operation       *op,
2228         SlapReply       *rs )
2229 {
2230         const char      *non = "";
2231         const char      *stripped = "";
2232
2233         switch( op->o_pagedresults ) {
2234         case SLAP_CONTROL_NONCRITICAL:
2235                 non = "non-";
2236                 stripped = "; stripped";
2237                 /* fallthru */
2238
2239         case SLAP_CONTROL_CRITICAL:
2240                 Debug( pcache_debug, "%s: "
2241                         "%scritical pagedResults control "
2242                         "disabled with proxy cache%s.\n",
2243                         op->o_log_prefix, non, stripped );
2244                 
2245                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2246                 break;
2247
2248         default:
2249                 rs->sr_err = SLAP_CB_CONTINUE;
2250                 break;
2251         }
2252
2253         return rs->sr_err;
2254 }
2255
2256 #ifdef PCACHE_CONTROL_PRIVDB
2257 static int
2258 pcache_op_privdb(
2259         Operation               *op,
2260         SlapReply               *rs )
2261 {
2262         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
2263         cache_manager   *cm = on->on_bi.bi_private;
2264         slap_callback   *save_cb;
2265         slap_op_t       type;
2266
2267         /* skip if control is unset */
2268         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2269                 return SLAP_CB_CONTINUE;
2270         }
2271
2272         /* The cache DB isn't open yet */
2273         if ( cm->defer_db_open ) {
2274                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2275                         "pcachePrivDB: cacheDB not available" );
2276                 return rs->sr_err;
2277         }
2278
2279         /* FIXME: might be a little bit exaggerated... */
2280         if ( !be_isroot( op ) ) {
2281                 save_cb = op->o_callback;
2282                 op->o_callback = NULL;
2283                 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2284                         "pcachePrivDB: operation not allowed" );
2285                 op->o_callback = save_cb;
2286
2287                 return rs->sr_err;
2288         }
2289
2290         /* map tag to operation */
2291         type = slap_req2op( op->o_tag );
2292         if ( type != SLAP_OP_LAST ) {
2293                 BI_op_func      **func;
2294                 int             rc;
2295
2296                 /* execute, if possible */
2297                 func = &cm->db.be_bind;
2298                 if ( func[ type ] != NULL ) {
2299                         Operation       op2 = *op;
2300         
2301                         op2.o_bd = &cm->db;
2302
2303                         rc = func[ type ]( &op2, rs );
2304                         if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2305                                 op->o_conn->c_authz_cookie = cm->db.be_private;
2306                         }
2307                 }
2308         }
2309
2310         /* otherwise fall back to error */
2311         save_cb = op->o_callback;
2312         op->o_callback = NULL;
2313         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2314                 "operation not supported with pcachePrivDB control" );
2315         op->o_callback = save_cb;
2316
2317         return rs->sr_err;
2318 }
2319 #endif /* PCACHE_CONTROL_PRIVDB */
2320
2321 static int
2322 pcache_op_search(
2323         Operation       *op,
2324         SlapReply       *rs )
2325 {
2326         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2327         cache_manager *cm = on->on_bi.bi_private;
2328         query_manager*          qm = cm->qm;
2329
2330         int i = -1;
2331
2332         AttributeName   *filter_attrs = NULL;
2333
2334         Query           query;
2335         QueryTemplate   *qtemp = NULL;
2336
2337         int             attr_set = -1;
2338         CachedQuery     *answerable = NULL;
2339         int             cacheable = 0;
2340         int             fattr_cnt=0;
2341         int             fattr_got_oc = 0;
2342
2343         struct berval   tempstr;
2344
2345 #ifdef PCACHE_CONTROL_PRIVDB
2346         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2347                 return pcache_op_privdb( op, rs );
2348         }
2349 #endif /* PCACHE_CONTROL_PRIVDB */
2350
2351         /* The cache DB isn't open yet */
2352         if ( cm->defer_db_open ) {
2353                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2354                         "pcachePrivDB: cacheDB not available" );
2355                 return rs->sr_err;
2356         }
2357
2358         /* pickup runtime ACL changes */
2359         cm->db.be_acl = op->o_bd->be_acl;
2360
2361         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2362         tempstr.bv_len = 0;
2363         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2364                 &fattr_cnt, &fattr_got_oc )) {
2365                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2366                 return SLAP_CB_CONTINUE;
2367         }
2368
2369         Debug( pcache_debug, "query template of incoming query = %s\n",
2370                                         tempstr.bv_val, 0, 0 );
2371
2372         /* FIXME: cannot cache/answer requests with pagedResults control */
2373
2374         /* find attr set */
2375         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2376
2377         query.filter = op->ors_filter;
2378         query.base = op->o_req_ndn;
2379         query.scope = op->ors_scope;
2380
2381         /* check for query containment */
2382         if (attr_set > -1) {
2383                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2384                 for (; qt; qt = qt->qtnext ) {
2385                         /* find if template i can potentially answer tempstr */
2386                         if (qt->querystr.bv_len != tempstr.bv_len ||
2387                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2388                                 continue;
2389                         cacheable = 1;
2390                         qtemp = qt;
2391                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
2392                                         op->ors_filterstr.bv_val, 0, 0 );
2393                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2394
2395                         if (answerable)
2396                                 break;
2397                 }
2398         }
2399         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2400
2401         if (answerable) {
2402                 BackendDB       *save_bd = op->o_bd;
2403                 slap_callback   *save_cb = op->o_callback;
2404
2405                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2406                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2407                 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
2408                 if ( BER_BVISNULL( &answerable->q_uuid )) {
2409                         /* No entries cached, just an empty result set */
2410                         i = rs->sr_err = 0;
2411                         send_ldap_result( op, rs );
2412                 } else {
2413                         op->o_bd = &cm->db;
2414                         if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
2415                                 /* The cached entry was already processed by any
2416                                  * other overlays, so don't let it get processed again.
2417                                  */
2418                                 op->o_callback = NULL;
2419                         }
2420                         i = cm->db.bd_info->bi_op_search( op, rs );
2421                 }
2422                 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
2423                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2424                 op->o_bd = save_bd;
2425                 op->o_callback = save_cb;
2426                 return i;
2427         }
2428
2429         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2430
2431         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2432         if (cm->num_cached_queries >= cm->max_queries) {
2433                 cacheable = 0;
2434         }
2435         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2436
2437         if (op->ors_attrsonly)
2438                 cacheable = 0;
2439
2440         if (cacheable) {
2441                 slap_callback           *cb;
2442                 struct search_info      *si;
2443
2444                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2445                 query.filter = filter_dup(op->ors_filter, NULL);
2446                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2447                 if ( !qtemp->t_attrs.count ) {
2448                         qtemp->t_attrs.count = add_filter_attrs(op,
2449                                 &qtemp->t_attrs.attrs,
2450                                 &qm->attr_sets[attr_set],
2451                                 filter_attrs, fattr_cnt, fattr_got_oc);
2452                 }
2453                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2454
2455                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2456                 cb->sc_response = pcache_response;
2457                 cb->sc_cleanup = pcache_op_cleanup;
2458                 cb->sc_private = (cb+1);
2459                 si = cb->sc_private;
2460                 si->on = on;
2461                 si->query = query;
2462                 si->qtemp = qtemp;
2463                 si->max = cm->num_entries_limit ;
2464                 si->over = 0;
2465                 si->count = 0;
2466                 si->slimit = 0;
2467                 si->slimit_exceeded = 0;
2468                 si->caching_reason = PC_IGNORE;
2469                 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
2470                         si->slimit = op->ors_slimit;
2471                         op->ors_slimit = cm->num_entries_limit;
2472                 }
2473                 si->head = NULL;
2474                 si->tail = NULL;
2475                 si->swap_saved_attrs = 1;
2476                 si->save_attrs = op->ors_attrs;
2477
2478                 op->ors_attrs = qtemp->t_attrs.attrs;
2479
2480                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2481                         cb->sc_next = op->o_callback;
2482                         op->o_callback = cb;
2483
2484                 } else {
2485                         slap_callback           **pcb;
2486
2487                         /* need to move the callback at the end, in case other
2488                          * overlays are present, so that the final entry is
2489                          * actually cached */
2490                         cb->sc_next = NULL;
2491                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2492                         *pcb = cb;
2493                 }
2494
2495         } else {
2496                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2497                                         0, 0, 0);
2498         }
2499
2500         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2501
2502         return SLAP_CB_CONTINUE;
2503 }
2504
2505 static int
2506 get_attr_set(
2507         AttributeName* attrs,
2508         query_manager* qm,
2509         int num )
2510 {
2511         int i;
2512         int count = 0;
2513
2514         if ( attrs ) {
2515                 for ( ; attrs[count].an_name.bv_val; count++ );
2516         }
2517
2518         /* recognize a single "*" or a "1.1" */
2519         if ( count == 0 ) {
2520                 count = 1;
2521                 attrs = slap_anlist_all_user_attributes;
2522
2523         } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2524                 count = 0;
2525                 attrs = NULL;
2526         }
2527
2528         for ( i = 0; i < num; i++ ) {
2529                 AttributeName *a2;
2530                 int found = 1;
2531
2532                 if ( count > qm->attr_sets[i].count ) {
2533                         continue;
2534                 }
2535
2536                 if ( !count ) {
2537                         if ( !qm->attr_sets[i].count ) {
2538                                 break;
2539                         }
2540                         continue;
2541                 }
2542
2543                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2544                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2545                                 found = 0;
2546                                 break;
2547                         }
2548                 }
2549
2550                 if ( found ) {
2551                         break;
2552                 }
2553         }
2554
2555         if ( i == num ) {
2556                 i = -1;
2557         }
2558
2559         return i;
2560 }
2561
2562 static void*
2563 consistency_check(
2564         void *ctx,
2565         void *arg )
2566 {
2567         struct re_s *rtask = arg;
2568         slap_overinst *on = rtask->arg;
2569         cache_manager *cm = on->on_bi.bi_private;
2570         query_manager *qm = cm->qm;
2571         Connection conn = {0};
2572         OperationBuffer opbuf;
2573         Operation *op;
2574
2575         SlapReply rs = {REP_RESULT};
2576         CachedQuery* query;
2577         int return_val, pause = 1;
2578         QueryTemplate* templ;
2579
2580         connection_fake_init( &conn, &opbuf, ctx );
2581         op = &opbuf.ob_op;
2582
2583         op->o_bd = &cm->db;
2584         op->o_dn = cm->db.be_rootdn;
2585         op->o_ndn = cm->db.be_rootndn;
2586
2587         cm->cc_arg = arg;
2588
2589         for (templ = qm->templates; templ; templ=templ->qmnext) {
2590                 query = templ->query_last;
2591                 if ( query ) pause = 0;
2592                 op->o_time = slap_get_time();
2593                 while (query && (query->expiry_time < op->o_time)) {
2594                         int rem = 0;
2595                         Debug( pcache_debug, "Lock CR index = %p\n",
2596                                         (void *) templ, 0, 0 );
2597                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2598                         if ( query == templ->query_last ) {
2599                                 rem = 1;
2600                                 remove_from_template(query, templ);
2601                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2602                                                 (void *) templ, templ->no_of_queries, 0 );
2603                                 Debug( pcache_debug, "Unlock CR index = %p\n",
2604                                                 (void *) templ, 0, 0 );
2605                         }
2606                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2607                         if ( !rem ) {
2608                                 query = templ->query_last;
2609                                 continue;
2610                         }
2611                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2612                         remove_query(qm, query);
2613                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2614                         if ( BER_BVISNULL( &query->q_uuid ))
2615                                 return_val = 0;
2616                         else
2617                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
2618                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2619                                                 return_val, 0, 0 );
2620                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2621                         cm->cur_entries -= return_val;
2622                         cm->num_cached_queries--;
2623                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
2624                                         cm->num_cached_queries, 0, 0 );
2625                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2626                         Debug( pcache_debug,
2627                                 "STALE QUERY REMOVED, CACHE ="
2628                                 "%d entries\n",
2629                                 cm->cur_entries, 0, 0 );
2630                         free_query(query);
2631                         query = templ->query_last;
2632                 }
2633         }
2634         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2635         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2636                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2637         }
2638         /* If there were no queries, defer processing for a while */
2639         cm->cc_paused = pause;
2640         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2641
2642         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2643         return NULL;
2644 }
2645
2646
2647 #define MAX_ATTR_SETS 500
2648
2649 enum {
2650         PC_MAIN = 1,
2651         PC_ATTR,
2652         PC_TEMP,
2653         PC_RESP,
2654         PC_QUERIES
2655 };
2656
2657 static ConfigDriver pc_cf_gen;
2658 static ConfigLDAPadd pc_ldadd;
2659 static ConfigCfAdd pc_cfadd;
2660
2661 static ConfigTable pccfg[] = {
2662         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2663                                 "<cycle_time",
2664                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2665                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2666                         "DESC 'ProxyCache basic parameters' "
2667                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2668         { "proxyattrset", "index> <attributes...",
2669                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2670                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2671                         "DESC 'A set of attributes to cache' "
2672                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2673         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2674                 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2675                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2676                         "DESC 'Filter template, attrset, cache TTL, "
2677                                 "optional negative TTL, optional sizelimit TTL' "
2678                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2679         { "response-callback", "head|tail(default)",
2680                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2681                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2682                         "DESC 'Response callback position in overlay stack' "
2683                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2684         { "proxyCacheQueries", "queries",
2685                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2686                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2687                         "DESC 'Maximum number of queries to cache' "
2688                         "SYNTAX OMsInteger )", NULL, NULL },
2689         { "proxySaveQueries", "TRUE|FALSE",
2690                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2691                 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2692                         "DESC 'Save cached queries for hot restart' "
2693                         "SYNTAX OMsBoolean )", NULL, NULL },
2694         { "proxyCheckCacheability", "TRUE|FALSE",
2695                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
2696                 "( OLcfgOvAt:2.7 NAME 'olcProxyCheckCacheability' "
2697                         "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
2698                         "SYNTAX OMsBoolean )", NULL, NULL },
2699
2700         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2701 };
2702
2703 static ConfigOCs pcocs[] = {
2704         { "( OLcfgOvOc:2.1 "
2705                 "NAME 'olcPcacheConfig' "
2706                 "DESC 'ProxyCache configuration' "
2707                 "SUP olcOverlayConfig "
2708                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2709                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries $ olcProxyCheckCacheability ) )",
2710                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2711         { "( OLcfgOvOc:2.2 "
2712                 "NAME 'olcPcacheDatabase' "
2713                 "DESC 'Cache database configuration' "
2714                 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
2715         { NULL, 0, NULL }
2716 };
2717
2718 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
2719
2720 static int
2721 pc_ldadd_cleanup( ConfigArgs *c )
2722 {
2723         slap_overinst *on = c->ca_private;
2724         return pcache_db_open2( on, &c->reply );
2725 }
2726
2727 static int
2728 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2729 {
2730         slap_overinst *on;
2731         cache_manager *cm;
2732
2733         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2734                 p->ce_bi->bi_cf_ocs != pcocs )
2735                 return LDAP_CONSTRAINT_VIOLATION;
2736
2737         on = (slap_overinst *)p->ce_bi;
2738         cm = on->on_bi.bi_private;
2739         ca->be = &cm->db;
2740         /* Defer open if this is an LDAPadd */
2741         if ( CONFIG_ONLINE_ADD( ca ))
2742                 ca->cleanup = pc_ldadd_cleanup;
2743         else
2744                 cm->defer_db_open = 0;
2745         ca->ca_private = on;
2746         return LDAP_SUCCESS;
2747 }
2748
2749 static int
2750 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2751 {
2752         CfEntryInfo *pe = p->e_private;
2753         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2754         cache_manager *cm = on->on_bi.bi_private;
2755         struct berval bv;
2756
2757         /* FIXME: should not hardcode "olcDatabase" here */
2758         bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
2759                 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
2760                 0, cm->db.bd_info->bi_type );
2761         if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
2762                 return -1;
2763         }
2764         bv.bv_val = ca->cr_msg;
2765         ca->be = &cm->db;
2766         cm->defer_db_open = 0;
2767
2768         /* We can only create this entry if the database is table-driven
2769          */
2770         if ( cm->db.bd_info->bi_cf_ocs )
2771                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2772                         &pcocs[1] );
2773
2774         return 0;
2775 }
2776
2777 static int
2778 pc_cf_gen( ConfigArgs *c )
2779 {
2780         slap_overinst   *on = (slap_overinst *)c->bi;
2781         cache_manager*  cm = on->on_bi.bi_private;
2782         query_manager*  qm = cm->qm;
2783         QueryTemplate*  temp;
2784         AttributeName*  attr_name;
2785         AttributeName*  attrarray;
2786         const char*     text=NULL;
2787         int             i, num, rc = 0;
2788         char            *ptr;
2789         unsigned long   t;
2790
2791         if ( c->op == SLAP_CONFIG_EMIT ) {
2792                 struct berval bv;
2793                 switch( c->type ) {
2794                 case PC_MAIN:
2795                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2796                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2797                                 cm->num_entries_limit, cm->cc_period );
2798                         bv.bv_val = c->cr_msg;
2799                         value_add_one( &c->rvalue_vals, &bv );
2800                         break;
2801                 case PC_ATTR:
2802                         for (i=0; i<cm->numattrsets; i++) {
2803                                 if ( !qm->attr_sets[i].count ) continue;
2804
2805                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2806
2807                                 /* count the attr length */
2808                                 for ( attr_name = qm->attr_sets[i].attrs;
2809                                         attr_name->an_name.bv_val; attr_name++ )
2810                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2811
2812                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2813                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2814                                 for ( attr_name = qm->attr_sets[i].attrs;
2815                                         attr_name->an_name.bv_val; attr_name++ ) {
2816                                         *ptr++ = ' ';
2817                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2818                                 }
2819                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2820                         }
2821                         if ( !c->rvalue_vals )
2822                                 rc = 1;
2823                         break;
2824                 case PC_TEMP:
2825                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2826                                 /* HEADS-UP: always print all;
2827                                  * if optional == 0, ignore */
2828                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2829                                         " %d %ld %ld %ld",
2830                                         temp->attr_set_index,
2831                                         temp->ttl,
2832                                         temp->negttl,
2833                                         temp->limitttl );
2834                                 bv.bv_len += temp->querystr.bv_len + 2;
2835                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2836                                 ptr = bv.bv_val;
2837                                 *ptr++ = '"';
2838                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2839                                 *ptr++ = '"';
2840                                 strcpy( ptr, c->cr_msg );
2841                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2842                         }
2843                         if ( !c->rvalue_vals )
2844                                 rc = 1;
2845                         break;
2846                 case PC_RESP:
2847                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2848                                 BER_BVSTR( &bv, "head" );
2849                         } else {
2850                                 BER_BVSTR( &bv, "tail" );
2851                         }
2852                         value_add_one( &c->rvalue_vals, &bv );
2853                         break;
2854                 case PC_QUERIES:
2855                         c->value_int = cm->max_queries;
2856                         break;
2857                 }
2858                 return rc;
2859         } else if ( c->op == LDAP_MOD_DELETE ) {
2860                 return 1;       /* FIXME */
2861 #if 0
2862                 switch( c->type ) {
2863                 case PC_ATTR:
2864                 case PC_TEMP:
2865                 }
2866                 return rc;
2867 #endif
2868         }
2869
2870         switch( c->type ) {
2871         case PC_MAIN:
2872                 if ( cm->numattrsets > 0 ) {
2873                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2874                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2875                         return( 1 );
2876                 }
2877
2878                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2879                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2880                                 c->argv[3] );
2881                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2882                         return( 1 );
2883                 }
2884                 if ( cm->numattrsets <= 0 ) {
2885                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2886                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2887                         return( 1 );
2888                 }
2889                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2890                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2891                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2892                         return( 1 );
2893                 }
2894
2895                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2896                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2897                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2898                         return( 1 );
2899                 }
2900
2901                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2902                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2903                                 c->argv[2] );
2904                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2905                         return( 1 );
2906                 }
2907                 if ( cm->max_entries <= 0 ) {
2908                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2909                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2910                         return( 1 );
2911                 }
2912
2913                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2914                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2915                                 c->argv[4] );
2916                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2917                         return( 1 );
2918                 }
2919                 if ( cm->num_entries_limit <= 0 ) {
2920                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2921                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2922                         return( 1 );
2923                 }
2924                 if ( cm->num_entries_limit > cm->max_entries ) {
2925                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2926                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2927                         return( 1 );
2928                 }
2929
2930                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2931                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2932                                 c->argv[5] );
2933                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2934                         return( 1 );
2935                 }
2936
2937                 cm->cc_period = (time_t)t;
2938                 Debug( pcache_debug,
2939                                 "Total # of attribute sets to be cached = %d.\n",
2940                                 cm->numattrsets, 0, 0 );
2941                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2942                                                 sizeof( struct attr_set ) );
2943                 break;
2944         case PC_ATTR:
2945                 if ( cm->numattrsets == 0 ) {
2946                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2947                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2948                         return( 1 );
2949                 }
2950                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2951                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2952                                 c->argv[1] );
2953                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2954                         return( 1 );
2955                 }
2956
2957                 if ( num < 0 || num >= cm->numattrsets ) {
2958                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2959                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2960                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2961                         return 1;
2962                 }
2963                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2964                 if ( c->argc == 2 ) {
2965                         /* assume "1.1" */
2966                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2967                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2968                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2969                         return 1;
2970
2971                 } else if ( c->argc == 3 ) {
2972                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2973                                 qm->attr_sets[num].count = 1;
2974                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2975                                         sizeof( AttributeName ) );
2976                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2977                                 break;
2978
2979                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2980                                 qm->attr_sets[num].count = 1;
2981                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2982                                         sizeof( AttributeName ) );
2983                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2984                                 break;
2985
2986                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2987                                 break;
2988                         }
2989                         /* else: fallthru */
2990
2991                 } else if ( c->argc == 4 ) {
2992                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2993                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2994                         {
2995                                 qm->attr_sets[num].count = 2;
2996                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2997                                         sizeof( AttributeName ) );
2998                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2999                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3000                                 break;
3001                         }
3002                         /* else: fallthru */
3003                 }
3004
3005                 if ( c->argc > 2 ) {
3006                         int all_user = 0, all_op = 0;
3007
3008                         qm->attr_sets[num].count = c->argc - 2;
3009                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
3010                                 sizeof( AttributeName ) );
3011                         attr_name = qm->attr_sets[num].attrs;
3012                         for ( i = 2; i < c->argc; i++ ) {
3013                                 attr_name->an_desc = NULL;
3014                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
3015                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3016                                                 "invalid attr #%d \"%s\" in attrlist",
3017                                                 i - 2, c->argv[i] );
3018                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3019                                         ch_free( qm->attr_sets[num].attrs );
3020                                         qm->attr_sets[num].attrs = NULL;
3021                                         qm->attr_sets[num].count = 0;
3022                                         return 1;
3023                                 }
3024                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3025                                         all_user = 1;
3026                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
3027                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3028                                         all_op = 1;
3029                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3030                                 } else {
3031                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
3032                                                 strcpy( c->cr_msg, text );
3033                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3034                                                 ch_free( qm->attr_sets[num].attrs );
3035                                                 qm->attr_sets[num].attrs = NULL;
3036                                                 qm->attr_sets[num].count = 0;
3037                                                 return 1;
3038                                         }
3039                                         attr_name->an_name = attr_name->an_desc->ad_cname;
3040                                 }
3041                                 attr_name->an_oc = NULL;
3042                                 attr_name->an_oc_exclude = 0;
3043                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
3044                                         qm->attr_sets[num].flags |= PC_GOT_OC;
3045                                 attr_name++;
3046                                 BER_BVZERO( &attr_name->an_name );
3047                         }
3048
3049                         /* warn if list contains both "*" and "+" */
3050                         if ( i > 4 && all_user && all_op ) {
3051                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3052                                         "warning: attribute list contains \"*\" and \"+\"" );
3053                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3054                         }
3055                 }
3056                 break;
3057         case PC_TEMP:
3058                 if ( cm->numattrsets == 0 ) {
3059                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3060                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3061                         return( 1 );
3062                 }
3063                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
3064                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
3065                                 c->argv[2] );
3066                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3067                         return( 1 );
3068                 }
3069
3070                 if ( i < 0 || i >= cm->numattrsets || 
3071                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
3072                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
3073                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3074                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3075                         return 1;
3076                 }
3077                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
3078                 temp->qmnext = qm->templates;
3079                 qm->templates = temp;
3080                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
3081                 temp->query = temp->query_last = NULL;
3082                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
3083                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3084                                 "unable to parse template ttl=\"%s\"",
3085                                 c->argv[3] );
3086                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3087                         return( 1 );
3088                 }
3089                 temp->ttl = (time_t)t;
3090                 temp->negttl = (time_t)0;
3091                 temp->limitttl = (time_t)0;
3092                 switch ( c->argc ) {
3093                 case 6:
3094                         if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3095                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3096                                         "unable to parse template sizelimit ttl=\"%s\"",
3097                                         c->argv[5] );
3098                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3099                                         return( 1 );
3100                         }
3101                         temp->limitttl = (time_t)t;
3102                         /* fallthru */
3103
3104                 case 5:
3105                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
3106                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3107                                         "unable to parse template negative ttl=\"%s\"",
3108                                         c->argv[4] );
3109                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3110                                         return( 1 );
3111                         }
3112                         temp->negttl = (time_t)t;
3113                         break;
3114                 }
3115
3116                 temp->no_of_queries = 0;
3117
3118                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3119                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3120                 Debug( pcache_debug, "  query template: %s\n",
3121                                 temp->querystr.bv_val, 0, 0 );
3122                 temp->attr_set_index = i;
3123                 qm->attr_sets[i].flags |= PC_REFERENCED;
3124                 temp->qtnext = qm->attr_sets[i].templates;
3125                 qm->attr_sets[i].templates = temp;
3126                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
3127                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3128                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
3129                                 Debug( pcache_debug, "\t%s\n",
3130                                         attrarray[i].an_name.bv_val, 0, 0 );
3131                 }
3132                 break;
3133         case PC_RESP:
3134                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3135                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3136
3137                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3138                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3139
3140                 } else {
3141                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3142                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3143                         return 1;
3144                 }
3145                 break;
3146         case PC_QUERIES:
3147                 if ( c->value_int <= 0 ) {
3148                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3149                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3150                         return( 1 );
3151                 }
3152                 cm->max_queries = c->value_int;
3153                 break;
3154         }
3155         return rc;
3156 }
3157
3158 static int
3159 pcache_db_config(
3160         BackendDB       *be,
3161         const char      *fname,
3162         int             lineno,
3163         int             argc,
3164         char            **argv
3165 )
3166 {
3167         slap_overinst   *on = (slap_overinst *)be->bd_info;
3168         cache_manager*  cm = on->on_bi.bi_private;
3169
3170         /* Something for the cache database? */
3171         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3172                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3173                         argc, argv );
3174         return SLAP_CONF_UNKNOWN;
3175 }
3176
3177 static int
3178 pcache_db_init(
3179         BackendDB *be,
3180         ConfigReply *cr)
3181 {
3182         slap_overinst *on = (slap_overinst *)be->bd_info;
3183         cache_manager *cm;
3184         query_manager *qm;
3185
3186         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3187         on->on_bi.bi_private = cm;
3188
3189         qm = (query_manager*)ch_malloc(sizeof(query_manager));
3190
3191         cm->db = *be;
3192         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3193         cm->db.be_private = NULL;
3194         cm->db.bd_self = &cm->db;
3195         cm->qm = qm;
3196         cm->numattrsets = 0;
3197         cm->num_entries_limit = 5;
3198         cm->num_cached_queries = 0;
3199         cm->max_entries = 0;
3200         cm->cur_entries = 0;
3201         cm->max_queries = 10000;
3202         cm->save_queries = 0;
3203         cm->check_cacheability = 0;
3204         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3205         cm->defer_db_open = 1;
3206         cm->cc_period = 1000;
3207         cm->cc_paused = 0;
3208         cm->cc_arg = NULL;
3209
3210         qm->attr_sets = NULL;
3211         qm->templates = NULL;
3212         qm->lru_top = NULL;
3213         qm->lru_bottom = NULL;
3214
3215         qm->qcfunc = query_containment;
3216         qm->crfunc = cache_replacement;
3217         qm->addfunc = add_query;
3218         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3219
3220         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3221         return 0;
3222 }
3223
3224 static int
3225 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3226 {
3227         assert( op->o_tag == LDAP_REQ_SEARCH );
3228
3229         if ( rs->sr_type == REP_SEARCH ) {
3230                 Attribute       *a;
3231
3232                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3233                 if ( a != NULL ) {
3234                         BerVarray       *valsp;
3235
3236                         assert( a->a_nvals != NULL );
3237
3238                         valsp = op->o_callback->sc_private;
3239                         assert( *valsp == NULL );
3240
3241                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3242                 }
3243         }
3244
3245         return 0;
3246 }
3247
3248 static int
3249 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3250 {
3251         assert( op->o_tag == LDAP_REQ_SEARCH );
3252
3253         if ( rs->sr_type == REP_SEARCH ) {
3254                 int     *countp = (int *)op->o_callback->sc_private;
3255
3256                 (*countp)++;
3257         }
3258
3259         return 0;
3260 }
3261
3262 static int
3263 pcache_db_open2(
3264         slap_overinst *on,
3265         ConfigReply *cr )
3266 {
3267         cache_manager   *cm = on->on_bi.bi_private;
3268         query_manager*  qm = cm->qm;
3269         int rc;
3270
3271         rc = backend_startup_one( &cm->db, cr );
3272         if ( rc == 0 ) {
3273                 cm->defer_db_open = 0;
3274         }
3275
3276         /* There is no runqueue in TOOL mode */
3277         if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
3278                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3279                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3280                         consistency_check, on,
3281                         "pcache_consistency", cm->db.be_suffix[0].bv_val );
3282                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3283
3284                 /* Cached database must have the rootdn */
3285                 if ( BER_BVISNULL( &cm->db.be_rootndn )
3286                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3287                 {
3288                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3289                                 "underlying database of type \"%s\"\n"
3290                                 "    serving naming context \"%s\"\n"
3291                                 "    has no \"rootdn\", required by \"proxycache\".\n",
3292                                 on->on_info->oi_orig->bi_type,
3293                                 cm->db.be_suffix[0].bv_val, 0 );
3294                         return 1;
3295                 }
3296
3297                 if ( cm->save_queries ) {
3298                         void            *thrctx = ldap_pvt_thread_pool_context();
3299                         Connection      conn = { 0 };
3300                         OperationBuffer opbuf;
3301                         Operation       *op;
3302                         slap_callback   cb = { 0 };
3303                         SlapReply       rs = { 0 };
3304                         BerVarray       vals = NULL;
3305                         Filter          f = { 0 }, f2 = { 0 };
3306                         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
3307                         AttributeName   attrs[ 2 ] = {{{ 0 }}};
3308
3309                         connection_fake_init( &conn, &opbuf, thrctx );
3310                         op = &opbuf.ob_op;
3311
3312                         op->o_bd = &cm->db;
3313
3314                         op->o_tag = LDAP_REQ_SEARCH;
3315                         op->o_protocol = LDAP_VERSION3;
3316                         cb.sc_response = pcache_cachedquery_open_cb;
3317                         cb.sc_private = &vals;
3318                         op->o_callback = &cb;
3319                         op->o_time = slap_get_time();
3320                         op->o_do_not_cache = 1;
3321                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
3322
3323                         op->o_dn = cm->db.be_rootdn;
3324                         op->o_ndn = cm->db.be_rootndn;
3325                         op->o_req_dn = cm->db.be_suffix[ 0 ];
3326                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3327
3328                         op->ors_scope = LDAP_SCOPE_BASE;
3329                         op->ors_deref = LDAP_DEREF_NEVER;
3330                         op->ors_slimit = 1;
3331                         op->ors_tlimit = SLAP_NO_LIMIT;
3332                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3333                         f.f_choice = LDAP_FILTER_PRESENT;
3334                         f.f_desc = ad_cachedQueryURL;
3335                         op->ors_filter = &f;
3336                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
3337                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3338                         op->ors_attrs = attrs;
3339                         op->ors_attrsonly = 0;
3340
3341                         rc = op->o_bd->be_search( op, &rs );
3342                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
3343                                 int     i;
3344
3345                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3346                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3347                                                 cm->num_cached_queries++;
3348                                         }
3349                                 }
3350
3351                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3352                         }
3353
3354                         /* count cached entries */
3355                         f.f_choice = LDAP_FILTER_NOT;
3356                         f.f_not = &f2;
3357                         f2.f_choice = LDAP_FILTER_EQUALITY;
3358                         f2.f_ava = &ava;
3359                         f2.f_av_desc = slap_schema.si_ad_objectClass;
3360                         BER_BVSTR( &f2.f_av_value, "glue" );
3361                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3362
3363                         op->ors_slimit = SLAP_NO_LIMIT;
3364                         op->ors_scope = LDAP_SCOPE_SUBTREE;
3365                         op->ors_attrs = slap_anlist_no_attrs;
3366
3367                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
3368                         rs.sr_nentries = 0;
3369                         op->o_callback->sc_private = &rs.sr_nentries;
3370
3371                         rc = op->o_bd->be_search( op, &rs );
3372
3373                         cm->cur_entries = rs.sr_nentries;
3374
3375                         /* ignore errors */
3376                         rc = 0;
3377                 }
3378         }
3379         return rc;
3380 }
3381
3382 static int
3383 pcache_db_open(
3384         BackendDB *be,
3385         ConfigReply *cr )
3386 {
3387         slap_overinst   *on = (slap_overinst *)be->bd_info;
3388         cache_manager   *cm = on->on_bi.bi_private;
3389         query_manager*  qm = cm->qm;
3390         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3391
3392         /* check attr sets */
3393         for ( i = 0; i < cm->numattrsets; i++) {
3394                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3395                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3396                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3397                                 rf++;
3398
3399                         } else {
3400                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3401                         }
3402                         ncf++;
3403
3404                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3405                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3406                         nrf++;
3407                 }
3408         }
3409
3410         if ( ncf || rf || nrf ) {
3411                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3412                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3413                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3414
3415                 if ( rf > 0 ) {
3416                         return 1;
3417                 }
3418         }
3419
3420         /* need to inherit something from the original database... */
3421         cm->db.be_def_limit = be->be_def_limit;
3422         cm->db.be_limits = be->be_limits;
3423         cm->db.be_acl = be->be_acl;
3424         cm->db.be_dfltaccess = be->be_dfltaccess;
3425
3426         if ( SLAP_DBMONITORING( be ) ) {
3427                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3428
3429         } else {
3430                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3431         }
3432
3433         if ( !cm->defer_db_open )
3434                 rc = pcache_db_open2( on, cr );
3435
3436         return rc;
3437 }
3438
3439 static void
3440 pcache_free_qbase( void *v )
3441 {
3442         Qbase *qb = v;
3443         int i;
3444
3445         for (i=0; i<3; i++)
3446                 tavl_free( qb->scopes[i], NULL );
3447         ch_free( qb );
3448 }
3449
3450 static int
3451 pcache_db_close(
3452         BackendDB *be,
3453         ConfigReply *cr
3454 )
3455 {
3456         slap_overinst *on = (slap_overinst *)be->bd_info;
3457         cache_manager *cm = on->on_bi.bi_private;
3458         query_manager *qm = cm->qm;
3459         QueryTemplate *tm;
3460         int i, rc = 0;
3461
3462         if ( cm->save_queries ) {
3463                 CachedQuery     *qc;
3464                 BerVarray       vals = NULL;
3465
3466                 void            *thrctx;
3467                 Connection      conn = { 0 };
3468                 OperationBuffer opbuf;
3469                 Operation       *op;
3470                 slap_callback   cb = { 0 };
3471
3472                 SlapReply       rs = { REP_RESULT };
3473                 Modifications   mod = {{ 0 }};
3474
3475                 thrctx = ldap_pvt_thread_pool_context();
3476
3477                 connection_fake_init( &conn, &opbuf, thrctx );
3478                 op = &opbuf.ob_op;
3479
3480                 if ( qm->templates != NULL ) {
3481                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3482                                 for ( qc = tm->query; qc; qc = qc->next ) {
3483                                         struct berval   bv;
3484
3485                                         if ( query2url( op, qc, &bv ) == 0 ) {
3486                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3487                                         }
3488                                 }
3489                         }
3490                 }
3491
3492                 op->o_bd = &cm->db;
3493                 op->o_dn = cm->db.be_rootdn;
3494                 op->o_ndn = cm->db.be_rootndn;
3495
3496                 op->o_tag = LDAP_REQ_MODIFY;
3497                 op->o_protocol = LDAP_VERSION3;
3498                 cb.sc_response = slap_null_cb;
3499                 op->o_callback = &cb;
3500                 op->o_time = slap_get_time();
3501                 op->o_do_not_cache = 1;
3502                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3503
3504                 op->o_req_dn = op->o_bd->be_suffix[0];
3505                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3506
3507                 mod.sml_op = LDAP_MOD_REPLACE;
3508                 mod.sml_flags = 0;
3509                 mod.sml_desc = ad_cachedQueryURL;
3510                 mod.sml_type = ad_cachedQueryURL->ad_cname;
3511                 mod.sml_values = vals;
3512                 mod.sml_nvalues = NULL;
3513                 mod.sml_numvals = 1;
3514                 mod.sml_next = NULL;
3515                 Debug( pcache_debug,
3516                         "%sSETTING CACHED QUERY URLS\n",
3517                         vals == NULL ? "RE" : "", 0, 0 );
3518
3519                 op->orm_modlist = &mod;
3520
3521                 op->o_bd->be_modify( op, &rs );
3522
3523                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3524         }
3525
3526         /* cleanup stuff inherited from the original database... */
3527         cm->db.be_limits = NULL;
3528         cm->db.be_acl = NULL;
3529
3530         /* stop the thread ... */
3531         if ( cm->cc_arg ) {
3532                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3533                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3534                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3535                 }
3536                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3537                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3538         }
3539
3540         if ( cm->db.bd_info->bi_db_close ) {
3541                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3542         }
3543         while ( (tm = qm->templates) != NULL ) {
3544                 CachedQuery *qc, *qn;
3545                 qm->templates = tm->qmnext;
3546                 for ( qc = tm->query; qc; qc = qn ) {
3547                         qn = qc->next;
3548                         free_query( qc );
3549                 }
3550                 avl_free( tm->qbase, pcache_free_qbase );
3551                 free( tm->querystr.bv_val );
3552                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3553                 free( tm->t_attrs.attrs );
3554                 free( tm );
3555         }
3556
3557         for ( i=0; i<cm->numattrsets; i++ ) {
3558                 free( qm->attr_sets[i].attrs );
3559         }
3560         free( qm->attr_sets );
3561         qm->attr_sets = NULL;
3562
3563         return rc;
3564 }
3565
3566 static int
3567 pcache_db_destroy(
3568         BackendDB *be,
3569         ConfigReply *cr
3570 )
3571 {
3572         slap_overinst *on = (slap_overinst *)be->bd_info;
3573         cache_manager *cm = on->on_bi.bi_private;
3574         query_manager *qm = cm->qm;
3575
3576         if ( cm->db.be_private != NULL ) {
3577                 backend_stopdown_one( &cm->db );
3578         }
3579
3580         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3581         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3582         free( qm );
3583         free( cm );
3584
3585         return 0;
3586 }
3587
3588 #ifdef PCACHE_CONTROL_PRIVDB
3589 /*
3590         Control ::= SEQUENCE {
3591              controlType             LDAPOID,
3592              criticality             BOOLEAN DEFAULT FALSE,
3593              controlValue            OCTET STRING OPTIONAL }
3594
3595         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3596
3597  * criticality must be TRUE; controlValue must be absent.
3598  */
3599 static int
3600 parse_privdb_ctrl(
3601         Operation       *op,
3602         SlapReply       *rs,
3603         LDAPControl     *ctrl )
3604 {
3605         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3606                 rs->sr_text = "privateDB control specified multiple times";
3607                 return LDAP_PROTOCOL_ERROR;
3608         }
3609
3610         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3611                 rs->sr_text = "privateDB control value not absent";
3612                 return LDAP_PROTOCOL_ERROR;
3613         }
3614
3615         if ( !ctrl->ldctl_iscritical ) {
3616                 rs->sr_text = "privateDB control criticality required";
3617                 return LDAP_PROTOCOL_ERROR;
3618         }
3619
3620         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3621
3622         return LDAP_SUCCESS;
3623 }
3624
3625 static char *extops[] = {
3626         LDAP_EXOP_MODIFY_PASSWD,
3627         NULL
3628 };
3629 #endif /* PCACHE_CONTROL_PRIVDB */
3630
3631 #ifdef PCACHE_EXOP_QUERY_DELETE
3632 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3633
3634 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3635 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3636 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3637
3638 /*
3639         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3640              requestName      [0] LDAPOID,
3641              requestValue     [1] OCTET STRING OPTIONAL }
3642
3643         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3644
3645         requestValue ::= SEQUENCE { CHOICE {
3646                   baseDN           [0] LDAPDN
3647                   entryDN          [1] LDAPDN },
3648              queryID          [2] OCTET STRING (SIZE(16))
3649                   -- constrained to UUID }
3650
3651  * Either baseDN or entryDN must be present, to allow database selection.
3652  *
3653  * 1. if baseDN and queryID are present, then the query corresponding
3654  *    to queryID is deleted;
3655  * 2. if baseDN is present and queryID is absent, then all queries
3656  *    are deleted;
3657  * 3. if entryDN is present and queryID is absent, then all queries
3658  *    corresponding to the queryID values present in entryDN are deleted;
3659  * 4. if entryDN and queryID are present, then all queries
3660  *    corresponding to the queryID values present in entryDN are deleted,
3661  *    but only if the value of queryID is contained in the entry;
3662  *
3663  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
3664  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3665  * or by removing the database files.
3666
3667         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3668              COMPONENTS OF LDAPResult,
3669              responseName     [10] LDAPOID OPTIONAL,
3670              responseValue    [11] OCTET STRING OPTIONAL }
3671
3672  * responseName and responseValue must be absent.
3673  */
3674
3675 /*
3676  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3677  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3678  * - if ndn != NULL, it is set to the normalized DN in the request
3679  *   corresponding to either the baseDN or the entryDN, according
3680  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
3681  *   be freed by the caller.
3682  * - if uuid != NULL, it is set to point to the normalized UUID;
3683  *   memory is malloc'ed on the Operation's slab, and must
3684  *   be freed by the caller.
3685  */
3686 static int
3687 pcache_parse_query_delete(
3688         struct berval   *in,
3689         ber_tag_t       *tagp,
3690         struct berval   *ndn,
3691         struct berval   *uuid,
3692         const char      **text,
3693         void            *ctx )
3694 {
3695         int                     rc = LDAP_SUCCESS;
3696         ber_tag_t               tag;
3697         ber_len_t               len = -1;
3698         BerElementBuffer        berbuf;
3699         BerElement              *ber = (BerElement *)&berbuf;
3700         struct berval           reqdata = BER_BVNULL;
3701
3702         *text = NULL;
3703
3704         if ( ndn ) {
3705                 BER_BVZERO( ndn );
3706         }
3707
3708         if ( uuid ) {
3709                 BER_BVZERO( uuid );
3710         }
3711
3712         if ( in == NULL || in->bv_len == 0 ) {
3713                 *text = "empty request data field in queryDelete exop";
3714                 return LDAP_PROTOCOL_ERROR;
3715         }
3716
3717         ber_dupbv_x( &reqdata, in, ctx );
3718
3719         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3720         ber_init2( ber, &reqdata, 0 );
3721
3722         tag = ber_scanf( ber, "{" /*}*/ );
3723
3724         if ( tag == LBER_ERROR ) {
3725                 Debug( LDAP_DEBUG_TRACE,
3726                         "pcache_parse_query_delete: decoding error.\n",
3727                         0, 0, 0 );
3728                 goto decoding_error;
3729         }
3730
3731         tag = ber_peek_tag( ber, &len );
3732         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3733                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3734         {
3735                 *tagp = tag;
3736
3737                 if ( ndn != NULL ) {
3738                         struct berval   dn;
3739
3740                         tag = ber_scanf( ber, "m", &dn );
3741                         if ( tag == LBER_ERROR ) {
3742                                 Debug( LDAP_DEBUG_TRACE,
3743                                         "pcache_parse_query_delete: DN parse failed.\n",
3744                                         0, 0, 0 );
3745                                 goto decoding_error;
3746                         }
3747
3748                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3749                         if ( rc != LDAP_SUCCESS ) {
3750                                 *text = "invalid DN in queryDelete exop request data";
3751                                 goto done;
3752                         }
3753
3754                 } else {
3755                         tag = ber_scanf( ber, "x" /* "m" */ );
3756                         if ( tag == LBER_DEFAULT ) {
3757                                 goto decoding_error;
3758                         }
3759                 }
3760
3761                 tag = ber_peek_tag( ber, &len );
3762         }
3763
3764         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3765                 if ( uuid != NULL ) {
3766                         struct berval   bv;
3767                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3768
3769                         tag = ber_scanf( ber, "m", &bv );
3770                         if ( tag == LBER_ERROR ) {
3771                                 Debug( LDAP_DEBUG_TRACE,
3772                                         "pcache_parse_query_delete: UUID parse failed.\n",
3773                                         0, 0, 0 );
3774                                 goto decoding_error;
3775                         }
3776
3777                         if ( bv.bv_len != 16 ) {
3778                                 Debug( LDAP_DEBUG_TRACE,
3779                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3780                                         (unsigned long)bv.bv_len, 0, 0 );
3781                                 goto decoding_error;
3782                         }
3783
3784                         rc = lutil_uuidstr_from_normalized(
3785                                 bv.bv_val, bv.bv_len,
3786                                 uuidbuf, sizeof( uuidbuf ) );
3787                         if ( rc == -1 ) {
3788                                 goto decoding_error;
3789                         }
3790                         ber_str2bv( uuidbuf, rc, 1, uuid );
3791                         rc = LDAP_SUCCESS;
3792
3793                 } else {
3794                         tag = ber_skip_tag( ber, &len );
3795                         if ( tag == LBER_DEFAULT ) {
3796                                 goto decoding_error;
3797                         }
3798
3799                         if ( len != 16 ) {
3800                                 Debug( LDAP_DEBUG_TRACE,
3801                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3802                                         (unsigned long)len, 0, 0 );
3803                                 goto decoding_error;
3804                         }
3805                 }
3806
3807                 tag = ber_peek_tag( ber, &len );
3808         }
3809
3810         if ( tag != LBER_DEFAULT || len != 0 ) {
3811 decoding_error:;
3812                 Debug( LDAP_DEBUG_TRACE,
3813                         "pcache_parse_query_delete: decoding error\n",
3814                         0, 0, 0 );
3815                 rc = LDAP_PROTOCOL_ERROR;
3816                 *text = "queryDelete data decoding error";
3817
3818 done:;
3819                 if ( ndn && !BER_BVISNULL( ndn ) ) {
3820                         slap_sl_free( ndn->bv_val, ctx );
3821                         BER_BVZERO( ndn );
3822                 }
3823
3824                 if ( uuid && !BER_BVISNULL( uuid ) ) {
3825                         slap_sl_free( uuid->bv_val, ctx );
3826                         BER_BVZERO( uuid );
3827                 }
3828         }
3829
3830         if ( !BER_BVISNULL( &reqdata ) ) {
3831                 ber_memfree_x( reqdata.bv_val, ctx );
3832         }
3833
3834         return rc;
3835 }
3836
3837 static int
3838 pcache_exop_query_delete(
3839         Operation       *op,
3840         SlapReply       *rs )
3841 {
3842         BackendDB       *bd = op->o_bd;
3843
3844         struct berval   uuid = BER_BVNULL,
3845                         *uuidp = NULL;
3846         char            buf[ SLAP_TEXT_BUFLEN ];
3847         unsigned        len;
3848         ber_tag_t       tag = LBER_DEFAULT;
3849
3850         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3851                 uuidp = &uuid;
3852         }
3853
3854         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3855                 &tag, &op->o_req_ndn, uuidp,
3856                 &rs->sr_text, op->o_tmpmemctx );
3857         if ( rs->sr_err != LDAP_SUCCESS ) {
3858                 return rs->sr_err;
3859         }
3860
3861         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3862                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3863                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3864
3865                 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
3866                         snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3867                 }
3868
3869                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3870                         op->o_log_prefix, buf, 0 );
3871         }
3872         op->o_req_dn = op->o_req_ndn;
3873
3874         op->o_bd = select_backend( &op->o_req_ndn, 0 );
3875         rs->sr_err = backend_check_restrictions( op, rs,
3876                 (struct berval *)&pcache_exop_QUERY_DELETE );
3877         if ( rs->sr_err != LDAP_SUCCESS ) {
3878                 goto done;
3879         }
3880
3881         if ( op->o_bd->be_extended == NULL ) {
3882                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3883                         "backend does not support extended operations" );
3884                 goto done;
3885         }
3886
3887         op->o_bd->be_extended( op, rs );
3888
3889 done:;
3890         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3891                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3892                 BER_BVZERO( &op->o_req_ndn );
3893                 BER_BVZERO( &op->o_req_dn );
3894         }
3895
3896         if ( !BER_BVISNULL( &uuid ) ) {
3897                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3898         }
3899
3900         op->o_bd = bd;
3901
3902         return rs->sr_err;
3903 }
3904
3905 static int
3906 pcache_op_extended( Operation *op, SlapReply *rs )
3907 {
3908         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
3909         cache_manager   *cm = on->on_bi.bi_private;
3910
3911 #ifdef PCACHE_CONTROL_PRIVDB
3912         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3913                 return pcache_op_privdb( op, rs );
3914         }
3915 #endif /* PCACHE_CONTROL_PRIVDB */
3916
3917         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3918                 struct berval   uuid = BER_BVNULL;
3919                 ber_tag_t       tag = LBER_DEFAULT;
3920
3921                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3922                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3923                 assert( rs->sr_err == LDAP_SUCCESS );
3924
3925                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3926                         /* remove all queries related to the selected entry */
3927                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3928                                 cm, &op->o_req_ndn, &uuid );
3929
3930                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3931                         if ( !BER_BVISNULL( &uuid ) ) {
3932                                 /* remove the selected query */
3933                                 rs->sr_err = pcache_remove_query_from_cache( op,
3934                                         cm, &uuid );
3935
3936                         } else {
3937                                 /* TODO: remove all queries */
3938                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3939                                 rs->sr_text = "deletion of all queries not implemented";
3940                         }
3941                 }
3942
3943                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3944         }
3945
3946         return rs->sr_err;
3947 }
3948 #endif /* PCACHE_EXOP_QUERY_DELETE */
3949
3950 static slap_overinst pcache;
3951
3952 static char *obsolete_names[] = {
3953         "proxycache",
3954         NULL
3955 };
3956
3957 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3958 static
3959 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3960 int
3961 pcache_initialize()
3962 {
3963         int i, code;
3964         struct berval debugbv = BER_BVC("pcache");
3965
3966         code = slap_loglevel_get( &debugbv, &pcache_debug );
3967         if ( code ) {
3968                 return code;
3969         }
3970
3971 #ifdef PCACHE_CONTROL_PRIVDB
3972         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3973                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3974                 parse_privdb_ctrl, &privDB_cid );
3975         if ( code != LDAP_SUCCESS ) {
3976                 Debug( LDAP_DEBUG_ANY,
3977                         "pcache_initialize: failed to register control %s (%d)\n",
3978                         PCACHE_CONTROL_PRIVDB, code, 0 );
3979                 return code;
3980         }
3981 #endif /* PCACHE_CONTROL_PRIVDB */
3982
3983 #ifdef PCACHE_EXOP_QUERY_DELETE
3984         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3985                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3986                 0 );
3987         if ( code != LDAP_SUCCESS ) {
3988                 Debug( LDAP_DEBUG_ANY,
3989                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
3990                         code, 0, 0 );
3991                 return code;
3992         }
3993 #endif /* PCACHE_EXOP_QUERY_DELETE */
3994
3995         for ( i = 0; as[i].desc != NULL; i++ ) {
3996                 code = register_at( as[i].desc, as[i].adp, 0 );
3997                 if ( code ) {
3998                         Debug( LDAP_DEBUG_ANY,
3999                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
4000                         return code;
4001                 }
4002                 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
4003         }
4004
4005         pcache.on_bi.bi_type = "pcache";
4006         pcache.on_bi.bi_obsolete_names = obsolete_names;
4007         pcache.on_bi.bi_db_init = pcache_db_init;
4008         pcache.on_bi.bi_db_config = pcache_db_config;
4009         pcache.on_bi.bi_db_open = pcache_db_open;
4010         pcache.on_bi.bi_db_close = pcache_db_close;
4011         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
4012
4013         pcache.on_bi.bi_op_search = pcache_op_search;
4014 #ifdef PCACHE_CONTROL_PRIVDB
4015         pcache.on_bi.bi_op_bind = pcache_op_privdb;
4016         pcache.on_bi.bi_op_compare = pcache_op_privdb;
4017         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
4018         pcache.on_bi.bi_op_modify = pcache_op_privdb;
4019         pcache.on_bi.bi_op_add = pcache_op_privdb;
4020         pcache.on_bi.bi_op_delete = pcache_op_privdb;
4021 #endif /* PCACHE_CONTROL_PRIVDB */
4022 #ifdef PCACHE_EXOP_QUERY_DELETE
4023         pcache.on_bi.bi_extended = pcache_op_extended;
4024 #elif defined( PCACHE_CONTROL_PRIVDB )
4025         pcache.on_bi.bi_extended = pcache_op_privdb;
4026 #endif
4027
4028         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
4029
4030         pcache.on_bi.bi_cf_ocs = pcocs;
4031
4032         code = config_register_schema( pccfg, pcocs );
4033         if ( code ) return code;
4034
4035         return overlay_register( &pcache );
4036 }
4037
4038 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4039 int init_module(int argc, char *argv[]) {
4040         return pcache_initialize();
4041 }
4042 #endif
4043
4044 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */