]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
ITS#6152 preliminary refresh support, untested
[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 } dnlist;
2677
2678 typedef struct refresh_info {
2679         dnlist *ri_dns;
2680         dnlist *ri_tail;
2681         dnlist *ri_dels;
2682         BackendDB *ri_be;
2683         CachedQuery *ri_q;
2684 } refresh_info;
2685
2686 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
2687 {
2688         dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
2689                         op->o_tmpmemctx );
2690         dn->dn.bv_len = bvdn->bv_len;
2691         dn->dn.bv_val = (char *)(dn+1);
2692         AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
2693         dn->dn.bv_val[dn->dn.bv_len] = '\0';
2694         return dn;
2695 }
2696
2697 static int
2698 refresh_merge( Operation *op, SlapReply *rs )
2699 {
2700         if ( rs->sr_type == REP_SEARCH ) {
2701                 refresh_info *ri = op->o_callback->sc_private;
2702                 BackendDB *be = op->o_bd;
2703                 Entry *e;
2704                 dnlist *dn;
2705                 slap_callback *ocb;
2706                 int rc;
2707
2708                 ocb = op->o_callback;
2709                 /* Find local entry, merge */
2710                 op->o_bd = ri->ri_be;
2711                 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
2712                 if ( rc != LDAP_SUCCESS || e == NULL ) {
2713                         /* No local entry, just add it. FIXME: we are not checking
2714                          * the cache entry limit here
2715                          */
2716                          merge_entry( op, rs->sr_entry, &ri->ri_q->q_uuid );
2717                 } else {
2718                         /* Entry exists, update it */
2719                         Entry ne;
2720                         Attribute *a, **b;
2721                         Modifications *modlist, *mods;
2722                         const char*     text = NULL;
2723                         char                    textbuf[SLAP_TEXT_BUFLEN];
2724                         size_t                  textlen = sizeof(textbuf);
2725                         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
2726
2727                         ne = *e;
2728                         b = &ne.e_attrs;
2729                         /* Get a copy of only the attrs we requested */
2730                         for ( a=e->e_attrs; a; a=a->a_next ) {
2731                                 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
2732                                         *b = attr_alloc( a->a_desc );
2733                                         *(*b) = *a;
2734                                         b = &((*b)->a_next);
2735                                 }
2736                         }
2737                         *b = NULL;
2738                         slap_entry2mods( &ne, &modlist, &text, textbuf, textlen );
2739                         syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
2740                                 &mods, &modlist, 0 );
2741                         be_entry_release_r( op, e );
2742                         op->o_tag = LDAP_REQ_MODIFY;
2743                         op->orm_modlist = mods;
2744                         op->o_callback = &cb;
2745                         op->o_bd->be_modify( op, rs );
2746                         slap_mods_free( mods, 1 );
2747                 }
2748
2749                 /* Add DN to list */
2750                 dn = dnl_alloc( op, &rs->sr_entry->e_nname );
2751                 dn->next = NULL;
2752                 if ( ri->ri_tail ) {
2753                         ri->ri_tail->next = dn;
2754                 } else {
2755                         ri->ri_dns = dn;
2756                 }
2757                 ri->ri_tail = dn;
2758                 op->o_callback = ocb;
2759         }
2760         return 0;
2761 }
2762
2763 static int
2764 refresh_purge( Operation *op, SlapReply *rs )
2765 {
2766         if ( rs->sr_type == REP_SEARCH ) {
2767                 refresh_info *ri = op->o_callback->sc_private;
2768                 dnlist **dn;
2769                 int del = 1;
2770
2771                 /* Did the entry exist on the remote? */
2772                 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
2773                         if ( dnmatch( &(*dn)->dn, &rs->sr_entry->e_nname )) {
2774                                 dnlist *dnext = (*dn)->next;
2775                                 op->o_tmpfree( *dn, op->o_tmpmemctx );
2776                                 *dn = dnext;
2777                                 del = 0;
2778                                 break;
2779                         }
2780                 }
2781                 /* No, so put it on the list to delete */
2782                 if ( del ) {
2783                         dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
2784                         dnl->next = ri->ri_dels;
2785                         ri->ri_dels = dnl;
2786                 }
2787         }
2788         return 0;
2789 }
2790
2791 static int
2792 refresh_query( Operation *op, SlapReply *rs, CachedQuery *query,
2793         slap_overinst *on )
2794 {
2795         slap_callback cb = { 0 };
2796         refresh_info ri = { 0 };
2797         char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
2798         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
2799         Filter filter = {LDAP_FILTER_EQUALITY};
2800         dnlist *dn;
2801         int i, rc;
2802
2803         cb.sc_response = refresh_merge;
2804         cb.sc_private = &ri;
2805
2806         /* cache DB */
2807         ri.ri_be = op->o_bd;
2808         ri.ri_q = query;
2809
2810         op->o_tag = LDAP_REQ_SEARCH;
2811         op->o_protocol = LDAP_VERSION3;
2812         op->o_callback = &cb;
2813         op->o_do_not_cache = 1;
2814
2815         op->o_req_dn = query->qbase->base;
2816         op->o_req_ndn = query->qbase->base;
2817         op->ors_scope = query->scope;
2818         op->ors_slimit = SLAP_NO_LIMIT;
2819         op->ors_tlimit = SLAP_NO_LIMIT;
2820         op->ors_filter = query->filter;
2821         filter2bv_x( op, query->filter, &op->ors_filterstr );
2822         op->ors_attrs = query->qtemp->t_attrs.attrs;
2823         op->ors_attrsonly = 0;
2824
2825         op->o_bd = on->on_info->oi_origdb;
2826         rc = op->o_bd->be_search( op, rs );
2827         if ( rc ) {
2828                 op->o_bd = ri.ri_be;
2829                 goto leave;
2830         }
2831
2832         /* Get the DNs of all entries matching this query */
2833         cb.sc_response = refresh_purge;
2834
2835         op->o_bd = ri.ri_be;
2836         op->o_req_dn = op->o_bd->be_suffix[0];
2837         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2838         op->ors_scope = LDAP_SCOPE_SUBTREE;
2839         op->ors_deref = LDAP_DEREF_NEVER;
2840         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
2841                 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
2842         filter.f_ava = &ava;
2843         filter.f_av_desc = ad_queryId;
2844         filter.f_av_value = query->q_uuid;
2845         op->ors_attrs = slap_anlist_no_attrs;
2846         op->ors_attrsonly = 1;
2847         rs->sr_entry = NULL;
2848         rs->sr_nentries = 0;
2849         rc = op->o_bd->be_search( op, rs );
2850         if ( rc ) goto leave;
2851
2852         op->o_tag = LDAP_REQ_DELETE;
2853         while (( dn = ri.ri_dels )) {
2854                 op->o_req_dn = dn->dn;
2855                 op->o_req_ndn = dn->dn;
2856                 op->o_bd->be_delete( op, rs );
2857                 ri.ri_dels = dn->next;
2858                 op->o_tmpfree( dn, op->o_tmpmemctx );
2859         }
2860
2861 leave:
2862         /* reset our local heap, we're done with it */
2863         slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
2864         return rc;
2865 }
2866
2867 static void*
2868 consistency_check(
2869         void *ctx,
2870         void *arg )
2871 {
2872         struct re_s *rtask = arg;
2873         slap_overinst *on = rtask->arg;
2874         cache_manager *cm = on->on_bi.bi_private;
2875         query_manager *qm = cm->qm;
2876         Connection conn = {0};
2877         OperationBuffer opbuf;
2878         Operation *op;
2879
2880         SlapReply rs = {REP_RESULT};
2881         CachedQuery *query, *qprev;
2882         int return_val, pause = PCACHE_CC_PAUSED;
2883         QueryTemplate *templ;
2884
2885         /* Don't expire anything when we're offline */
2886         if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
2887                 pause = PCACHE_CC_OFFLINE;
2888                 goto leave;
2889         }
2890
2891         connection_fake_init( &conn, &opbuf, ctx );
2892         op = &opbuf.ob_op;
2893
2894         op->o_bd = &cm->db;
2895         op->o_dn = cm->db.be_rootdn;
2896         op->o_ndn = cm->db.be_rootndn;
2897
2898         cm->cc_arg = arg;
2899
2900         for (templ = qm->templates; templ; templ=templ->qmnext) {
2901                 time_t ttl;
2902                 if ( !templ->query_last ) continue;
2903                 pause = 0;
2904                 op->o_time = slap_get_time();
2905                 if ( !templ->ttr ) {
2906                         ttl = templ->ttl;
2907                         if ( templ->negttl && templ->negttl < ttl )
2908                                 ttl = templ->negttl;
2909                         if ( templ->limitttl && templ->limitttl < ttl )
2910                                 ttl = templ->limitttl;
2911                         /* The oldest timestamp that needs expiration checking */
2912                         ttl += op->o_time;
2913                 }
2914
2915                 for ( query=templ->query_last; query; query=qprev ) {
2916                         qprev = query->prev;
2917                         if ( query->refresh_time && query->refresh_time < op->o_time ) {
2918                                 /* A refresh will extend the expiry if the query has been
2919                                  * referenced, but not if it's unreferenced. If the
2920                                  * expiration has been hit, then skip the refresh since
2921                                  * we're just going to discard the result anyway.
2922                                  */
2923                                 if ( query->refcnt )
2924                                         query->expiry_time = op->o_time + templ->ttl;
2925                                 if ( query->expiry_time > op->o_time ) {
2926                                         refresh_query( op, &rs, query, on );
2927                                         continue;
2928                                 }
2929                         }
2930
2931                         if (query->expiry_time < op->o_time) {
2932                                 int rem = 0;
2933                                 Debug( pcache_debug, "Lock CR index = %p\n",
2934                                                 (void *) templ, 0, 0 );
2935                                 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2936                                 if ( query == templ->query_last ) {
2937                                         rem = 1;
2938                                         remove_from_template(query, templ);
2939                                         Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2940                                                         (void *) templ, templ->no_of_queries, 0 );
2941                                         Debug( pcache_debug, "Unlock CR index = %p\n",
2942                                                         (void *) templ, 0, 0 );
2943                                 }
2944                                 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2945                                 if ( !rem ) {
2946                                         continue;
2947                                 }
2948                                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2949                                 remove_query(qm, query);
2950                                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2951                                 if ( BER_BVISNULL( &query->q_uuid ))
2952                                         return_val = 0;
2953                                 else
2954                                         return_val = remove_query_data(op, &rs, &query->q_uuid);
2955                                 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2956                                                         return_val, 0, 0 );
2957                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2958                                 cm->cur_entries -= return_val;
2959                                 cm->num_cached_queries--;
2960                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2961                                                 cm->num_cached_queries, 0, 0 );
2962                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2963                                 Debug( pcache_debug,
2964                                         "STALE QUERY REMOVED, CACHE ="
2965                                         "%d entries\n",
2966                                         cm->cur_entries, 0, 0 );
2967                                 free_query(query);
2968                         } else if ( !templ->ttr && query->expiry_time > ttl ) {
2969                                 /* We don't need to check for refreshes, and this
2970                                  * query's expiry is too new, and all subsequent queries
2971                                  * will be newer yet. So stop looking.
2972                                  *
2973                                  * If we have refreshes, then we always have to walk the
2974                                  * entire query list.
2975                                  */
2976                                 break;
2977                         }
2978                 }
2979         }
2980
2981 leave:
2982         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2983         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2984                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2985         }
2986         /* If there were no queries, defer processing for a while */
2987         if ( cm->cc_paused != pause )
2988                 cm->cc_paused = pause;
2989         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2990
2991         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2992         return NULL;
2993 }
2994
2995
2996 #define MAX_ATTR_SETS 500
2997
2998 enum {
2999         PC_MAIN = 1,
3000         PC_ATTR,
3001         PC_TEMP,
3002         PC_RESP,
3003         PC_QUERIES,
3004         PC_OFFLINE,
3005         PC_PRIVATE_DB
3006 };
3007
3008 static ConfigDriver pc_cf_gen;
3009 static ConfigLDAPadd pc_ldadd;
3010 static ConfigCfAdd pc_cfadd;
3011
3012 static ConfigTable pccfg[] = {
3013         { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3014                                 "<cycle_time",
3015                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3016                 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3017                         "DESC 'Proxy Cache basic parameters' "
3018                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3019         { "pcacheAttrset", "index> <attributes...",
3020                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3021                 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3022                         "DESC 'A set of attributes to cache' "
3023                         "SYNTAX OMsDirectoryString )", NULL, NULL },
3024         { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3025                         "<limitTTL> <TTR",
3026                 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3027                 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3028                         "DESC 'Filter template, attrset, cache TTL, "
3029                                 "optional negative TTL, optional sizelimit TTL, "
3030                                 "optional TTR' "
3031                         "SYNTAX OMsDirectoryString )", NULL, NULL },
3032         { "pcachePosition", "head|tail(default)",
3033                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3034                 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3035                         "DESC 'Response callback position in overlay stack' "
3036                         "SYNTAX OMsDirectoryString )", NULL, NULL },
3037         { "pcacheMaxQueries", "queries",
3038                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3039                 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3040                         "DESC 'Maximum number of queries to cache' "
3041                         "SYNTAX OMsInteger )", NULL, NULL },
3042         { "pcachePersist", "TRUE|FALSE",
3043                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3044                 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3045                         "DESC 'Save cached queries for hot restart' "
3046                         "SYNTAX OMsBoolean )", NULL, NULL },
3047         { "pcacheValidate", "TRUE|FALSE",
3048                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3049                 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3050                         "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3051                         "SYNTAX OMsBoolean )", NULL, NULL },
3052         { "pcacheOffline", "TRUE|FALSE",
3053                 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3054                 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3055                         "DESC 'Set cache to offline mode and disable expiration' "
3056                         "SYNTAX OMsBoolean )", NULL, NULL },
3057         { "pcache-", "private database args",
3058                 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3059                 NULL, NULL, NULL },
3060
3061         /* Legacy keywords */
3062         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3063                                 "<cycle_time",
3064                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3065                 NULL, NULL, NULL },
3066         { "proxyattrset", "index> <attributes...",
3067                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3068                 NULL, NULL, NULL },
3069         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3070                 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3071                 NULL, NULL, NULL },
3072         { "response-callback", "head|tail(default)",
3073                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3074                 NULL, NULL, NULL },
3075         { "proxyCacheQueries", "queries",
3076                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3077                 NULL, NULL, NULL },
3078         { "proxySaveQueries", "TRUE|FALSE",
3079                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3080                 NULL, NULL, NULL },
3081         { "proxyCheckCacheability", "TRUE|FALSE",
3082                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3083                 NULL, NULL, NULL },
3084
3085         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3086 };
3087
3088 static ConfigOCs pcocs[] = {
3089         { "( OLcfgOvOc:2.1 "
3090                 "NAME 'olcPcacheConfig' "
3091                 "DESC 'ProxyCache configuration' "
3092                 "SUP olcOverlayConfig "
3093                 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3094                 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3095                         "olcPcacheValidate $ olcPcacheOffline ) )",
3096                 Cft_Overlay, pccfg, NULL, pc_cfadd },
3097         { "( OLcfgOvOc:2.2 "
3098                 "NAME 'olcPcacheDatabase' "
3099                 "DESC 'Cache database configuration' "
3100                 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3101         { NULL, 0, NULL }
3102 };
3103
3104 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3105
3106 static int
3107 pc_ldadd_cleanup( ConfigArgs *c )
3108 {
3109         slap_overinst *on = c->ca_private;
3110         return pcache_db_open2( on, &c->reply );
3111 }
3112
3113 static int
3114 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3115 {
3116         slap_overinst *on;
3117         cache_manager *cm;
3118
3119         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3120                 p->ce_bi->bi_cf_ocs != pcocs )
3121                 return LDAP_CONSTRAINT_VIOLATION;
3122
3123         on = (slap_overinst *)p->ce_bi;
3124         cm = on->on_bi.bi_private;
3125         ca->be = &cm->db;
3126         /* Defer open if this is an LDAPadd */
3127         if ( CONFIG_ONLINE_ADD( ca ))
3128                 ca->cleanup = pc_ldadd_cleanup;
3129         else
3130                 cm->defer_db_open = 0;
3131         ca->ca_private = on;
3132         return LDAP_SUCCESS;
3133 }
3134
3135 static int
3136 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3137 {
3138         CfEntryInfo *pe = p->e_private;
3139         slap_overinst *on = (slap_overinst *)pe->ce_bi;
3140         cache_manager *cm = on->on_bi.bi_private;
3141         struct berval bv;
3142
3143         /* FIXME: should not hardcode "olcDatabase" here */
3144         bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3145                 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3146                 0, cm->db.bd_info->bi_type );
3147         if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3148                 return -1;
3149         }
3150         bv.bv_val = ca->cr_msg;
3151         ca->be = &cm->db;
3152         cm->defer_db_open = 0;
3153
3154         /* We can only create this entry if the database is table-driven
3155          */
3156         if ( cm->db.bd_info->bi_cf_ocs )
3157                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3158                         &pcocs[1] );
3159
3160         return 0;
3161 }
3162
3163 static int
3164 pc_cf_gen( ConfigArgs *c )
3165 {
3166         slap_overinst   *on = (slap_overinst *)c->bi;
3167         cache_manager*  cm = on->on_bi.bi_private;
3168         query_manager*  qm = cm->qm;
3169         QueryTemplate*  temp;
3170         AttributeName*  attr_name;
3171         AttributeName*  attrarray;
3172         const char*     text=NULL;
3173         int             i, num, rc = 0;
3174         char            *ptr;
3175         unsigned long   t;
3176
3177         if ( c->op == SLAP_CONFIG_EMIT ) {
3178                 struct berval bv;
3179                 switch( c->type ) {
3180                 case PC_MAIN:
3181                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3182                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3183                                 cm->num_entries_limit, cm->cc_period );
3184                         bv.bv_val = c->cr_msg;
3185                         value_add_one( &c->rvalue_vals, &bv );
3186                         break;
3187                 case PC_ATTR:
3188                         for (i=0; i<cm->numattrsets; i++) {
3189                                 if ( !qm->attr_sets[i].count ) continue;
3190
3191                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3192
3193                                 /* count the attr length */
3194                                 for ( attr_name = qm->attr_sets[i].attrs;
3195                                         attr_name->an_name.bv_val; attr_name++ )
3196                                         bv.bv_len += attr_name->an_name.bv_len + 1;
3197
3198                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
3199                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3200                                 for ( attr_name = qm->attr_sets[i].attrs;
3201                                         attr_name->an_name.bv_val; attr_name++ ) {
3202                                         *ptr++ = ' ';
3203                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3204                                 }
3205                                 ber_bvarray_add( &c->rvalue_vals, &bv );
3206                         }
3207                         if ( !c->rvalue_vals )
3208                                 rc = 1;
3209                         break;
3210                 case PC_TEMP:
3211                         for (temp=qm->templates; temp; temp=temp->qmnext) {
3212                                 /* HEADS-UP: always print all;
3213                                  * if optional == 0, ignore */
3214                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3215                                         " %d %ld %ld %ld %ld",
3216                                         temp->attr_set_index,
3217                                         temp->ttl,
3218                                         temp->negttl,
3219                                         temp->limitttl,
3220                                         temp->ttr );
3221                                 bv.bv_len += temp->querystr.bv_len + 2;
3222                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
3223                                 ptr = bv.bv_val;
3224                                 *ptr++ = '"';
3225                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3226                                 *ptr++ = '"';
3227                                 strcpy( ptr, c->cr_msg );
3228                                 ber_bvarray_add( &c->rvalue_vals, &bv );
3229                         }
3230                         if ( !c->rvalue_vals )
3231                                 rc = 1;
3232                         break;
3233                 case PC_RESP:
3234                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3235                                 BER_BVSTR( &bv, "head" );
3236                         } else {
3237                                 BER_BVSTR( &bv, "tail" );
3238                         }
3239                         value_add_one( &c->rvalue_vals, &bv );
3240                         break;
3241                 case PC_QUERIES:
3242                         c->value_int = cm->max_queries;
3243                         break;
3244                 case PC_OFFLINE:
3245                         c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3246                         break;
3247                 }
3248                 return rc;
3249         } else if ( c->op == LDAP_MOD_DELETE ) {
3250                 rc = 1;
3251                 switch( c->type ) {
3252                 case PC_ATTR: /* FIXME */
3253                 case PC_TEMP:
3254                         break;
3255                 case PC_OFFLINE:
3256                         cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3257                         rc = 0;
3258                         break;
3259                 }
3260                 return rc;
3261         }
3262
3263         switch( c->type ) {
3264         case PC_MAIN:
3265                 if ( cm->numattrsets > 0 ) {
3266                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
3267                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3268                         return( 1 );
3269                 }
3270
3271                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3272                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3273                                 c->argv[3] );
3274                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3275                         return( 1 );
3276                 }
3277                 if ( cm->numattrsets <= 0 ) {
3278                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3279                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3280                         return( 1 );
3281                 }
3282                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3283                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3284                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3285                         return( 1 );
3286                 }
3287
3288                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3289                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3290                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3291                         return( 1 );
3292                 }
3293
3294                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3295                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3296                                 c->argv[2] );
3297                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3298                         return( 1 );
3299                 }
3300                 if ( cm->max_entries <= 0 ) {
3301                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3302                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
3303                         return( 1 );
3304                 }
3305
3306                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
3307                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
3308                                 c->argv[4] );
3309                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3310                         return( 1 );
3311                 }
3312                 if ( cm->num_entries_limit <= 0 ) {
3313                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
3314                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3315                         return( 1 );
3316                 }
3317                 if ( cm->num_entries_limit > cm->max_entries ) {
3318                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
3319                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3320                         return( 1 );
3321                 }
3322
3323                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3324                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
3325                                 c->argv[5] );
3326                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3327                         return( 1 );
3328                 }
3329
3330                 cm->cc_period = (time_t)t;
3331                 Debug( pcache_debug,
3332                                 "Total # of attribute sets to be cached = %d.\n",
3333                                 cm->numattrsets, 0, 0 );
3334                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
3335                                                 sizeof( struct attr_set ) );
3336                 break;
3337         case PC_ATTR:
3338                 if ( cm->numattrsets == 0 ) {
3339                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3340                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3341                         return( 1 );
3342                 }
3343                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
3344                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
3345                                 c->argv[1] );
3346                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3347                         return( 1 );
3348                 }
3349
3350                 if ( num < 0 || num >= cm->numattrsets ) {
3351                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
3352                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3353                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3354                         return 1;
3355                 }
3356                 qm->attr_sets[num].flags |= PC_CONFIGURED;
3357                 if ( c->argc == 2 ) {
3358                         /* assume "1.1" */
3359                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3360                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
3361                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3362                         return 1;
3363
3364                 } else if ( c->argc == 3 ) {
3365                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3366                                 qm->attr_sets[num].count = 1;
3367                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3368                                         sizeof( AttributeName ) );
3369                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
3370                                 break;
3371
3372                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3373                                 qm->attr_sets[num].count = 1;
3374                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3375                                         sizeof( AttributeName ) );
3376                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3377                                 break;
3378
3379                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
3380                                 break;
3381                         }
3382                         /* else: fallthru */
3383
3384                 } else if ( c->argc == 4 ) {
3385                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
3386                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
3387                         {
3388                                 qm->attr_sets[num].count = 2;
3389                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
3390                                         sizeof( AttributeName ) );
3391                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
3392                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3393                                 break;
3394                         }
3395                         /* else: fallthru */
3396                 }
3397
3398                 if ( c->argc > 2 ) {
3399                         int all_user = 0, all_op = 0;
3400
3401                         qm->attr_sets[num].count = c->argc - 2;
3402                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
3403                                 sizeof( AttributeName ) );
3404                         attr_name = qm->attr_sets[num].attrs;
3405                         for ( i = 2; i < c->argc; i++ ) {
3406                                 attr_name->an_desc = NULL;
3407                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
3408                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3409                                                 "invalid attr #%d \"%s\" in attrlist",
3410                                                 i - 2, c->argv[i] );
3411                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3412                                         ch_free( qm->attr_sets[num].attrs );
3413                                         qm->attr_sets[num].attrs = NULL;
3414                                         qm->attr_sets[num].count = 0;
3415                                         return 1;
3416                                 }
3417                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3418                                         all_user = 1;
3419                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
3420                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3421                                         all_op = 1;
3422                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3423                                 } else {
3424                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
3425                                                 strcpy( c->cr_msg, text );
3426                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3427                                                 ch_free( qm->attr_sets[num].attrs );
3428                                                 qm->attr_sets[num].attrs = NULL;
3429                                                 qm->attr_sets[num].count = 0;
3430                                                 return 1;
3431                                         }
3432                                         attr_name->an_name = attr_name->an_desc->ad_cname;
3433                                 }
3434                                 attr_name->an_oc = NULL;
3435                                 attr_name->an_flags = 0;
3436                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
3437                                         qm->attr_sets[num].flags |= PC_GOT_OC;
3438                                 attr_name++;
3439                                 BER_BVZERO( &attr_name->an_name );
3440                         }
3441
3442                         /* warn if list contains both "*" and "+" */
3443                         if ( i > 4 && all_user && all_op ) {
3444                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3445                                         "warning: attribute list contains \"*\" and \"+\"" );
3446                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3447                         }
3448                 }
3449                 break;
3450         case PC_TEMP:
3451                 if ( cm->numattrsets == 0 ) {
3452                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3453                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3454                         return( 1 );
3455                 }
3456                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
3457                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
3458                                 c->argv[2] );
3459                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3460                         return( 1 );
3461                 }
3462
3463                 if ( i < 0 || i >= cm->numattrsets || 
3464                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
3465                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
3466                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3467                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3468                         return 1;
3469                 }
3470                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
3471                 temp->qmnext = qm->templates;
3472                 qm->templates = temp;
3473                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
3474                 temp->query = temp->query_last = NULL;
3475                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
3476                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3477                                 "unable to parse template ttl=\"%s\"",
3478                                 c->argv[3] );
3479                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3480                         return( 1 );
3481                 }
3482                 temp->ttl = (time_t)t;
3483                 temp->negttl = (time_t)0;
3484                 temp->limitttl = (time_t)0;
3485                 temp->ttr = (time_t)0;
3486                 switch ( c->argc ) {
3487                 case 7:
3488                         if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
3489                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3490                                         "unable to parse template ttr=\"%s\"",
3491                                         c->argv[6] );
3492                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3493                                         return( 1 );
3494                         }
3495                         temp->ttr = (time_t)t;
3496                         /* fallthru */
3497
3498                 case 6:
3499                         if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3500                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3501                                         "unable to parse template sizelimit ttl=\"%s\"",
3502                                         c->argv[5] );
3503                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3504                                         return( 1 );
3505                         }
3506                         temp->limitttl = (time_t)t;
3507                         /* fallthru */
3508
3509                 case 5:
3510                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
3511                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3512                                         "unable to parse template negative ttl=\"%s\"",
3513                                         c->argv[4] );
3514                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3515                                         return( 1 );
3516                         }
3517                         temp->negttl = (time_t)t;
3518                         break;
3519                 }
3520
3521                 temp->no_of_queries = 0;
3522
3523                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3524                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3525                 Debug( pcache_debug, "  query template: %s\n",
3526                                 temp->querystr.bv_val, 0, 0 );
3527                 temp->attr_set_index = i;
3528                 qm->attr_sets[i].flags |= PC_REFERENCED;
3529                 temp->qtnext = qm->attr_sets[i].templates;
3530                 qm->attr_sets[i].templates = temp;
3531                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
3532                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3533                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
3534                                 Debug( pcache_debug, "\t%s\n",
3535                                         attrarray[i].an_name.bv_val, 0, 0 );
3536                 }
3537                 break;
3538         case PC_RESP:
3539                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3540                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3541
3542                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3543                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3544
3545                 } else {
3546                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3547                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3548                         return 1;
3549                 }
3550                 break;
3551         case PC_QUERIES:
3552                 if ( c->value_int <= 0 ) {
3553                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3554                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3555                         return( 1 );
3556                 }
3557                 cm->max_queries = c->value_int;
3558                 break;
3559         case PC_OFFLINE:
3560                 if ( c->value_int )
3561                         cm->cc_paused |= PCACHE_CC_OFFLINE;
3562                 else
3563                         cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3564                 break;
3565         case PC_PRIVATE_DB:
3566                 if ( cm->db.be_private == NULL ) {
3567                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3568                                 "private database must be defined before setting database specific options" );
3569                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3570                         return( 1 );
3571                 }
3572
3573                 if ( cm->db.bd_info->bi_cf_ocs ) {
3574                         ConfigTable     *ct;
3575                         ConfigArgs      c2 = *c;
3576                         char            *argv0 = c->argv[ 0 ];
3577
3578                         c->argv[ 0 ] = &argv0[ STRLENOF( "proxycache-" ) ];
3579
3580                         ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
3581                         if ( ct == NULL ) {
3582                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3583                                         "private database does not recognize specific option '%s'",
3584                                         c->argv[ 0 ] );
3585                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3586                                 rc = 1;
3587
3588                         } else {
3589                                 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
3590                                 c->be = &cm->db;
3591                                 c->bi = c->be->bd_info;
3592
3593                                 rc = config_add_vals( ct, c );
3594
3595                                 c->bi = c2.bi;
3596                                 c->be = c2.be;
3597                                 c->table = c2.table;
3598                         }
3599
3600                         c->argv[ 0 ] = argv0;
3601
3602                 } else if ( cm->db.be_config != NULL ) {
3603                         char    *argv0 = c->argv[ 0 ];
3604
3605                         c->argv[ 0 ] = &argv0[ STRLENOF( "proxycache-" ) ];
3606                         rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
3607                         c->argv[ 0 ] = argv0;
3608
3609                 } else {
3610                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3611                                 "no means to set private database specific options" );
3612                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3613                         return 1;
3614                 }
3615                 break;
3616         default:
3617                 rc = SLAP_CONF_UNKNOWN;
3618                 break;
3619         }
3620
3621         return rc;
3622 }
3623
3624 static int
3625 pcache_db_config(
3626         BackendDB       *be,
3627         const char      *fname,
3628         int             lineno,
3629         int             argc,
3630         char            **argv
3631 )
3632 {
3633         slap_overinst   *on = (slap_overinst *)be->bd_info;
3634         cache_manager*  cm = on->on_bi.bi_private;
3635
3636         /* Something for the cache database? */
3637         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3638                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3639                         argc, argv );
3640         return SLAP_CONF_UNKNOWN;
3641 }
3642
3643 static int
3644 pcache_db_init(
3645         BackendDB *be,
3646         ConfigReply *cr)
3647 {
3648         slap_overinst *on = (slap_overinst *)be->bd_info;
3649         cache_manager *cm;
3650         query_manager *qm;
3651
3652         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3653         on->on_bi.bi_private = cm;
3654
3655         qm = (query_manager*)ch_malloc(sizeof(query_manager));
3656
3657         cm->db = *be;
3658         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3659         cm->db.be_private = NULL;
3660         cm->db.bd_self = &cm->db;
3661         cm->qm = qm;
3662         cm->numattrsets = 0;
3663         cm->num_entries_limit = 5;
3664         cm->num_cached_queries = 0;
3665         cm->max_entries = 0;
3666         cm->cur_entries = 0;
3667         cm->max_queries = 10000;
3668         cm->save_queries = 0;
3669         cm->check_cacheability = 0;
3670         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3671         cm->defer_db_open = 1;
3672         cm->cc_period = 1000;
3673         cm->cc_paused = 0;
3674         cm->cc_arg = NULL;
3675
3676         qm->attr_sets = NULL;
3677         qm->templates = NULL;
3678         qm->lru_top = NULL;
3679         qm->lru_bottom = NULL;
3680
3681         qm->qcfunc = query_containment;
3682         qm->crfunc = cache_replacement;
3683         qm->addfunc = add_query;
3684         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3685
3686         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3687         return 0;
3688 }
3689
3690 static int
3691 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3692 {
3693         assert( op->o_tag == LDAP_REQ_SEARCH );
3694
3695         if ( rs->sr_type == REP_SEARCH ) {
3696                 Attribute       *a;
3697
3698                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3699                 if ( a != NULL ) {
3700                         BerVarray       *valsp;
3701
3702                         assert( a->a_nvals != NULL );
3703
3704                         valsp = op->o_callback->sc_private;
3705                         assert( *valsp == NULL );
3706
3707                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3708                 }
3709         }
3710
3711         return 0;
3712 }
3713
3714 static int
3715 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3716 {
3717         assert( op->o_tag == LDAP_REQ_SEARCH );
3718
3719         if ( rs->sr_type == REP_SEARCH ) {
3720                 int     *countp = (int *)op->o_callback->sc_private;
3721
3722                 (*countp)++;
3723         }
3724
3725         return 0;
3726 }
3727
3728 static int
3729 pcache_db_open2(
3730         slap_overinst *on,
3731         ConfigReply *cr )
3732 {
3733         cache_manager   *cm = on->on_bi.bi_private;
3734         query_manager*  qm = cm->qm;
3735         int rc;
3736
3737         rc = backend_startup_one( &cm->db, cr );
3738         if ( rc == 0 ) {
3739                 cm->defer_db_open = 0;
3740         }
3741
3742         /* There is no runqueue in TOOL mode */
3743         if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
3744                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3745                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3746                         consistency_check, on,
3747                         "pcache_consistency", cm->db.be_suffix[0].bv_val );
3748                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3749
3750                 /* Cached database must have the rootdn */
3751                 if ( BER_BVISNULL( &cm->db.be_rootndn )
3752                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3753                 {
3754                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3755                                 "underlying database of type \"%s\"\n"
3756                                 "    serving naming context \"%s\"\n"
3757                                 "    has no \"rootdn\", required by \"proxycache\".\n",
3758                                 on->on_info->oi_orig->bi_type,
3759                                 cm->db.be_suffix[0].bv_val, 0 );
3760                         return 1;
3761                 }
3762
3763                 if ( cm->save_queries ) {
3764                         void            *thrctx = ldap_pvt_thread_pool_context();
3765                         Connection      conn = { 0 };
3766                         OperationBuffer opbuf;
3767                         Operation       *op;
3768                         slap_callback   cb = { 0 };
3769                         SlapReply       rs = { 0 };
3770                         BerVarray       vals = NULL;
3771                         Filter          f = { 0 }, f2 = { 0 };
3772                         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
3773                         AttributeName   attrs[ 2 ] = {{{ 0 }}};
3774
3775                         connection_fake_init( &conn, &opbuf, thrctx );
3776                         op = &opbuf.ob_op;
3777
3778                         op->o_bd = &cm->db;
3779
3780                         op->o_tag = LDAP_REQ_SEARCH;
3781                         op->o_protocol = LDAP_VERSION3;
3782                         cb.sc_response = pcache_cachedquery_open_cb;
3783                         cb.sc_private = &vals;
3784                         op->o_callback = &cb;
3785                         op->o_time = slap_get_time();
3786                         op->o_do_not_cache = 1;
3787                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
3788
3789                         op->o_dn = cm->db.be_rootdn;
3790                         op->o_ndn = cm->db.be_rootndn;
3791                         op->o_req_dn = cm->db.be_suffix[ 0 ];
3792                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3793
3794                         op->ors_scope = LDAP_SCOPE_BASE;
3795                         op->ors_deref = LDAP_DEREF_NEVER;
3796                         op->ors_slimit = 1;
3797                         op->ors_tlimit = SLAP_NO_LIMIT;
3798                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3799                         f.f_choice = LDAP_FILTER_PRESENT;
3800                         f.f_desc = ad_cachedQueryURL;
3801                         op->ors_filter = &f;
3802                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
3803                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3804                         op->ors_attrs = attrs;
3805                         op->ors_attrsonly = 0;
3806
3807                         rc = op->o_bd->be_search( op, &rs );
3808                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
3809                                 int     i;
3810
3811                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3812                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3813                                                 cm->num_cached_queries++;
3814                                         }
3815                                 }
3816
3817                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3818                         }
3819
3820                         /* count cached entries */
3821                         f.f_choice = LDAP_FILTER_NOT;
3822                         f.f_not = &f2;
3823                         f2.f_choice = LDAP_FILTER_EQUALITY;
3824                         f2.f_ava = &ava;
3825                         f2.f_av_desc = slap_schema.si_ad_objectClass;
3826                         BER_BVSTR( &f2.f_av_value, "glue" );
3827                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3828
3829                         op->ors_slimit = SLAP_NO_LIMIT;
3830                         op->ors_scope = LDAP_SCOPE_SUBTREE;
3831                         op->ors_attrs = slap_anlist_no_attrs;
3832
3833                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
3834                         rs.sr_nentries = 0;
3835                         op->o_callback->sc_private = &rs.sr_nentries;
3836
3837                         rc = op->o_bd->be_search( op, &rs );
3838
3839                         cm->cur_entries = rs.sr_nentries;
3840
3841                         /* ignore errors */
3842                         rc = 0;
3843                 }
3844         }
3845         return rc;
3846 }
3847
3848 static int
3849 pcache_db_open(
3850         BackendDB *be,
3851         ConfigReply *cr )
3852 {
3853         slap_overinst   *on = (slap_overinst *)be->bd_info;
3854         cache_manager   *cm = on->on_bi.bi_private;
3855         query_manager*  qm = cm->qm;
3856         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3857
3858         /* check attr sets */
3859         for ( i = 0; i < cm->numattrsets; i++) {
3860                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3861                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3862                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3863                                 rf++;
3864
3865                         } else {
3866                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3867                         }
3868                         ncf++;
3869
3870                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3871                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3872                         nrf++;
3873                 }
3874         }
3875
3876         if ( ncf || rf || nrf ) {
3877                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3878                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3879                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3880
3881                 if ( rf > 0 ) {
3882                         return 1;
3883                 }
3884         }
3885
3886         /* need to inherit something from the original database... */
3887         cm->db.be_def_limit = be->be_def_limit;
3888         cm->db.be_limits = be->be_limits;
3889         cm->db.be_acl = be->be_acl;
3890         cm->db.be_dfltaccess = be->be_dfltaccess;
3891
3892         if ( SLAP_DBMONITORING( be ) ) {
3893                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3894
3895         } else {
3896                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3897         }
3898
3899         if ( !cm->defer_db_open )
3900                 rc = pcache_db_open2( on, cr );
3901
3902         return rc;
3903 }
3904
3905 static void
3906 pcache_free_qbase( void *v )
3907 {
3908         Qbase *qb = v;
3909         int i;
3910
3911         for (i=0; i<3; i++)
3912                 tavl_free( qb->scopes[i], NULL );
3913         ch_free( qb );
3914 }
3915
3916 static int
3917 pcache_db_close(
3918         BackendDB *be,
3919         ConfigReply *cr
3920 )
3921 {
3922         slap_overinst *on = (slap_overinst *)be->bd_info;
3923         cache_manager *cm = on->on_bi.bi_private;
3924         query_manager *qm = cm->qm;
3925         QueryTemplate *tm;
3926         int i, rc = 0;
3927
3928         if ( cm->save_queries ) {
3929                 CachedQuery     *qc;
3930                 BerVarray       vals = NULL;
3931
3932                 void            *thrctx;
3933                 Connection      conn = { 0 };
3934                 OperationBuffer opbuf;
3935                 Operation       *op;
3936                 slap_callback   cb = { 0 };
3937
3938                 SlapReply       rs = { REP_RESULT };
3939                 Modifications   mod = {{ 0 }};
3940
3941                 thrctx = ldap_pvt_thread_pool_context();
3942
3943                 connection_fake_init( &conn, &opbuf, thrctx );
3944                 op = &opbuf.ob_op;
3945
3946                 if ( qm->templates != NULL ) {
3947                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3948                                 for ( qc = tm->query; qc; qc = qc->next ) {
3949                                         struct berval   bv;
3950
3951                                         if ( query2url( op, qc, &bv, 0 ) == 0 ) {
3952                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3953                                         }
3954                                 }
3955                         }
3956                 }
3957
3958                 op->o_bd = &cm->db;
3959                 op->o_dn = cm->db.be_rootdn;
3960                 op->o_ndn = cm->db.be_rootndn;
3961
3962                 op->o_tag = LDAP_REQ_MODIFY;
3963                 op->o_protocol = LDAP_VERSION3;
3964                 cb.sc_response = slap_null_cb;
3965                 op->o_callback = &cb;
3966                 op->o_time = slap_get_time();
3967                 op->o_do_not_cache = 1;
3968                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3969
3970                 op->o_req_dn = op->o_bd->be_suffix[0];
3971                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3972
3973                 mod.sml_op = LDAP_MOD_REPLACE;
3974                 mod.sml_flags = 0;
3975                 mod.sml_desc = ad_cachedQueryURL;
3976                 mod.sml_type = ad_cachedQueryURL->ad_cname;
3977                 mod.sml_values = vals;
3978                 mod.sml_nvalues = NULL;
3979                 mod.sml_numvals = 1;
3980                 mod.sml_next = NULL;
3981                 Debug( pcache_debug,
3982                         "%sSETTING CACHED QUERY URLS\n",
3983                         vals == NULL ? "RE" : "", 0, 0 );
3984
3985                 op->orm_modlist = &mod;
3986
3987                 op->o_bd->be_modify( op, &rs );
3988
3989                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3990         }
3991
3992         /* cleanup stuff inherited from the original database... */
3993         cm->db.be_limits = NULL;
3994         cm->db.be_acl = NULL;
3995
3996         /* stop the thread ... */
3997         if ( cm->cc_arg ) {
3998                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3999                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4000                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4001                 }
4002                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4003                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4004         }
4005
4006         if ( cm->db.bd_info->bi_db_close ) {
4007                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4008         }
4009         while ( (tm = qm->templates) != NULL ) {
4010                 CachedQuery *qc, *qn;
4011                 qm->templates = tm->qmnext;
4012                 for ( qc = tm->query; qc; qc = qn ) {
4013                         qn = qc->next;
4014                         free_query( qc );
4015                 }
4016                 avl_free( tm->qbase, pcache_free_qbase );
4017                 free( tm->querystr.bv_val );
4018                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4019                 free( tm->t_attrs.attrs );
4020                 free( tm );
4021         }
4022
4023         for ( i=0; i<cm->numattrsets; i++ ) {
4024                 free( qm->attr_sets[i].attrs );
4025         }
4026         free( qm->attr_sets );
4027         qm->attr_sets = NULL;
4028
4029         return rc;
4030 }
4031
4032 static int
4033 pcache_db_destroy(
4034         BackendDB *be,
4035         ConfigReply *cr
4036 )
4037 {
4038         slap_overinst *on = (slap_overinst *)be->bd_info;
4039         cache_manager *cm = on->on_bi.bi_private;
4040         query_manager *qm = cm->qm;
4041
4042         if ( cm->db.be_private != NULL ) {
4043                 backend_stopdown_one( &cm->db );
4044         }
4045
4046         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4047         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4048         free( qm );
4049         free( cm );
4050
4051         return 0;
4052 }
4053
4054 #ifdef PCACHE_CONTROL_PRIVDB
4055 /*
4056         Control ::= SEQUENCE {
4057              controlType             LDAPOID,
4058              criticality             BOOLEAN DEFAULT FALSE,
4059              controlValue            OCTET STRING OPTIONAL }
4060
4061         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4062
4063  * criticality must be TRUE; controlValue must be absent.
4064  */
4065 static int
4066 parse_privdb_ctrl(
4067         Operation       *op,
4068         SlapReply       *rs,
4069         LDAPControl     *ctrl )
4070 {
4071         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4072                 rs->sr_text = "privateDB control specified multiple times";
4073                 return LDAP_PROTOCOL_ERROR;
4074         }
4075
4076         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4077                 rs->sr_text = "privateDB control value not absent";
4078                 return LDAP_PROTOCOL_ERROR;
4079         }
4080
4081         if ( !ctrl->ldctl_iscritical ) {
4082                 rs->sr_text = "privateDB control criticality required";
4083                 return LDAP_PROTOCOL_ERROR;
4084         }
4085
4086         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4087
4088         return LDAP_SUCCESS;
4089 }
4090
4091 static char *extops[] = {
4092         LDAP_EXOP_MODIFY_PASSWD,
4093         NULL
4094 };
4095 #endif /* PCACHE_CONTROL_PRIVDB */
4096
4097 #ifdef PCACHE_EXOP_QUERY_DELETE
4098 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4099
4100 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4101 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4102 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
4103
4104 /*
4105         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
4106              requestName      [0] LDAPOID,
4107              requestValue     [1] OCTET STRING OPTIONAL }
4108
4109         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
4110
4111         requestValue ::= SEQUENCE { CHOICE {
4112                   baseDN           [0] LDAPDN
4113                   entryDN          [1] LDAPDN },
4114              queryID          [2] OCTET STRING (SIZE(16))
4115                   -- constrained to UUID }
4116
4117  * Either baseDN or entryDN must be present, to allow database selection.
4118  *
4119  * 1. if baseDN and queryID are present, then the query corresponding
4120  *    to queryID is deleted;
4121  * 2. if baseDN is present and queryID is absent, then all queries
4122  *    are deleted;
4123  * 3. if entryDN is present and queryID is absent, then all queries
4124  *    corresponding to the queryID values present in entryDN are deleted;
4125  * 4. if entryDN and queryID are present, then all queries
4126  *    corresponding to the queryID values present in entryDN are deleted,
4127  *    but only if the value of queryID is contained in the entry;
4128  *
4129  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
4130  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
4131  * or by removing the database files.
4132
4133         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
4134              COMPONENTS OF LDAPResult,
4135              responseName     [10] LDAPOID OPTIONAL,
4136              responseValue    [11] OCTET STRING OPTIONAL }
4137
4138  * responseName and responseValue must be absent.
4139  */
4140
4141 /*
4142  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
4143  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
4144  * - if ndn != NULL, it is set to the normalized DN in the request
4145  *   corresponding to either the baseDN or the entryDN, according
4146  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
4147  *   be freed by the caller.
4148  * - if uuid != NULL, it is set to point to the normalized UUID;
4149  *   memory is malloc'ed on the Operation's slab, and must
4150  *   be freed by the caller.
4151  */
4152 static int
4153 pcache_parse_query_delete(
4154         struct berval   *in,
4155         ber_tag_t       *tagp,
4156         struct berval   *ndn,
4157         struct berval   *uuid,
4158         const char      **text,
4159         void            *ctx )
4160 {
4161         int                     rc = LDAP_SUCCESS;
4162         ber_tag_t               tag;
4163         ber_len_t               len = -1;
4164         BerElementBuffer        berbuf;
4165         BerElement              *ber = (BerElement *)&berbuf;
4166         struct berval           reqdata = BER_BVNULL;
4167
4168         *text = NULL;
4169
4170         if ( ndn ) {
4171                 BER_BVZERO( ndn );
4172         }
4173
4174         if ( uuid ) {
4175                 BER_BVZERO( uuid );
4176         }
4177
4178         if ( in == NULL || in->bv_len == 0 ) {
4179                 *text = "empty request data field in queryDelete exop";
4180                 return LDAP_PROTOCOL_ERROR;
4181         }
4182
4183         ber_dupbv_x( &reqdata, in, ctx );
4184
4185         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
4186         ber_init2( ber, &reqdata, 0 );
4187
4188         tag = ber_scanf( ber, "{" /*}*/ );
4189
4190         if ( tag == LBER_ERROR ) {
4191                 Debug( LDAP_DEBUG_TRACE,
4192                         "pcache_parse_query_delete: decoding error.\n",
4193                         0, 0, 0 );
4194                 goto decoding_error;
4195         }
4196
4197         tag = ber_peek_tag( ber, &len );
4198         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
4199                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
4200         {
4201                 *tagp = tag;
4202
4203                 if ( ndn != NULL ) {
4204                         struct berval   dn;
4205
4206                         tag = ber_scanf( ber, "m", &dn );
4207                         if ( tag == LBER_ERROR ) {
4208                                 Debug( LDAP_DEBUG_TRACE,
4209                                         "pcache_parse_query_delete: DN parse failed.\n",
4210                                         0, 0, 0 );
4211                                 goto decoding_error;
4212                         }
4213
4214                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
4215                         if ( rc != LDAP_SUCCESS ) {
4216                                 *text = "invalid DN in queryDelete exop request data";
4217                                 goto done;
4218                         }
4219
4220                 } else {
4221                         tag = ber_scanf( ber, "x" /* "m" */ );
4222                         if ( tag == LBER_DEFAULT ) {
4223                                 goto decoding_error;
4224                         }
4225                 }
4226
4227                 tag = ber_peek_tag( ber, &len );
4228         }
4229
4230         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
4231                 if ( uuid != NULL ) {
4232                         struct berval   bv;
4233                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
4234
4235                         tag = ber_scanf( ber, "m", &bv );
4236                         if ( tag == LBER_ERROR ) {
4237                                 Debug( LDAP_DEBUG_TRACE,
4238                                         "pcache_parse_query_delete: UUID parse failed.\n",
4239                                         0, 0, 0 );
4240                                 goto decoding_error;
4241                         }
4242
4243                         if ( bv.bv_len != 16 ) {
4244                                 Debug( LDAP_DEBUG_TRACE,
4245                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
4246                                         (unsigned long)bv.bv_len, 0, 0 );
4247                                 goto decoding_error;
4248                         }
4249
4250                         rc = lutil_uuidstr_from_normalized(
4251                                 bv.bv_val, bv.bv_len,
4252                                 uuidbuf, sizeof( uuidbuf ) );
4253                         if ( rc == -1 ) {
4254                                 goto decoding_error;
4255                         }
4256                         ber_str2bv( uuidbuf, rc, 1, uuid );
4257                         rc = LDAP_SUCCESS;
4258
4259                 } else {
4260                         tag = ber_skip_tag( ber, &len );
4261                         if ( tag == LBER_DEFAULT ) {
4262                                 goto decoding_error;
4263                         }
4264
4265                         if ( len != 16 ) {
4266                                 Debug( LDAP_DEBUG_TRACE,
4267                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
4268                                         (unsigned long)len, 0, 0 );
4269                                 goto decoding_error;
4270                         }
4271                 }
4272
4273                 tag = ber_peek_tag( ber, &len );
4274         }
4275
4276         if ( tag != LBER_DEFAULT || len != 0 ) {
4277 decoding_error:;
4278                 Debug( LDAP_DEBUG_TRACE,
4279                         "pcache_parse_query_delete: decoding error\n",
4280                         0, 0, 0 );
4281                 rc = LDAP_PROTOCOL_ERROR;
4282                 *text = "queryDelete data decoding error";
4283
4284 done:;
4285                 if ( ndn && !BER_BVISNULL( ndn ) ) {
4286                         slap_sl_free( ndn->bv_val, ctx );
4287                         BER_BVZERO( ndn );
4288                 }
4289
4290                 if ( uuid && !BER_BVISNULL( uuid ) ) {
4291                         slap_sl_free( uuid->bv_val, ctx );
4292                         BER_BVZERO( uuid );
4293                 }
4294         }
4295
4296         if ( !BER_BVISNULL( &reqdata ) ) {
4297                 ber_memfree_x( reqdata.bv_val, ctx );
4298         }
4299
4300         return rc;
4301 }
4302
4303 static int
4304 pcache_exop_query_delete(
4305         Operation       *op,
4306         SlapReply       *rs )
4307 {
4308         BackendDB       *bd = op->o_bd;
4309
4310         struct berval   uuid = BER_BVNULL,
4311                         *uuidp = NULL;
4312         char            buf[ SLAP_TEXT_BUFLEN ];
4313         unsigned        len;
4314         ber_tag_t       tag = LBER_DEFAULT;
4315
4316         if ( LogTest( LDAP_DEBUG_STATS ) ) {
4317                 uuidp = &uuid;
4318         }
4319
4320         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
4321                 &tag, &op->o_req_ndn, uuidp,
4322                 &rs->sr_text, op->o_tmpmemctx );
4323         if ( rs->sr_err != LDAP_SUCCESS ) {
4324                 return rs->sr_err;
4325         }
4326
4327         if ( LogTest( LDAP_DEBUG_STATS ) ) {
4328                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
4329                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
4330
4331                 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
4332                         snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
4333                 }
4334
4335                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
4336                         op->o_log_prefix, buf, 0 );
4337         }
4338         op->o_req_dn = op->o_req_ndn;
4339
4340         op->o_bd = select_backend( &op->o_req_ndn, 0 );
4341         rs->sr_err = backend_check_restrictions( op, rs,
4342                 (struct berval *)&pcache_exop_QUERY_DELETE );
4343         if ( rs->sr_err != LDAP_SUCCESS ) {
4344                 goto done;
4345         }
4346
4347         if ( op->o_bd->be_extended == NULL ) {
4348                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
4349                         "backend does not support extended operations" );
4350                 goto done;
4351         }
4352
4353         op->o_bd->be_extended( op, rs );
4354
4355 done:;
4356         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
4357                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
4358                 BER_BVZERO( &op->o_req_ndn );
4359                 BER_BVZERO( &op->o_req_dn );
4360         }
4361
4362         if ( !BER_BVISNULL( &uuid ) ) {
4363                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
4364         }
4365
4366         op->o_bd = bd;
4367
4368         return rs->sr_err;
4369 }
4370
4371 static int
4372 pcache_op_extended( Operation *op, SlapReply *rs )
4373 {
4374         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
4375         cache_manager   *cm = on->on_bi.bi_private;
4376
4377 #ifdef PCACHE_CONTROL_PRIVDB
4378         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
4379                 return pcache_op_privdb( op, rs );
4380         }
4381 #endif /* PCACHE_CONTROL_PRIVDB */
4382
4383         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
4384                 struct berval   uuid = BER_BVNULL;
4385                 ber_tag_t       tag = LBER_DEFAULT;
4386
4387                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
4388                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
4389                 assert( rs->sr_err == LDAP_SUCCESS );
4390
4391                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
4392                         /* remove all queries related to the selected entry */
4393                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
4394                                 cm, &op->o_req_ndn, &uuid );
4395
4396                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
4397                         if ( !BER_BVISNULL( &uuid ) ) {
4398                                 /* remove the selected query */
4399                                 rs->sr_err = pcache_remove_query_from_cache( op,
4400                                         cm, &uuid );
4401
4402                         } else {
4403                                 /* TODO: remove all queries */
4404                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4405                                 rs->sr_text = "deletion of all queries not implemented";
4406                         }
4407                 }
4408
4409                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
4410         }
4411
4412         return rs->sr_err;
4413 }
4414 #endif /* PCACHE_EXOP_QUERY_DELETE */
4415
4416 static slap_overinst pcache;
4417
4418 static char *obsolete_names[] = {
4419         "proxycache",
4420         NULL
4421 };
4422
4423 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4424 static
4425 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
4426 int
4427 pcache_initialize()
4428 {
4429         int i, code;
4430         struct berval debugbv = BER_BVC("pcache");
4431
4432         code = slap_loglevel_get( &debugbv, &pcache_debug );
4433         if ( code ) {
4434                 return code;
4435         }
4436
4437 #ifdef PCACHE_CONTROL_PRIVDB
4438         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
4439                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
4440                 parse_privdb_ctrl, &privDB_cid );
4441         if ( code != LDAP_SUCCESS ) {
4442                 Debug( LDAP_DEBUG_ANY,
4443                         "pcache_initialize: failed to register control %s (%d)\n",
4444                         PCACHE_CONTROL_PRIVDB, code, 0 );
4445                 return code;
4446         }
4447 #endif /* PCACHE_CONTROL_PRIVDB */
4448
4449 #ifdef PCACHE_EXOP_QUERY_DELETE
4450         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
4451                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
4452                 0 );
4453         if ( code != LDAP_SUCCESS ) {
4454                 Debug( LDAP_DEBUG_ANY,
4455                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
4456                         code, 0, 0 );
4457                 return code;
4458         }
4459 #endif /* PCACHE_EXOP_QUERY_DELETE */
4460
4461         for ( i = 0; as[i].desc != NULL; i++ ) {
4462                 code = register_at( as[i].desc, as[i].adp, 0 );
4463                 if ( code ) {
4464                         Debug( LDAP_DEBUG_ANY,
4465                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
4466                         return code;
4467                 }
4468                 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
4469         }
4470
4471         pcache.on_bi.bi_type = "pcache";
4472         pcache.on_bi.bi_obsolete_names = obsolete_names;
4473         pcache.on_bi.bi_db_init = pcache_db_init;
4474         pcache.on_bi.bi_db_config = pcache_db_config;
4475         pcache.on_bi.bi_db_open = pcache_db_open;
4476         pcache.on_bi.bi_db_close = pcache_db_close;
4477         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
4478
4479         pcache.on_bi.bi_op_search = pcache_op_search;
4480 #ifdef PCACHE_CONTROL_PRIVDB
4481         pcache.on_bi.bi_op_bind = pcache_op_privdb;
4482         pcache.on_bi.bi_op_compare = pcache_op_privdb;
4483         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
4484         pcache.on_bi.bi_op_modify = pcache_op_privdb;
4485         pcache.on_bi.bi_op_add = pcache_op_privdb;
4486         pcache.on_bi.bi_op_delete = pcache_op_privdb;
4487 #endif /* PCACHE_CONTROL_PRIVDB */
4488 #ifdef PCACHE_EXOP_QUERY_DELETE
4489         pcache.on_bi.bi_extended = pcache_op_extended;
4490 #elif defined( PCACHE_CONTROL_PRIVDB )
4491         pcache.on_bi.bi_extended = pcache_op_privdb;
4492 #endif
4493
4494         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
4495
4496         pcache.on_bi.bi_cf_ocs = pcocs;
4497
4498         code = config_register_schema( pccfg, pcocs );
4499         if ( code ) return code;
4500
4501         return overlay_register( &pcache );
4502 }
4503
4504 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4505 int init_module(int argc, char *argv[]) {
4506         return pcache_initialize();
4507 }
4508 #endif
4509
4510 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */