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