]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
Fix prev commit
[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                         /* check for malformed entries: attrs with no values */
1997                         {
1998                                 Attribute *a = rs->sr_entry->e_attrs;
1999                                 for (; a; a=a->a_next) {
2000                                         if ( !a->a_numvals ) {
2001                                                 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2002                                                 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2003                                                 a->a_desc->ad_cname.bv_val );
2004                                                 goto over;
2005                                         }
2006                                 }
2007                         }
2008
2009                         if ( si->count < si->max ) {
2010                                 si->count++;
2011                                 e = entry_dup( rs->sr_entry );
2012                                 if ( !si->head ) si->head = e;
2013                                 if ( si->tail ) si->tail->e_private = e;
2014                                 si->tail = e;
2015
2016                         } else {
2017 over:;
2018                                 si->over = 1;
2019                                 si->count = 0;
2020                                 for (;si->head; si->head=e) {
2021                                         e = si->head->e_private;
2022                                         si->head->e_private = NULL;
2023                                         entry_free(si->head);
2024                                 }
2025                                 si->tail = NULL;
2026                         }
2027                 }
2028
2029         }
2030
2031         if ( rs->sr_type == REP_RESULT || 
2032                 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2033         {
2034                 if ( si->swap_saved_attrs ) {
2035                         rs->sr_attrs = si->save_attrs;
2036                         op->ors_attrs = si->save_attrs;
2037                 }
2038                 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) && 
2039                                 si->caching_reason == PC_IGNORE ) {
2040                         filter_free( si->query.filter );
2041                         if ( si->count ) {
2042                                 /* duplicate query, free it */
2043                                 Entry *e;
2044                                 for (;si->head; si->head=e) {
2045                                         e = si->head->e_private;
2046                                         si->head->e_private = NULL;
2047                                         entry_free(si->head);
2048                                 }
2049                         }
2050                         op->o_callback = op->o_callback->sc_next;
2051                         op->o_tmpfree( cb, op->o_tmpmemctx );
2052                 } else if ( si->caching_reason != PC_IGNORE ) {
2053                         CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2054                                 si->qtemp, si->caching_reason, 1 );
2055
2056                         if ( qc != NULL ) {
2057                                 switch ( si->caching_reason ) {
2058                                 case PC_POSITIVE:
2059                                         cache_entries( op, rs, &qc->q_uuid );
2060                                         break;
2061
2062                                 case PC_SIZELIMIT:
2063                                         qc->q_sizelimit = rs->sr_nentries;
2064                                         break;
2065
2066                                 case PC_NEGATIVE:
2067                                         break;
2068
2069                                 default:
2070                                         assert( 0 );
2071                                         break;
2072                                 }
2073                                 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2074                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2075                                 cm->num_cached_queries++;
2076                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2077                                                 cm->num_cached_queries, 0, 0 );
2078                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2079
2080                                 /* If the consistency checker suspended itself,
2081                                  * wake it back up
2082                                  */
2083                                 if ( cm->cc_paused ) {
2084                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2085                                         if ( cm->cc_paused ) {
2086                                                 cm->cc_paused = 0;
2087                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2088                                         }
2089                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2090                                 }
2091
2092                         } else if ( si->count ) {
2093                                 /* duplicate query, free it */
2094                                 Entry *e;
2095                                 for (;si->head; si->head=e) {
2096                                         e = si->head->e_private;
2097                                         si->head->e_private = NULL;
2098                                         entry_free(si->head);
2099                                 }
2100                         }
2101
2102                 } else {
2103                         filter_free( si->query.filter );
2104                 }
2105         }
2106
2107         return SLAP_CB_CONTINUE;
2108 }
2109
2110 static int
2111 pcache_response(
2112         Operation       *op,
2113         SlapReply       *rs )
2114 {
2115         struct search_info *si = op->o_callback->sc_private;
2116
2117         if ( si->swap_saved_attrs ) {
2118                 rs->sr_attrs = si->save_attrs;
2119                 op->ors_attrs = si->save_attrs;
2120         }
2121
2122         if ( rs->sr_type == REP_SEARCH ) {
2123                 /* don't return more entries than requested by the client */
2124                 if ( si->slimit_exceeded ) {
2125                         return 0;
2126                 }
2127
2128         } else if ( rs->sr_type == REP_RESULT ) {
2129
2130                 if ( si->count ) {
2131                         if ( rs->sr_err == LDAP_SUCCESS ) {
2132                                 si->caching_reason = PC_POSITIVE;
2133
2134                         } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2135                                 && si->qtemp->limitttl )
2136                         {
2137                                 si->caching_reason = PC_SIZELIMIT;
2138                         }
2139
2140                 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2141                                 rs->sr_err == LDAP_SUCCESS )
2142                 {
2143                         si->caching_reason = PC_NEGATIVE;
2144                 }
2145
2146
2147                 if ( si->slimit_exceeded ) {
2148                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2149                 }
2150         }
2151
2152         return SLAP_CB_CONTINUE;
2153 }
2154
2155 static int
2156 add_filter_attrs(
2157         Operation *op,
2158         AttributeName** new_attrs,
2159         struct attr_set *attrs,
2160         AttributeName* filter_attrs,
2161         int fattr_cnt,
2162         int fattr_got_oc)
2163 {
2164         int alluser = 0;
2165         int allop = 0;
2166         int i, j;
2167         int count;
2168         int addoc = 0;
2169
2170         /* duplicate attrs */
2171         count = attrs->count + fattr_cnt;
2172         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2173                 addoc = 1;
2174                 count++;
2175         }
2176
2177         *new_attrs = (AttributeName*)ch_calloc( count + 1,
2178                 sizeof(AttributeName) );
2179         for (i=0; i<attrs->count; i++) {
2180                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2181                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2182         }
2183         BER_BVZERO( &(*new_attrs)[i].an_name );
2184         alluser = an_find( *new_attrs, slap_bv_all_user_attrs );
2185         allop = an_find( *new_attrs, slap_bv_all_operational_attrs );
2186
2187         j = i;
2188         for ( i=0; i<fattr_cnt; i++ ) {
2189                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2190                         continue;
2191                 }
2192                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2193                         if ( allop ) {
2194                                 continue;
2195                         }
2196                 } else if ( alluser ) {
2197                         continue;
2198                 }
2199                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2200                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2201                 (*new_attrs)[j].an_oc = NULL;
2202                 (*new_attrs)[j].an_oc_exclude = 0;
2203                 j++;
2204         }
2205         if ( addoc ) {
2206                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2207                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2208                 (*new_attrs)[j].an_oc = NULL;
2209                 (*new_attrs)[j].an_oc_exclude = 0;
2210                 j++;
2211         }
2212         BER_BVZERO( &(*new_attrs)[j].an_name );
2213
2214         return j;
2215 }
2216
2217 /* NOTE: this is a quick workaround to let pcache minimally interact
2218  * with pagedResults.  A more articulated solutions would be to
2219  * perform the remote query without control and cache all results,
2220  * performing the pagedResults search only within the client
2221  * and the proxy.  This requires pcache to understand pagedResults. */
2222 static int
2223 pcache_chk_controls(
2224         Operation       *op,
2225         SlapReply       *rs )
2226 {
2227         const char      *non = "";
2228         const char      *stripped = "";
2229
2230         switch( op->o_pagedresults ) {
2231         case SLAP_CONTROL_NONCRITICAL:
2232                 non = "non-";
2233                 stripped = "; stripped";
2234                 /* fallthru */
2235
2236         case SLAP_CONTROL_CRITICAL:
2237                 Debug( pcache_debug, "%s: "
2238                         "%scritical pagedResults control "
2239                         "disabled with proxy cache%s.\n",
2240                         op->o_log_prefix, non, stripped );
2241                 
2242                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2243                 break;
2244
2245         default:
2246                 rs->sr_err = SLAP_CB_CONTINUE;
2247                 break;
2248         }
2249
2250         return rs->sr_err;
2251 }
2252
2253 #ifdef PCACHE_CONTROL_PRIVDB
2254 static int
2255 pcache_op_privdb(
2256         Operation               *op,
2257         SlapReply               *rs )
2258 {
2259         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
2260         cache_manager   *cm = on->on_bi.bi_private;
2261         slap_callback   *save_cb;
2262         slap_op_t       type;
2263
2264         /* skip if control is unset */
2265         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2266                 return SLAP_CB_CONTINUE;
2267         }
2268
2269         /* The cache DB isn't open yet */
2270         if ( cm->defer_db_open ) {
2271                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2272                         "pcachePrivDB: cacheDB not available" );
2273                 return rs->sr_err;
2274         }
2275
2276         /* FIXME: might be a little bit exaggerated... */
2277         if ( !be_isroot( op ) ) {
2278                 save_cb = op->o_callback;
2279                 op->o_callback = NULL;
2280                 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2281                         "pcachePrivDB: operation not allowed" );
2282                 op->o_callback = save_cb;
2283
2284                 return rs->sr_err;
2285         }
2286
2287         /* map tag to operation */
2288         type = slap_req2op( op->o_tag );
2289         if ( type != SLAP_OP_LAST ) {
2290                 BI_op_func      **func;
2291                 int             rc;
2292
2293                 /* execute, if possible */
2294                 func = &cm->db.be_bind;
2295                 if ( func[ type ] != NULL ) {
2296                         Operation       op2 = *op;
2297         
2298                         op2.o_bd = &cm->db;
2299
2300                         rc = func[ type ]( &op2, rs );
2301                         if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2302                                 op->o_conn->c_authz_cookie = cm->db.be_private;
2303                         }
2304                 }
2305         }
2306
2307         /* otherwise fall back to error */
2308         save_cb = op->o_callback;
2309         op->o_callback = NULL;
2310         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2311                 "operation not supported with pcachePrivDB control" );
2312         op->o_callback = save_cb;
2313
2314         return rs->sr_err;
2315 }
2316 #endif /* PCACHE_CONTROL_PRIVDB */
2317
2318 static int
2319 pcache_op_search(
2320         Operation       *op,
2321         SlapReply       *rs )
2322 {
2323         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2324         cache_manager *cm = on->on_bi.bi_private;
2325         query_manager*          qm = cm->qm;
2326
2327         int i = -1;
2328
2329         AttributeName   *filter_attrs = NULL;
2330
2331         Query           query;
2332         QueryTemplate   *qtemp = NULL;
2333
2334         int             attr_set = -1;
2335         CachedQuery     *answerable = NULL;
2336         int             cacheable = 0;
2337         int             fattr_cnt=0;
2338         int             fattr_got_oc = 0;
2339
2340         struct berval   tempstr;
2341
2342 #ifdef PCACHE_CONTROL_PRIVDB
2343         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2344                 return pcache_op_privdb( op, rs );
2345         }
2346 #endif /* PCACHE_CONTROL_PRIVDB */
2347
2348         /* The cache DB isn't open yet */
2349         if ( cm->defer_db_open ) {
2350                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2351                         "pcachePrivDB: cacheDB not available" );
2352                 return rs->sr_err;
2353         }
2354
2355         /* pickup runtime ACL changes */
2356         cm->db.be_acl = op->o_bd->be_acl;
2357
2358         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2359         tempstr.bv_len = 0;
2360         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2361                 &fattr_cnt, &fattr_got_oc )) {
2362                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2363                 return SLAP_CB_CONTINUE;
2364         }
2365
2366         Debug( pcache_debug, "query template of incoming query = %s\n",
2367                                         tempstr.bv_val, 0, 0 );
2368
2369         /* FIXME: cannot cache/answer requests with pagedResults control */
2370
2371         /* find attr set */
2372         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2373
2374         query.filter = op->ors_filter;
2375         query.base = op->o_req_ndn;
2376         query.scope = op->ors_scope;
2377
2378         /* check for query containment */
2379         if (attr_set > -1) {
2380                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2381                 for (; qt; qt = qt->qtnext ) {
2382                         /* find if template i can potentially answer tempstr */
2383                         if (qt->querystr.bv_len != tempstr.bv_len ||
2384                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2385                                 continue;
2386                         cacheable = 1;
2387                         qtemp = qt;
2388                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
2389                                         op->ors_filterstr.bv_val, 0, 0 );
2390                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2391
2392                         if (answerable)
2393                                 break;
2394                 }
2395         }
2396         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2397
2398         if (answerable) {
2399                 /* Need to clear the callbacks of the original operation,
2400                  * in case there are other overlays */
2401                 BackendDB       *save_bd = op->o_bd;
2402                 slap_callback   *save_cb = op->o_callback;
2403
2404                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2405                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2406                 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
2407                 if ( BER_BVISNULL( &answerable->q_uuid )) {
2408                         /* No entries cached, just an empty result set */
2409                         i = rs->sr_err = 0;
2410                         send_ldap_result( op, rs );
2411                 } else {
2412                         op->o_bd = &cm->db;
2413                         op->o_callback = NULL;
2414                         i = cm->db.bd_info->bi_op_search( op, rs );
2415                 }
2416                 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
2417                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2418                 op->o_bd = save_bd;
2419                 op->o_callback = save_cb;
2420                 return i;
2421         }
2422
2423         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2424
2425         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2426         if (cm->num_cached_queries >= cm->max_queries) {
2427                 cacheable = 0;
2428         }
2429         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2430
2431         if (op->ors_attrsonly)
2432                 cacheable = 0;
2433
2434         if (cacheable) {
2435                 slap_callback           *cb;
2436                 struct search_info      *si;
2437
2438                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2439                 query.filter = filter_dup(op->ors_filter, NULL);
2440                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2441                 if ( !qtemp->t_attrs.count ) {
2442                         qtemp->t_attrs.count = add_filter_attrs(op,
2443                                 &qtemp->t_attrs.attrs,
2444                                 &qm->attr_sets[attr_set],
2445                                 filter_attrs, fattr_cnt, fattr_got_oc);
2446                 }
2447                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2448
2449                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2450                 cb->sc_response = pcache_response;
2451                 cb->sc_cleanup = pcache_op_cleanup;
2452                 cb->sc_private = (cb+1);
2453                 si = cb->sc_private;
2454                 si->on = on;
2455                 si->query = query;
2456                 si->qtemp = qtemp;
2457                 si->max = cm->num_entries_limit ;
2458                 si->over = 0;
2459                 si->count = 0;
2460                 si->slimit = 0;
2461                 si->slimit_exceeded = 0;
2462                 si->caching_reason = PC_IGNORE;
2463                 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2464                         si->slimit = op->ors_slimit;
2465                         op->ors_slimit = cm->num_entries_limit;
2466                 }
2467                 si->head = NULL;
2468                 si->tail = NULL;
2469                 si->swap_saved_attrs = 1;
2470                 si->save_attrs = op->ors_attrs;
2471
2472                 op->ors_attrs = qtemp->t_attrs.attrs;
2473
2474                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2475                         cb->sc_next = op->o_callback;
2476                         op->o_callback = cb;
2477
2478                 } else {
2479                         slap_callback           **pcb;
2480
2481                         /* need to move the callback at the end, in case other
2482                          * overlays are present, so that the final entry is
2483                          * actually cached */
2484                         cb->sc_next = NULL;
2485                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2486                         *pcb = cb;
2487                 }
2488
2489         } else {
2490                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2491                                         0, 0, 0);
2492         }
2493
2494         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2495
2496         return SLAP_CB_CONTINUE;
2497 }
2498
2499 static int
2500 get_attr_set(
2501         AttributeName* attrs,
2502         query_manager* qm,
2503         int num )
2504 {
2505         int i;
2506         int count = 0;
2507
2508         if ( attrs ) {
2509                 for ( ; attrs[count].an_name.bv_val; count++ );
2510         }
2511
2512         /* recognize a single "*" or a "1.1" */
2513         if ( count == 0 ) {
2514                 count = 1;
2515                 attrs = slap_anlist_all_user_attributes;
2516
2517         } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2518                 count = 0;
2519                 attrs = NULL;
2520         }
2521
2522         for ( i = 0; i < num; i++ ) {
2523                 AttributeName *a2;
2524                 int found = 1;
2525
2526                 if ( count > qm->attr_sets[i].count ) {
2527                         continue;
2528                 }
2529
2530                 if ( !count ) {
2531                         if ( !qm->attr_sets[i].count ) {
2532                                 break;
2533                         }
2534                         continue;
2535                 }
2536
2537                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2538                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2539                                 found = 0;
2540                                 break;
2541                         }
2542                 }
2543
2544                 if ( found ) {
2545                         break;
2546                 }
2547         }
2548
2549         if ( i == num ) {
2550                 i = -1;
2551         }
2552
2553         return i;
2554 }
2555
2556 static void*
2557 consistency_check(
2558         void *ctx,
2559         void *arg )
2560 {
2561         struct re_s *rtask = arg;
2562         slap_overinst *on = rtask->arg;
2563         cache_manager *cm = on->on_bi.bi_private;
2564         query_manager *qm = cm->qm;
2565         Connection conn = {0};
2566         OperationBuffer opbuf;
2567         Operation *op;
2568
2569         SlapReply rs = {REP_RESULT};
2570         CachedQuery* query;
2571         int return_val, pause = 1;
2572         QueryTemplate* templ;
2573
2574         connection_fake_init( &conn, &opbuf, ctx );
2575         op = &opbuf.ob_op;
2576
2577         op->o_bd = &cm->db;
2578         op->o_dn = cm->db.be_rootdn;
2579         op->o_ndn = cm->db.be_rootndn;
2580
2581         cm->cc_arg = arg;
2582
2583         for (templ = qm->templates; templ; templ=templ->qmnext) {
2584                 query = templ->query_last;
2585                 if ( query ) pause = 0;
2586                 op->o_time = slap_get_time();
2587                 while (query && (query->expiry_time < op->o_time)) {
2588                         int rem = 0;
2589                         Debug( pcache_debug, "Lock CR index = %p\n",
2590                                         (void *) templ, 0, 0 );
2591                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2592                         if ( query == templ->query_last ) {
2593                                 rem = 1;
2594                                 remove_from_template(query, templ);
2595                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2596                                                 (void *) templ, templ->no_of_queries, 0 );
2597                                 Debug( pcache_debug, "Unlock CR index = %p\n",
2598                                                 (void *) templ, 0, 0 );
2599                         }
2600                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2601                         if ( !rem ) {
2602                                 query = templ->query_last;
2603                                 continue;
2604                         }
2605                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2606                         remove_query(qm, query);
2607                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2608                         if ( BER_BVISNULL( &query->q_uuid ))
2609                                 return_val = 0;
2610                         else
2611                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
2612                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2613                                                 return_val, 0, 0 );
2614                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2615                         cm->cur_entries -= return_val;
2616                         cm->num_cached_queries--;
2617                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
2618                                         cm->num_cached_queries, 0, 0 );
2619                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2620                         Debug( pcache_debug,
2621                                 "STALE QUERY REMOVED, CACHE ="
2622                                 "%d entries\n",
2623                                 cm->cur_entries, 0, 0 );
2624                         free_query(query);
2625                         query = templ->query_last;
2626                 }
2627         }
2628         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2629         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2630                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2631         }
2632         /* If there were no queries, defer processing for a while */
2633         cm->cc_paused = pause;
2634         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2635
2636         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2637         return NULL;
2638 }
2639
2640
2641 #define MAX_ATTR_SETS 500
2642
2643 enum {
2644         PC_MAIN = 1,
2645         PC_ATTR,
2646         PC_TEMP,
2647         PC_RESP,
2648         PC_QUERIES
2649 };
2650
2651 static ConfigDriver pc_cf_gen;
2652 static ConfigLDAPadd pc_ldadd;
2653 static ConfigCfAdd pc_cfadd;
2654
2655 static ConfigTable pccfg[] = {
2656         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2657                                 "<cycle_time",
2658                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2659                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2660                         "DESC 'ProxyCache basic parameters' "
2661                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2662         { "proxyattrset", "index> <attributes...",
2663                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2664                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2665                         "DESC 'A set of attributes to cache' "
2666                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2667         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2668                 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2669                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2670                         "DESC 'Filter template, attrset, cache TTL, "
2671                                 "optional negative TTL, optional sizelimit TTL' "
2672                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2673         { "response-callback", "head|tail(default)",
2674                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2675                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2676                         "DESC 'Response callback position in overlay stack' "
2677                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2678         { "proxyCacheQueries", "queries",
2679                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2680                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2681                         "DESC 'Maximum number of queries to cache' "
2682                         "SYNTAX OMsInteger )", NULL, NULL },
2683         { "proxySaveQueries", "TRUE|FALSE",
2684                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2685                 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2686                         "DESC 'Save cached queries for hot restart' "
2687                         "SYNTAX OMsBoolean )", NULL, NULL },
2688         { "proxyCheckCacheability", "TRUE|FALSE",
2689                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
2690                 "( OLcfgOvAt:2.7 NAME 'olcProxyCheckCacheability' "
2691                         "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
2692                         "SYNTAX OMsBoolean )", NULL, NULL },
2693
2694         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2695 };
2696
2697 static ConfigOCs pcocs[] = {
2698         { "( OLcfgOvOc:2.1 "
2699                 "NAME 'olcPcacheConfig' "
2700                 "DESC 'ProxyCache configuration' "
2701                 "SUP olcOverlayConfig "
2702                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2703                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries $ olcProxyCheckCacheability ) )",
2704                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2705         { "( OLcfgOvOc:2.2 "
2706                 "NAME 'olcPcacheDatabase' "
2707                 "DESC 'Cache database configuration' "
2708                 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
2709         { NULL, 0, NULL }
2710 };
2711
2712 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
2713
2714 static int
2715 pc_ldadd_cleanup( ConfigArgs *c )
2716 {
2717         slap_overinst *on = c->ca_private;
2718         return pcache_db_open2( on, &c->reply );
2719 }
2720
2721 static int
2722 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2723 {
2724         slap_overinst *on;
2725         cache_manager *cm;
2726
2727         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2728                 p->ce_bi->bi_cf_ocs != pcocs )
2729                 return LDAP_CONSTRAINT_VIOLATION;
2730
2731         on = (slap_overinst *)p->ce_bi;
2732         cm = on->on_bi.bi_private;
2733         ca->be = &cm->db;
2734         /* Defer open if this is an LDAPadd */
2735         if ( CONFIG_ONLINE_ADD( ca ))
2736                 ca->cleanup = pc_ldadd_cleanup;
2737         else
2738                 cm->defer_db_open = 0;
2739         ca->ca_private = on;
2740         return LDAP_SUCCESS;
2741 }
2742
2743 static int
2744 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2745 {
2746         CfEntryInfo *pe = p->e_private;
2747         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2748         cache_manager *cm = on->on_bi.bi_private;
2749         struct berval bv;
2750
2751         /* FIXME: should not hardcode "olcDatabase" here */
2752         bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
2753                 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
2754                 0, cm->db.bd_info->bi_type );
2755         if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
2756                 return -1;
2757         }
2758         bv.bv_val = ca->cr_msg;
2759         ca->be = &cm->db;
2760         cm->defer_db_open = 0;
2761
2762         /* We can only create this entry if the database is table-driven
2763          */
2764         if ( cm->db.bd_info->bi_cf_ocs )
2765                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2766                         &pcocs[1] );
2767
2768         return 0;
2769 }
2770
2771 static int
2772 pc_cf_gen( ConfigArgs *c )
2773 {
2774         slap_overinst   *on = (slap_overinst *)c->bi;
2775         cache_manager*  cm = on->on_bi.bi_private;
2776         query_manager*  qm = cm->qm;
2777         QueryTemplate*  temp;
2778         AttributeName*  attr_name;
2779         AttributeName*  attrarray;
2780         const char*     text=NULL;
2781         int             i, num, rc = 0;
2782         char            *ptr;
2783         unsigned long   t;
2784
2785         if ( c->op == SLAP_CONFIG_EMIT ) {
2786                 struct berval bv;
2787                 switch( c->type ) {
2788                 case PC_MAIN:
2789                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2790                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2791                                 cm->num_entries_limit, cm->cc_period );
2792                         bv.bv_val = c->cr_msg;
2793                         value_add_one( &c->rvalue_vals, &bv );
2794                         break;
2795                 case PC_ATTR:
2796                         for (i=0; i<cm->numattrsets; i++) {
2797                                 if ( !qm->attr_sets[i].count ) continue;
2798
2799                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2800
2801                                 /* count the attr length */
2802                                 for ( attr_name = qm->attr_sets[i].attrs;
2803                                         attr_name->an_name.bv_val; attr_name++ )
2804                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2805
2806                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2807                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2808                                 for ( attr_name = qm->attr_sets[i].attrs;
2809                                         attr_name->an_name.bv_val; attr_name++ ) {
2810                                         *ptr++ = ' ';
2811                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2812                                 }
2813                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2814                         }
2815                         if ( !c->rvalue_vals )
2816                                 rc = 1;
2817                         break;
2818                 case PC_TEMP:
2819                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2820                                 /* HEADS-UP: always print all;
2821                                  * if optional == 0, ignore */
2822                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2823                                         " %d %ld %ld %ld",
2824                                         temp->attr_set_index,
2825                                         temp->ttl,
2826                                         temp->negttl,
2827                                         temp->limitttl );
2828                                 bv.bv_len += temp->querystr.bv_len + 2;
2829                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2830                                 ptr = bv.bv_val;
2831                                 *ptr++ = '"';
2832                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2833                                 *ptr++ = '"';
2834                                 strcpy( ptr, c->cr_msg );
2835                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2836                         }
2837                         if ( !c->rvalue_vals )
2838                                 rc = 1;
2839                         break;
2840                 case PC_RESP:
2841                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2842                                 BER_BVSTR( &bv, "head" );
2843                         } else {
2844                                 BER_BVSTR( &bv, "tail" );
2845                         }
2846                         value_add_one( &c->rvalue_vals, &bv );
2847                         break;
2848                 case PC_QUERIES:
2849                         c->value_int = cm->max_queries;
2850                         break;
2851                 }
2852                 return rc;
2853         } else if ( c->op == LDAP_MOD_DELETE ) {
2854                 return 1;       /* FIXME */
2855 #if 0
2856                 switch( c->type ) {
2857                 case PC_ATTR:
2858                 case PC_TEMP:
2859                 }
2860                 return rc;
2861 #endif
2862         }
2863
2864         switch( c->type ) {
2865         case PC_MAIN:
2866                 if ( cm->numattrsets > 0 ) {
2867                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2868                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2869                         return( 1 );
2870                 }
2871
2872                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2873                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2874                                 c->argv[3] );
2875                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2876                         return( 1 );
2877                 }
2878                 if ( cm->numattrsets <= 0 ) {
2879                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2880                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2881                         return( 1 );
2882                 }
2883                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2884                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2885                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2886                         return( 1 );
2887                 }
2888
2889                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2890                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2891                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2892                         return( 1 );
2893                 }
2894
2895                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2896                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2897                                 c->argv[2] );
2898                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2899                         return( 1 );
2900                 }
2901                 if ( cm->max_entries <= 0 ) {
2902                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2903                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2904                         return( 1 );
2905                 }
2906
2907                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2908                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2909                                 c->argv[4] );
2910                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2911                         return( 1 );
2912                 }
2913                 if ( cm->num_entries_limit <= 0 ) {
2914                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2915                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2916                         return( 1 );
2917                 }
2918                 if ( cm->num_entries_limit > cm->max_entries ) {
2919                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2920                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2921                         return( 1 );
2922                 }
2923
2924                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2925                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2926                                 c->argv[5] );
2927                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2928                         return( 1 );
2929                 }
2930
2931                 cm->cc_period = (time_t)t;
2932                 Debug( pcache_debug,
2933                                 "Total # of attribute sets to be cached = %d.\n",
2934                                 cm->numattrsets, 0, 0 );
2935                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2936                                                 sizeof( struct attr_set ) );
2937                 break;
2938         case PC_ATTR:
2939                 if ( cm->numattrsets == 0 ) {
2940                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2941                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2942                         return( 1 );
2943                 }
2944                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2945                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2946                                 c->argv[1] );
2947                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2948                         return( 1 );
2949                 }
2950
2951                 if ( num < 0 || num >= cm->numattrsets ) {
2952                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2953                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2954                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2955                         return 1;
2956                 }
2957                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2958                 if ( c->argc == 2 ) {
2959                         /* assume "1.1" */
2960                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2961                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2962                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2963                         return 1;
2964
2965                 } else if ( c->argc == 3 ) {
2966                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2967                                 qm->attr_sets[num].count = 1;
2968                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2969                                         sizeof( AttributeName ) );
2970                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2971                                 break;
2972
2973                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2974                                 qm->attr_sets[num].count = 1;
2975                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2976                                         sizeof( AttributeName ) );
2977                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2978                                 break;
2979
2980                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2981                                 break;
2982                         }
2983                         /* else: fallthru */
2984
2985                 } else if ( c->argc == 4 ) {
2986                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2987                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2988                         {
2989                                 qm->attr_sets[num].count = 2;
2990                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2991                                         sizeof( AttributeName ) );
2992                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2993                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2994                                 break;
2995                         }
2996                         /* else: fallthru */
2997                 }
2998
2999                 if ( c->argc > 2 ) {
3000                         int all_user = 0, all_op = 0;
3001
3002                         qm->attr_sets[num].count = c->argc - 2;
3003                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
3004                                 sizeof( AttributeName ) );
3005                         attr_name = qm->attr_sets[num].attrs;
3006                         for ( i = 2; i < c->argc; i++ ) {
3007                                 attr_name->an_desc = NULL;
3008                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
3009                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3010                                                 "invalid attr #%d \"%s\" in attrlist",
3011                                                 i - 2, c->argv[i] );
3012                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3013                                         ch_free( qm->attr_sets[num].attrs );
3014                                         qm->attr_sets[num].attrs = NULL;
3015                                         qm->attr_sets[num].count = 0;
3016                                         return 1;
3017                                 }
3018                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3019                                         all_user = 1;
3020                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
3021                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3022                                         all_op = 1;
3023                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3024                                 } else {
3025                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
3026                                                 strcpy( c->cr_msg, text );
3027                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3028                                                 ch_free( qm->attr_sets[num].attrs );
3029                                                 qm->attr_sets[num].attrs = NULL;
3030                                                 qm->attr_sets[num].count = 0;
3031                                                 return 1;
3032                                         }
3033                                         attr_name->an_name = attr_name->an_desc->ad_cname;
3034                                 }
3035                                 attr_name->an_oc = NULL;
3036                                 attr_name->an_oc_exclude = 0;
3037                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
3038                                         qm->attr_sets[num].flags |= PC_GOT_OC;
3039                                 attr_name++;
3040                                 BER_BVZERO( &attr_name->an_name );
3041                         }
3042
3043                         /* warn if list contains both "*" and "+" */
3044                         if ( i > 4 && all_user && all_op ) {
3045                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3046                                         "warning: attribute list contains \"*\" and \"+\"" );
3047                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3048                         }
3049                 }
3050                 break;
3051         case PC_TEMP:
3052                 if ( cm->numattrsets == 0 ) {
3053                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3054                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3055                         return( 1 );
3056                 }
3057                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
3058                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
3059                                 c->argv[2] );
3060                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3061                         return( 1 );
3062                 }
3063
3064                 if ( i < 0 || i >= cm->numattrsets || 
3065                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
3066                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
3067                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3068                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3069                         return 1;
3070                 }
3071                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
3072                 temp->qmnext = qm->templates;
3073                 qm->templates = temp;
3074                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
3075                 temp->query = temp->query_last = NULL;
3076                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
3077                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3078                                 "unable to parse template ttl=\"%s\"",
3079                                 c->argv[3] );
3080                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3081                         return( 1 );
3082                 }
3083                 temp->ttl = (time_t)t;
3084                 temp->negttl = (time_t)0;
3085                 temp->limitttl = (time_t)0;
3086                 switch ( c->argc ) {
3087                 case 6:
3088                         if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3089                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3090                                         "unable to parse template sizelimit ttl=\"%s\"",
3091                                         c->argv[5] );
3092                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3093                                         return( 1 );
3094                         }
3095                         temp->limitttl = (time_t)t;
3096                         /* fallthru */
3097
3098                 case 5:
3099                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
3100                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3101                                         "unable to parse template negative ttl=\"%s\"",
3102                                         c->argv[4] );
3103                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3104                                         return( 1 );
3105                         }
3106                         temp->negttl = (time_t)t;
3107                         break;
3108                 }
3109
3110                 temp->no_of_queries = 0;
3111
3112                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3113                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3114                 Debug( pcache_debug, "  query template: %s\n",
3115                                 temp->querystr.bv_val, 0, 0 );
3116                 temp->attr_set_index = i;
3117                 qm->attr_sets[i].flags |= PC_REFERENCED;
3118                 temp->qtnext = qm->attr_sets[i].templates;
3119                 qm->attr_sets[i].templates = temp;
3120                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
3121                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3122                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
3123                                 Debug( pcache_debug, "\t%s\n",
3124                                         attrarray[i].an_name.bv_val, 0, 0 );
3125                 }
3126                 break;
3127         case PC_RESP:
3128                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3129                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3130
3131                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3132                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3133
3134                 } else {
3135                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3136                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3137                         return 1;
3138                 }
3139                 break;
3140         case PC_QUERIES:
3141                 if ( c->value_int <= 0 ) {
3142                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3143                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3144                         return( 1 );
3145                 }
3146                 cm->max_queries = c->value_int;
3147                 break;
3148         }
3149         return rc;
3150 }
3151
3152 static int
3153 pcache_db_config(
3154         BackendDB       *be,
3155         const char      *fname,
3156         int             lineno,
3157         int             argc,
3158         char            **argv
3159 )
3160 {
3161         slap_overinst   *on = (slap_overinst *)be->bd_info;
3162         cache_manager*  cm = on->on_bi.bi_private;
3163
3164         /* Something for the cache database? */
3165         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3166                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3167                         argc, argv );
3168         return SLAP_CONF_UNKNOWN;
3169 }
3170
3171 static int
3172 pcache_db_init(
3173         BackendDB *be,
3174         ConfigReply *cr)
3175 {
3176         slap_overinst *on = (slap_overinst *)be->bd_info;
3177         cache_manager *cm;
3178         query_manager *qm;
3179
3180         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3181         on->on_bi.bi_private = cm;
3182
3183         qm = (query_manager*)ch_malloc(sizeof(query_manager));
3184
3185         cm->db = *be;
3186         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3187         cm->db.be_private = NULL;
3188         cm->db.bd_self = &cm->db;
3189         cm->qm = qm;
3190         cm->numattrsets = 0;
3191         cm->num_entries_limit = 5;
3192         cm->num_cached_queries = 0;
3193         cm->max_entries = 0;
3194         cm->cur_entries = 0;
3195         cm->max_queries = 10000;
3196         cm->save_queries = 0;
3197         cm->check_cacheability = 0;
3198         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3199         cm->defer_db_open = 1;
3200         cm->cc_period = 1000;
3201         cm->cc_paused = 0;
3202         cm->cc_arg = NULL;
3203
3204         qm->attr_sets = NULL;
3205         qm->templates = NULL;
3206         qm->lru_top = NULL;
3207         qm->lru_bottom = NULL;
3208
3209         qm->qcfunc = query_containment;
3210         qm->crfunc = cache_replacement;
3211         qm->addfunc = add_query;
3212         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3213
3214         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3215         return 0;
3216 }
3217
3218 static int
3219 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3220 {
3221         assert( op->o_tag == LDAP_REQ_SEARCH );
3222
3223         if ( rs->sr_type == REP_SEARCH ) {
3224                 Attribute       *a;
3225
3226                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3227                 if ( a != NULL ) {
3228                         BerVarray       *valsp;
3229
3230                         assert( a->a_nvals != NULL );
3231
3232                         valsp = op->o_callback->sc_private;
3233                         assert( *valsp == NULL );
3234
3235                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3236                 }
3237         }
3238
3239         return 0;
3240 }
3241
3242 static int
3243 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3244 {
3245         assert( op->o_tag == LDAP_REQ_SEARCH );
3246
3247         if ( rs->sr_type == REP_SEARCH ) {
3248                 int     *countp = (int *)op->o_callback->sc_private;
3249
3250                 (*countp)++;
3251         }
3252
3253         return 0;
3254 }
3255
3256 static int
3257 pcache_db_open2(
3258         slap_overinst *on,
3259         ConfigReply *cr )
3260 {
3261         cache_manager   *cm = on->on_bi.bi_private;
3262         query_manager*  qm = cm->qm;
3263         int rc;
3264
3265         rc = backend_startup_one( &cm->db, cr );
3266         if ( rc == 0 ) {
3267                 cm->defer_db_open = 0;
3268         }
3269
3270         /* There is no runqueue in TOOL mode */
3271         if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
3272                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3273                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3274                         consistency_check, on,
3275                         "pcache_consistency", cm->db.be_suffix[0].bv_val );
3276                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3277
3278                 /* Cached database must have the rootdn */
3279                 if ( BER_BVISNULL( &cm->db.be_rootndn )
3280                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3281                 {
3282                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3283                                 "underlying database of type \"%s\"\n"
3284                                 "    serving naming context \"%s\"\n"
3285                                 "    has no \"rootdn\", required by \"proxycache\".\n",
3286                                 on->on_info->oi_orig->bi_type,
3287                                 cm->db.be_suffix[0].bv_val, 0 );
3288                         return 1;
3289                 }
3290
3291                 if ( cm->save_queries ) {
3292                         void            *thrctx = ldap_pvt_thread_pool_context();
3293                         Connection      conn = { 0 };
3294                         OperationBuffer opbuf;
3295                         Operation       *op;
3296                         slap_callback   cb = { 0 };
3297                         SlapReply       rs = { 0 };
3298                         BerVarray       vals = NULL;
3299                         Filter          f = { 0 }, f2 = { 0 };
3300                         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
3301                         AttributeName   attrs[ 2 ] = {{{ 0 }}};
3302
3303                         connection_fake_init( &conn, &opbuf, thrctx );
3304                         op = &opbuf.ob_op;
3305
3306                         op->o_bd = &cm->db;
3307
3308                         op->o_tag = LDAP_REQ_SEARCH;
3309                         op->o_protocol = LDAP_VERSION3;
3310                         cb.sc_response = pcache_cachedquery_open_cb;
3311                         cb.sc_private = &vals;
3312                         op->o_callback = &cb;
3313                         op->o_time = slap_get_time();
3314                         op->o_do_not_cache = 1;
3315                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
3316
3317                         op->o_dn = cm->db.be_rootdn;
3318                         op->o_ndn = cm->db.be_rootndn;
3319                         op->o_req_dn = cm->db.be_suffix[ 0 ];
3320                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3321
3322                         op->ors_scope = LDAP_SCOPE_BASE;
3323                         op->ors_deref = LDAP_DEREF_NEVER;
3324                         op->ors_slimit = 1;
3325                         op->ors_tlimit = SLAP_NO_LIMIT;
3326                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3327                         f.f_choice = LDAP_FILTER_PRESENT;
3328                         f.f_desc = ad_cachedQueryURL;
3329                         op->ors_filter = &f;
3330                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
3331                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3332                         op->ors_attrs = attrs;
3333                         op->ors_attrsonly = 0;
3334
3335                         rc = op->o_bd->be_search( op, &rs );
3336                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
3337                                 int     i;
3338
3339                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3340                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3341                                                 cm->num_cached_queries++;
3342                                         }
3343                                 }
3344
3345                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3346                         }
3347
3348                         /* count cached entries */
3349                         f.f_choice = LDAP_FILTER_NOT;
3350                         f.f_not = &f2;
3351                         f2.f_choice = LDAP_FILTER_EQUALITY;
3352                         f2.f_ava = &ava;
3353                         f2.f_av_desc = slap_schema.si_ad_objectClass;
3354                         BER_BVSTR( &f2.f_av_value, "glue" );
3355                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3356
3357                         op->ors_slimit = SLAP_NO_LIMIT;
3358                         op->ors_scope = LDAP_SCOPE_SUBTREE;
3359                         op->ors_attrs = slap_anlist_no_attrs;
3360
3361                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
3362                         rs.sr_nentries = 0;
3363                         op->o_callback->sc_private = &rs.sr_nentries;
3364
3365                         rc = op->o_bd->be_search( op, &rs );
3366
3367                         cm->cur_entries = rs.sr_nentries;
3368
3369                         /* ignore errors */
3370                         rc = 0;
3371                 }
3372         }
3373         return rc;
3374 }
3375
3376 static int
3377 pcache_db_open(
3378         BackendDB *be,
3379         ConfigReply *cr )
3380 {
3381         slap_overinst   *on = (slap_overinst *)be->bd_info;
3382         cache_manager   *cm = on->on_bi.bi_private;
3383         query_manager*  qm = cm->qm;
3384         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3385
3386         /* check attr sets */
3387         for ( i = 0; i < cm->numattrsets; i++) {
3388                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3389                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3390                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3391                                 rf++;
3392
3393                         } else {
3394                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3395                         }
3396                         ncf++;
3397
3398                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3399                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3400                         nrf++;
3401                 }
3402         }
3403
3404         if ( ncf || rf || nrf ) {
3405                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3406                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3407                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3408
3409                 if ( rf > 0 ) {
3410                         return 1;
3411                 }
3412         }
3413
3414         /* need to inherit something from the original database... */
3415         cm->db.be_def_limit = be->be_def_limit;
3416         cm->db.be_limits = be->be_limits;
3417         cm->db.be_acl = be->be_acl;
3418         cm->db.be_dfltaccess = be->be_dfltaccess;
3419
3420         if ( SLAP_DBMONITORING( be ) ) {
3421                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3422
3423         } else {
3424                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3425         }
3426
3427         if ( !cm->defer_db_open )
3428                 rc = pcache_db_open2( on, cr );
3429
3430         return rc;
3431 }
3432
3433 static void
3434 pcache_free_qbase( void *v )
3435 {
3436         Qbase *qb = v;
3437         int i;
3438
3439         for (i=0; i<3; i++)
3440                 tavl_free( qb->scopes[i], NULL );
3441         ch_free( qb );
3442 }
3443
3444 static int
3445 pcache_db_close(
3446         BackendDB *be,
3447         ConfigReply *cr
3448 )
3449 {
3450         slap_overinst *on = (slap_overinst *)be->bd_info;
3451         cache_manager *cm = on->on_bi.bi_private;
3452         query_manager *qm = cm->qm;
3453         QueryTemplate *tm;
3454         int i, rc = 0;
3455
3456         if ( cm->save_queries ) {
3457                 CachedQuery     *qc;
3458                 BerVarray       vals = NULL;
3459
3460                 void            *thrctx;
3461                 Connection      conn = { 0 };
3462                 OperationBuffer opbuf;
3463                 Operation       *op;
3464                 slap_callback   cb = { 0 };
3465
3466                 SlapReply       rs = { REP_RESULT };
3467                 Modifications   mod = {{ 0 }};
3468
3469                 thrctx = ldap_pvt_thread_pool_context();
3470
3471                 connection_fake_init( &conn, &opbuf, thrctx );
3472                 op = &opbuf.ob_op;
3473
3474                 if ( qm->templates != NULL ) {
3475                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3476                                 for ( qc = tm->query; qc; qc = qc->next ) {
3477                                         struct berval   bv;
3478
3479                                         if ( query2url( op, qc, &bv ) == 0 ) {
3480                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3481                                         }
3482                                 }
3483                         }
3484                 }
3485
3486                 op->o_bd = &cm->db;
3487                 op->o_dn = cm->db.be_rootdn;
3488                 op->o_ndn = cm->db.be_rootndn;
3489
3490                 op->o_tag = LDAP_REQ_MODIFY;
3491                 op->o_protocol = LDAP_VERSION3;
3492                 cb.sc_response = slap_null_cb;
3493                 op->o_callback = &cb;
3494                 op->o_time = slap_get_time();
3495                 op->o_do_not_cache = 1;
3496                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3497
3498                 op->o_req_dn = op->o_bd->be_suffix[0];
3499                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3500
3501                 mod.sml_op = LDAP_MOD_REPLACE;
3502                 mod.sml_flags = 0;
3503                 mod.sml_desc = ad_cachedQueryURL;
3504                 mod.sml_type = ad_cachedQueryURL->ad_cname;
3505                 mod.sml_values = vals;
3506                 mod.sml_nvalues = NULL;
3507                 mod.sml_numvals = 1;
3508                 mod.sml_next = NULL;
3509                 Debug( pcache_debug,
3510                         "%sSETTING CACHED QUERY URLS\n",
3511                         vals == NULL ? "RE" : "", 0, 0 );
3512
3513                 op->orm_modlist = &mod;
3514
3515                 op->o_bd->be_modify( op, &rs );
3516
3517                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3518         }
3519
3520         /* cleanup stuff inherited from the original database... */
3521         cm->db.be_limits = NULL;
3522         cm->db.be_acl = NULL;
3523
3524         /* stop the thread ... */
3525         if ( cm->cc_arg ) {
3526                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3527                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3528                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3529                 }
3530                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3531                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3532         }
3533
3534         if ( cm->db.bd_info->bi_db_close ) {
3535                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3536         }
3537         while ( (tm = qm->templates) != NULL ) {
3538                 CachedQuery *qc, *qn;
3539                 qm->templates = tm->qmnext;
3540                 for ( qc = tm->query; qc; qc = qn ) {
3541                         qn = qc->next;
3542                         free_query( qc );
3543                 }
3544                 avl_free( tm->qbase, pcache_free_qbase );
3545                 free( tm->querystr.bv_val );
3546                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3547                 free( tm->t_attrs.attrs );
3548                 free( tm );
3549         }
3550
3551         for ( i=0; i<cm->numattrsets; i++ ) {
3552                 free( qm->attr_sets[i].attrs );
3553         }
3554         free( qm->attr_sets );
3555         qm->attr_sets = NULL;
3556
3557         return rc;
3558 }
3559
3560 static int
3561 pcache_db_destroy(
3562         BackendDB *be,
3563         ConfigReply *cr
3564 )
3565 {
3566         slap_overinst *on = (slap_overinst *)be->bd_info;
3567         cache_manager *cm = on->on_bi.bi_private;
3568         query_manager *qm = cm->qm;
3569
3570         if ( cm->db.be_private != NULL ) {
3571                 backend_stopdown_one( &cm->db );
3572         }
3573
3574         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3575         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3576         free( qm );
3577         free( cm );
3578
3579         return 0;
3580 }
3581
3582 #ifdef PCACHE_CONTROL_PRIVDB
3583 /*
3584         Control ::= SEQUENCE {
3585              controlType             LDAPOID,
3586              criticality             BOOLEAN DEFAULT FALSE,
3587              controlValue            OCTET STRING OPTIONAL }
3588
3589         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3590
3591  * criticality must be TRUE; controlValue must be absent.
3592  */
3593 static int
3594 parse_privdb_ctrl(
3595         Operation       *op,
3596         SlapReply       *rs,
3597         LDAPControl     *ctrl )
3598 {
3599         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3600                 rs->sr_text = "privateDB control specified multiple times";
3601                 return LDAP_PROTOCOL_ERROR;
3602         }
3603
3604         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3605                 rs->sr_text = "privateDB control value not absent";
3606                 return LDAP_PROTOCOL_ERROR;
3607         }
3608
3609         if ( !ctrl->ldctl_iscritical ) {
3610                 rs->sr_text = "privateDB control criticality required";
3611                 return LDAP_PROTOCOL_ERROR;
3612         }
3613
3614         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3615
3616         return LDAP_SUCCESS;
3617 }
3618
3619 static char *extops[] = {
3620         LDAP_EXOP_MODIFY_PASSWD,
3621         NULL
3622 };
3623 #endif /* PCACHE_CONTROL_PRIVDB */
3624
3625 #ifdef PCACHE_EXOP_QUERY_DELETE
3626 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3627
3628 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3629 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3630 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3631
3632 /*
3633         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3634              requestName      [0] LDAPOID,
3635              requestValue     [1] OCTET STRING OPTIONAL }
3636
3637         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3638
3639         requestValue ::= SEQUENCE { CHOICE {
3640                   baseDN           [0] LDAPDN
3641                   entryDN          [1] LDAPDN },
3642              queryID          [2] OCTET STRING (SIZE(16))
3643                   -- constrained to UUID }
3644
3645  * Either baseDN or entryDN must be present, to allow database selection.
3646  *
3647  * 1. if baseDN and queryID are present, then the query corresponding
3648  *    to queryID is deleted;
3649  * 2. if baseDN is present and queryID is absent, then all queries
3650  *    are deleted;
3651  * 3. if entryDN is present and queryID is absent, then all queries
3652  *    corresponding to the queryID values present in entryDN are deleted;
3653  * 4. if entryDN and queryID are present, then all queries
3654  *    corresponding to the queryID values present in entryDN are deleted,
3655  *    but only if the value of queryID is contained in the entry;
3656  *
3657  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
3658  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3659  * or by removing the database files.
3660
3661         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3662              COMPONENTS OF LDAPResult,
3663              responseName     [10] LDAPOID OPTIONAL,
3664              responseValue    [11] OCTET STRING OPTIONAL }
3665
3666  * responseName and responseValue must be absent.
3667  */
3668
3669 /*
3670  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3671  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3672  * - if ndn != NULL, it is set to the normalized DN in the request
3673  *   corresponding to either the baseDN or the entryDN, according
3674  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
3675  *   be freed by the caller.
3676  * - if uuid != NULL, it is set to point to the normalized UUID;
3677  *   memory is malloc'ed on the Operation's slab, and must
3678  *   be freed by the caller.
3679  */
3680 static int
3681 pcache_parse_query_delete(
3682         struct berval   *in,
3683         ber_tag_t       *tagp,
3684         struct berval   *ndn,
3685         struct berval   *uuid,
3686         const char      **text,
3687         void            *ctx )
3688 {
3689         int                     rc = LDAP_SUCCESS;
3690         ber_tag_t               tag;
3691         ber_len_t               len = -1;
3692         BerElementBuffer        berbuf;
3693         BerElement              *ber = (BerElement *)&berbuf;
3694         struct berval           reqdata = BER_BVNULL;
3695
3696         *text = NULL;
3697
3698         if ( ndn ) {
3699                 BER_BVZERO( ndn );
3700         }
3701
3702         if ( uuid ) {
3703                 BER_BVZERO( uuid );
3704         }
3705
3706         if ( in == NULL || in->bv_len == 0 ) {
3707                 *text = "empty request data field in queryDelete exop";
3708                 return LDAP_PROTOCOL_ERROR;
3709         }
3710
3711         ber_dupbv_x( &reqdata, in, ctx );
3712
3713         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3714         ber_init2( ber, &reqdata, 0 );
3715
3716         tag = ber_scanf( ber, "{" /*}*/ );
3717
3718         if ( tag == LBER_ERROR ) {
3719                 Debug( LDAP_DEBUG_TRACE,
3720                         "pcache_parse_query_delete: decoding error.\n",
3721                         0, 0, 0 );
3722                 goto decoding_error;
3723         }
3724
3725         tag = ber_peek_tag( ber, &len );
3726         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3727                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3728         {
3729                 *tagp = tag;
3730
3731                 if ( ndn != NULL ) {
3732                         struct berval   dn;
3733
3734                         tag = ber_scanf( ber, "m", &dn );
3735                         if ( tag == LBER_ERROR ) {
3736                                 Debug( LDAP_DEBUG_TRACE,
3737                                         "pcache_parse_query_delete: DN parse failed.\n",
3738                                         0, 0, 0 );
3739                                 goto decoding_error;
3740                         }
3741
3742                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3743                         if ( rc != LDAP_SUCCESS ) {
3744                                 *text = "invalid DN in queryDelete exop request data";
3745                                 goto done;
3746                         }
3747
3748                 } else {
3749                         tag = ber_scanf( ber, "x" /* "m" */ );
3750                         if ( tag == LBER_DEFAULT ) {
3751                                 goto decoding_error;
3752                         }
3753                 }
3754
3755                 tag = ber_peek_tag( ber, &len );
3756         }
3757
3758         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3759                 if ( uuid != NULL ) {
3760                         struct berval   bv;
3761                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3762
3763                         tag = ber_scanf( ber, "m", &bv );
3764                         if ( tag == LBER_ERROR ) {
3765                                 Debug( LDAP_DEBUG_TRACE,
3766                                         "pcache_parse_query_delete: UUID parse failed.\n",
3767                                         0, 0, 0 );
3768                                 goto decoding_error;
3769                         }
3770
3771                         if ( bv.bv_len != 16 ) {
3772                                 Debug( LDAP_DEBUG_TRACE,
3773                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3774                                         (unsigned long)bv.bv_len, 0, 0 );
3775                                 goto decoding_error;
3776                         }
3777
3778                         rc = lutil_uuidstr_from_normalized(
3779                                 bv.bv_val, bv.bv_len,
3780                                 uuidbuf, sizeof( uuidbuf ) );
3781                         if ( rc == -1 ) {
3782                                 goto decoding_error;
3783                         }
3784                         ber_str2bv( uuidbuf, rc, 1, uuid );
3785                         rc = LDAP_SUCCESS;
3786
3787                 } else {
3788                         tag = ber_skip_tag( ber, &len );
3789                         if ( tag == LBER_DEFAULT ) {
3790                                 goto decoding_error;
3791                         }
3792
3793                         if ( len != 16 ) {
3794                                 Debug( LDAP_DEBUG_TRACE,
3795                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3796                                         (unsigned long)len, 0, 0 );
3797                                 goto decoding_error;
3798                         }
3799                 }
3800
3801                 tag = ber_peek_tag( ber, &len );
3802         }
3803
3804         if ( tag != LBER_DEFAULT || len != 0 ) {
3805 decoding_error:;
3806                 Debug( LDAP_DEBUG_TRACE,
3807                         "pcache_parse_query_delete: decoding error\n",
3808                         0, 0, 0 );
3809                 rc = LDAP_PROTOCOL_ERROR;
3810                 *text = "queryDelete data decoding error";
3811
3812 done:;
3813                 if ( ndn && !BER_BVISNULL( ndn ) ) {
3814                         slap_sl_free( ndn->bv_val, ctx );
3815                         BER_BVZERO( ndn );
3816                 }
3817
3818                 if ( uuid && !BER_BVISNULL( uuid ) ) {
3819                         slap_sl_free( uuid->bv_val, ctx );
3820                         BER_BVZERO( uuid );
3821                 }
3822         }
3823
3824         if ( !BER_BVISNULL( &reqdata ) ) {
3825                 ber_memfree_x( reqdata.bv_val, ctx );
3826         }
3827
3828         return rc;
3829 }
3830
3831 static int
3832 pcache_exop_query_delete(
3833         Operation       *op,
3834         SlapReply       *rs )
3835 {
3836         BackendDB       *bd = op->o_bd;
3837
3838         struct berval   uuid = BER_BVNULL,
3839                         *uuidp = NULL;
3840         char            buf[ SLAP_TEXT_BUFLEN ];
3841         unsigned        len;
3842         ber_tag_t       tag = LBER_DEFAULT;
3843
3844         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3845                 uuidp = &uuid;
3846         }
3847
3848         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3849                 &tag, &op->o_req_ndn, uuidp,
3850                 &rs->sr_text, op->o_tmpmemctx );
3851         if ( rs->sr_err != LDAP_SUCCESS ) {
3852                 return rs->sr_err;
3853         }
3854
3855         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3856                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3857                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3858
3859                 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
3860                         snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3861                 }
3862
3863                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3864                         op->o_log_prefix, buf, 0 );
3865         }
3866         op->o_req_dn = op->o_req_ndn;
3867
3868         op->o_bd = select_backend( &op->o_req_ndn, 0 );
3869         rs->sr_err = backend_check_restrictions( op, rs,
3870                 (struct berval *)&pcache_exop_QUERY_DELETE );
3871         if ( rs->sr_err != LDAP_SUCCESS ) {
3872                 goto done;
3873         }
3874
3875         if ( op->o_bd->be_extended == NULL ) {
3876                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3877                         "backend does not support extended operations" );
3878                 goto done;
3879         }
3880
3881         op->o_bd->be_extended( op, rs );
3882
3883 done:;
3884         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3885                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3886                 BER_BVZERO( &op->o_req_ndn );
3887                 BER_BVZERO( &op->o_req_dn );
3888         }
3889
3890         if ( !BER_BVISNULL( &uuid ) ) {
3891                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3892         }
3893
3894         op->o_bd = bd;
3895
3896         return rs->sr_err;
3897 }
3898
3899 static int
3900 pcache_op_extended( Operation *op, SlapReply *rs )
3901 {
3902         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
3903         cache_manager   *cm = on->on_bi.bi_private;
3904
3905 #ifdef PCACHE_CONTROL_PRIVDB
3906         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3907                 return pcache_op_privdb( op, rs );
3908         }
3909 #endif /* PCACHE_CONTROL_PRIVDB */
3910
3911         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3912                 struct berval   uuid = BER_BVNULL;
3913                 ber_tag_t       tag = LBER_DEFAULT;
3914
3915                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3916                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3917                 assert( rs->sr_err == LDAP_SUCCESS );
3918
3919                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3920                         /* remove all queries related to the selected entry */
3921                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3922                                 cm, &op->o_req_ndn, &uuid );
3923
3924                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3925                         if ( !BER_BVISNULL( &uuid ) ) {
3926                                 /* remove the selected query */
3927                                 rs->sr_err = pcache_remove_query_from_cache( op,
3928                                         cm, &uuid );
3929
3930                         } else {
3931                                 /* TODO: remove all queries */
3932                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3933                                 rs->sr_text = "deletion of all queries not implemented";
3934                         }
3935                 }
3936
3937                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3938         }
3939
3940         return rs->sr_err;
3941 }
3942 #endif /* PCACHE_EXOP_QUERY_DELETE */
3943
3944 static slap_overinst pcache;
3945
3946 static char *obsolete_names[] = {
3947         "proxycache",
3948         NULL
3949 };
3950
3951 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3952 static
3953 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3954 int
3955 pcache_initialize()
3956 {
3957         int i, code;
3958         struct berval debugbv = BER_BVC("pcache");
3959
3960         code = slap_loglevel_get( &debugbv, &pcache_debug );
3961         if ( code ) {
3962                 return code;
3963         }
3964
3965 #ifdef PCACHE_CONTROL_PRIVDB
3966         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3967                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3968                 parse_privdb_ctrl, &privDB_cid );
3969         if ( code != LDAP_SUCCESS ) {
3970                 Debug( LDAP_DEBUG_ANY,
3971                         "pcache_initialize: failed to register control %s (%d)\n",
3972                         PCACHE_CONTROL_PRIVDB, code, 0 );
3973                 return code;
3974         }
3975 #endif /* PCACHE_CONTROL_PRIVDB */
3976
3977 #ifdef PCACHE_EXOP_QUERY_DELETE
3978         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3979                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3980                 0 );
3981         if ( code != LDAP_SUCCESS ) {
3982                 Debug( LDAP_DEBUG_ANY,
3983                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
3984                         code, 0, 0 );
3985                 return code;
3986         }
3987 #endif /* PCACHE_EXOP_QUERY_DELETE */
3988
3989         for ( i = 0; as[i].desc != NULL; i++ ) {
3990                 code = register_at( as[i].desc, as[i].adp, 0 );
3991                 if ( code ) {
3992                         Debug( LDAP_DEBUG_ANY,
3993                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3994                         return code;
3995                 }
3996                 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3997         }
3998
3999         pcache.on_bi.bi_type = "pcache";
4000         pcache.on_bi.bi_obsolete_names = obsolete_names;
4001         pcache.on_bi.bi_db_init = pcache_db_init;
4002         pcache.on_bi.bi_db_config = pcache_db_config;
4003         pcache.on_bi.bi_db_open = pcache_db_open;
4004         pcache.on_bi.bi_db_close = pcache_db_close;
4005         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
4006
4007         pcache.on_bi.bi_op_search = pcache_op_search;
4008 #ifdef PCACHE_CONTROL_PRIVDB
4009         pcache.on_bi.bi_op_bind = pcache_op_privdb;
4010         pcache.on_bi.bi_op_compare = pcache_op_privdb;
4011         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
4012         pcache.on_bi.bi_op_modify = pcache_op_privdb;
4013         pcache.on_bi.bi_op_add = pcache_op_privdb;
4014         pcache.on_bi.bi_op_delete = pcache_op_privdb;
4015 #endif /* PCACHE_CONTROL_PRIVDB */
4016 #ifdef PCACHE_EXOP_QUERY_DELETE
4017         pcache.on_bi.bi_extended = pcache_op_extended;
4018 #elif defined( PCACHE_CONTROL_PRIVDB )
4019         pcache.on_bi.bi_extended = pcache_op_privdb;
4020 #endif
4021
4022         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
4023
4024         pcache.on_bi.bi_cf_ocs = pcocs;
4025
4026         code = config_register_schema( pccfg, pcocs );
4027         if ( code ) return code;
4028
4029         return overlay_register( &pcache );
4030 }
4031
4032 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4033 int init_module(int argc, char *argv[]) {
4034         return pcache_initialize();
4035 }
4036 #endif
4037
4038 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */