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