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