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