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