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