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