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