]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
also log cookie parsing
[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         int len, ret;
1486
1487         switch ( f->f_choice ) {
1488         case LDAP_FILTER_EQUALITY:
1489                 ad = f->f_av_desc;
1490                 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1491                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1492                 assert( ret == len );
1493                 fstr->bv_len += len;
1494                 break;
1495
1496         case LDAP_FILTER_GE:
1497                 ad = f->f_av_desc;
1498                 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1499                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1500                 assert( ret == len );
1501                 fstr->bv_len += len;
1502                 break;
1503
1504         case LDAP_FILTER_LE:
1505                 ad = f->f_av_desc;
1506                 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1507                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1508                 assert( ret == len );
1509                 fstr->bv_len += len;
1510                 break;
1511
1512         case LDAP_FILTER_APPROX:
1513                 ad = f->f_av_desc;
1514                 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1515                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1516                 assert( ret == len );
1517                 fstr->bv_len += len;
1518                 break;
1519
1520         case LDAP_FILTER_SUBSTRINGS:
1521                 ad = f->f_sub_desc;
1522                 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1523                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1524                 assert( ret == len );
1525                 fstr->bv_len += len;
1526                 break;
1527
1528         case LDAP_FILTER_PRESENT:
1529                 ad = f->f_desc;
1530                 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1531                 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1532                 assert( ret == len );
1533                 fstr->bv_len += len;
1534                 break;
1535
1536         case LDAP_FILTER_AND:
1537         case LDAP_FILTER_OR:
1538         case LDAP_FILTER_NOT: {
1539                 int rc = 0;
1540                 fstr->bv_val[fstr->bv_len++] = '(';
1541                 switch ( f->f_choice ) {
1542                 case LDAP_FILTER_AND:
1543                         fstr->bv_val[fstr->bv_len] = '&';
1544                         break;
1545                 case LDAP_FILTER_OR:
1546                         fstr->bv_val[fstr->bv_len] = '|';
1547                         break;
1548                 case LDAP_FILTER_NOT:
1549                         fstr->bv_val[fstr->bv_len] = '!';
1550                         break;
1551                 }
1552                 fstr->bv_len++;
1553
1554                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1555                         rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1556                                 filter_got_oc );
1557                         if ( rc ) break;
1558                 }
1559                 fstr->bv_val[fstr->bv_len++] = ')';
1560                 fstr->bv_val[fstr->bv_len] = '\0';
1561
1562                 return rc;
1563                 }
1564
1565         default:
1566                 /* a filter should at least have room for "()",
1567                  * an "=" and for a 1-char attr */
1568                 strcpy( fstr->bv_val, "(?=)" );
1569                 fstr->bv_len += STRLENOF("(?=)");
1570                 return -1;
1571         }
1572
1573         if ( filter_attrs != NULL ) {
1574                 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1575                                 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1576
1577                 (*filter_attrs)[*filter_cnt].an_desc = ad;
1578                 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1579                 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1580                 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1581                 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1582                 (*filter_cnt)++;
1583                 if ( ad == slap_schema.si_ad_objectClass )
1584                         *filter_got_oc = 1;
1585         }
1586
1587         return 0;
1588 }
1589
1590 struct search_info {
1591         slap_overinst *on;
1592         Query query;
1593         QueryTemplate *qtemp;
1594         AttributeName*  save_attrs;     /* original attributes, saved for response */
1595         int max;
1596         int over;
1597         int count;
1598         int slimit;
1599         int slimit_exceeded;
1600         pc_caching_reason_t caching_reason;
1601         Entry *head, *tail;
1602 };
1603
1604 static void
1605 remove_query_and_data(
1606         Operation       *op,
1607         SlapReply       *rs,
1608         cache_manager   *cm,
1609         struct berval   *uuid )
1610 {
1611         query_manager*          qm = cm->qm;
1612
1613         qm->crfunc( qm, uuid );
1614         if ( !BER_BVISNULL( uuid ) ) {
1615                 int     return_val;
1616
1617                 Debug( pcache_debug,
1618                         "Removing query UUID %s\n",
1619                         uuid->bv_val, 0, 0 );
1620                 return_val = remove_query_data( op, rs, uuid );
1621                 Debug( pcache_debug,
1622                         "QUERY REMOVED, SIZE=%d\n",
1623                         return_val, 0, 0);
1624                 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1625                 cm->cur_entries -= return_val;
1626                 cm->num_cached_queries--;
1627                 Debug( pcache_debug,
1628                         "STORED QUERIES = %lu\n",
1629                         cm->num_cached_queries, 0, 0 );
1630                 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1631                 Debug( pcache_debug,
1632                         "QUERY REMOVED, CACHE ="
1633                         "%d entries\n",
1634                         cm->cur_entries, 0, 0 );
1635         }
1636 }
1637
1638 /*
1639  * Callback used to fetch queryId values based on entryUUID;
1640  * used by pcache_remove_entries_from_cache()
1641  */
1642 static int
1643 fetch_queryId_cb( Operation *op, SlapReply *rs )
1644 {
1645         int             rc = 0;
1646
1647         /* only care about searchEntry responses */
1648         if ( rs->sr_type != REP_SEARCH ) {
1649                 return 0;
1650         }
1651
1652         /* allow only one response per entryUUID */
1653         if ( op->o_callback->sc_private != NULL ) {
1654                 rc = 1;
1655
1656         } else {
1657                 Attribute       *a;
1658
1659                 /* copy all queryId values into callback's private data */
1660                 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1661                 if ( a != NULL ) {
1662                         BerVarray       vals = NULL;
1663
1664                         ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1665                         op->o_callback->sc_private = (void *)vals;
1666                 }
1667         }
1668
1669         /* clear entry if required */
1670         if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1671                 entry_free( rs->sr_entry );
1672                 rs->sr_entry = NULL;
1673                 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1674         }
1675
1676         return rc;
1677 }
1678
1679 /*
1680  * Call that allows to remove a set of entries from the cache,
1681  * by forcing the removal of all the related queries.
1682  */
1683 int
1684 pcache_remove_entries_from_cache(
1685         Operation       *op,
1686         cache_manager   *cm,
1687         BerVarray       entryUUIDs )
1688 {
1689         Connection      conn = { 0 };
1690         OperationBuffer opbuf;
1691         Operation       op2;
1692         slap_callback   sc = { 0 };
1693         SlapReply       rs = { REP_RESULT };
1694         Filter          f = { 0 };
1695         char            filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1696         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1697         AttributeName   attrs[ 2 ] = { 0 };
1698         int             s, rc;
1699
1700         if ( op == NULL ) {
1701                 void    *thrctx = ldap_pvt_thread_pool_context();
1702
1703                 connection_fake_init( &conn, &opbuf, thrctx );
1704                 op = &opbuf.ob_op;
1705
1706         } else {
1707                 op2 = *op;
1708                 op = &op2;
1709         }
1710
1711         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1712         op->ors_scope = LDAP_SCOPE_SUBTREE;
1713         op->ors_deref = LDAP_DEREF_NEVER;
1714         f.f_choice = LDAP_FILTER_EQUALITY;
1715         f.f_ava = &ava;
1716         ava.aa_desc = slap_schema.si_ad_entryUUID;
1717         op->ors_filter = &f;
1718         op->ors_slimit = 1;
1719         op->ors_tlimit = SLAP_NO_LIMIT;
1720         attrs[ 0 ].an_desc = ad_queryId;
1721         attrs[ 0 ].an_name = ad_queryId->ad_cname;
1722         op->ors_attrs = attrs;
1723         op->ors_attrsonly = 0;
1724
1725         op->o_req_dn = cm->db.be_suffix[ 0 ];
1726         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1727
1728         op->o_tag = LDAP_REQ_SEARCH;
1729         op->o_protocol = LDAP_VERSION3;
1730         op->o_managedsait = SLAP_CONTROL_CRITICAL;
1731         op->o_bd = &cm->db;
1732         op->o_dn = op->o_bd->be_rootdn;
1733         op->o_ndn = op->o_bd->be_rootndn;
1734         sc.sc_response = fetch_queryId_cb;
1735         op->o_callback = &sc;
1736
1737         for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1738                 BerVarray       vals = NULL;
1739
1740                 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1741                         "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1742                 op->ors_filterstr.bv_val = filtbuf;
1743                 ava.aa_value = entryUUIDs[ s ];
1744
1745                 rc = op->o_bd->be_search( op, &rs );
1746                 if ( rc != LDAP_SUCCESS ) {
1747                         continue;
1748                 }
1749
1750                 vals = (BerVarray)op->o_callback->sc_private;
1751                 if ( vals != NULL ) {
1752                         int             i;
1753
1754                         for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1755                                 struct berval   val = vals[ i ];
1756
1757                                 remove_query_and_data( op, &rs, cm, &val );
1758
1759                                 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1760                                         ch_free( val.bv_val );
1761                                 }
1762                         }
1763
1764                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
1765                         op->o_callback->sc_private = NULL;
1766                 }
1767         }
1768
1769         return 0;
1770 }
1771
1772 /*
1773  * Call that allows to remove a query from the cache.
1774  */
1775 int
1776 pcache_remove_query_from_cache(
1777         Operation       *op,
1778         cache_manager   *cm,
1779         struct berval   *queryid )
1780 {
1781         Operation       op2 = *op;
1782         SlapReply       rs2 = { 0 };
1783
1784         op2.o_bd = &cm->db;
1785
1786         /* remove the selected query */
1787         remove_query_and_data( &op2, &rs2, cm, queryid );
1788
1789         return LDAP_SUCCESS;
1790 }
1791
1792 /*
1793  * Call that allows to remove a set of queries related to an entry 
1794  * from the cache; if queryid is not null, the entry must belong to
1795  * the query indicated by queryid.
1796  */
1797 int
1798 pcache_remove_entry_queries_from_cache(
1799         Operation       *op,
1800         cache_manager   *cm,
1801         struct berval   *ndn,
1802         struct berval   *queryid )
1803 {
1804         Connection              conn = { 0 };
1805         OperationBuffer         opbuf;
1806         Operation               op2;
1807         slap_callback           sc = { 0 };
1808         SlapReply               rs = { REP_RESULT };
1809         Filter                  f = { 0 };
1810         char                    filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1811         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
1812         AttributeName           attrs[ 2 ] = { 0 };
1813         int                     rc;
1814
1815         BerVarray               vals = NULL;
1816
1817         if ( op == NULL ) {
1818                 void    *thrctx = ldap_pvt_thread_pool_context();
1819
1820                 connection_fake_init( &conn, &opbuf, thrctx );
1821                 op = &opbuf.ob_op;
1822
1823         } else {
1824                 op2 = *op;
1825                 op = &op2;
1826         }
1827
1828         memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1829         op->ors_scope = LDAP_SCOPE_BASE;
1830         op->ors_deref = LDAP_DEREF_NEVER;
1831         if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1832                 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1833                 f.f_choice = LDAP_FILTER_PRESENT;
1834                 f.f_desc = slap_schema.si_ad_objectClass;
1835
1836         } else {
1837                 op->ors_filterstr.bv_len = snprintf( filter_str,
1838                         sizeof( filter_str ), "(%s=%s)",
1839                         ad_queryId->ad_cname.bv_val, queryid->bv_val );
1840                 f.f_choice = LDAP_FILTER_EQUALITY;
1841                 f.f_ava = &ava;
1842                 f.f_av_desc = ad_queryId;
1843                 f.f_av_value = *queryid;
1844         }
1845         op->ors_filter = &f;
1846         op->ors_slimit = 1;
1847         op->ors_tlimit = SLAP_NO_LIMIT;
1848         attrs[ 0 ].an_desc = ad_queryId;
1849         attrs[ 0 ].an_name = ad_queryId->ad_cname;
1850         op->ors_attrs = attrs;
1851         op->ors_attrsonly = 0;
1852
1853         op->o_req_dn = *ndn;
1854         op->o_req_ndn = *ndn;
1855
1856         op->o_tag = LDAP_REQ_SEARCH;
1857         op->o_protocol = LDAP_VERSION3;
1858         op->o_managedsait = SLAP_CONTROL_CRITICAL;
1859         op->o_bd = &cm->db;
1860         op->o_dn = op->o_bd->be_rootdn;
1861         op->o_ndn = op->o_bd->be_rootndn;
1862         sc.sc_response = fetch_queryId_cb;
1863         op->o_callback = &sc;
1864
1865         rc = op->o_bd->be_search( op, &rs );
1866         if ( rc != LDAP_SUCCESS ) {
1867                 return rc;
1868         }
1869
1870         vals = (BerVarray)op->o_callback->sc_private;
1871         if ( vals != NULL ) {
1872                 int             i;
1873
1874                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1875                         struct berval   val = vals[ i ];
1876
1877                         remove_query_and_data( op, &rs, cm, &val );
1878
1879                         if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1880                                 ch_free( val.bv_val );
1881                         }
1882                 }
1883
1884                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1885         }
1886
1887         return LDAP_SUCCESS;
1888 }
1889
1890 static int
1891 cache_entries(
1892         Operation       *op,
1893         SlapReply       *rs,
1894         struct berval *query_uuid )
1895 {
1896         struct search_info *si = op->o_callback->sc_private;
1897         slap_overinst *on = si->on;
1898         cache_manager *cm = on->on_bi.bi_private;
1899         int             return_val = 0;
1900         Entry           *e;
1901         struct berval   crp_uuid;
1902         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1903         Operation op_tmp = *op;
1904
1905         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1906         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1907
1908         op_tmp.o_bd = &cm->db;
1909         op_tmp.o_dn = cm->db.be_rootdn;
1910         op_tmp.o_ndn = cm->db.be_rootndn;
1911
1912         Debug( pcache_debug, "UUID for query being added = %s\n",
1913                         uuidbuf, 0, 0 );
1914
1915         for ( e=si->head; e; e=si->head ) {
1916                 si->head = e->e_private;
1917                 e->e_private = NULL;
1918                 while ( cm->cur_entries > (cm->max_entries) ) {
1919                         BER_BVZERO( &crp_uuid );
1920                         remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1921                 }
1922
1923                 return_val = merge_entry(&op_tmp, e, query_uuid);
1924                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1925                 cm->cur_entries += return_val;
1926                 Debug( pcache_debug,
1927                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1928                         cm->cur_entries, 0, 0 );
1929                 return_val = 0;
1930                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1931         }
1932
1933         return return_val;
1934 }
1935
1936 static int
1937 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1938         slap_callback   *cb = op->o_callback;
1939         struct search_info *si = cb->sc_private;
1940         slap_overinst *on = si->on;
1941         cache_manager *cm = on->on_bi.bi_private;
1942         query_manager*          qm = cm->qm;
1943
1944         if ( rs->sr_type == REP_SEARCH ) {
1945                 Entry *e;
1946
1947                 /* don't return more entries than requested by the client */
1948                 if ( si->slimit && rs->sr_nentries >= si->slimit ) {
1949                         si->slimit_exceeded = 1;
1950                 }
1951
1952                 /* If we haven't exceeded the limit for this query,
1953                  * build a chain of answers to store. If we hit the
1954                  * limit, empty the chain and ignore the rest.
1955                  */
1956                 if ( !si->over ) {
1957                         if ( si->count < si->max ) {
1958                                 si->count++;
1959                                 e = entry_dup( rs->sr_entry );
1960                                 if ( !si->head ) si->head = e;
1961                                 if ( si->tail ) si->tail->e_private = e;
1962                                 si->tail = e;
1963
1964                         } else {
1965                                 si->over = 1;
1966                                 si->count = 0;
1967                                 for (;si->head; si->head=e) {
1968                                         e = si->head->e_private;
1969                                         si->head->e_private = NULL;
1970                                         entry_free(si->head);
1971                                 }
1972                                 si->tail = NULL;
1973                         }
1974                 }
1975
1976         }
1977
1978         if ( rs->sr_type == REP_RESULT || 
1979                 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
1980         {
1981                 if ( si->save_attrs != NULL ) {
1982                         rs->sr_attrs = si->save_attrs;
1983                         op->ors_attrs = si->save_attrs;
1984                 }
1985                 if ( op->o_abandon || rs->sr_err == SLAPD_ABANDON ) {
1986                         filter_free( si->query.filter );
1987                         if ( si->count ) {
1988                                 /* duplicate query, free it */
1989                                 Entry *e;
1990                                 for (;si->head; si->head=e) {
1991                                         e = si->head->e_private;
1992                                         si->head->e_private = NULL;
1993                                         entry_free(si->head);
1994                                 }
1995                         }
1996                         op->o_callback = op->o_callback->sc_next;
1997                         op->o_tmpfree( cb, op->o_tmpmemctx );
1998                 } else if ( si->caching_reason != PC_IGNORE ) {
1999                         CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2000                                 si->qtemp, si->caching_reason, 1 );
2001
2002                         if ( qc != NULL ) {
2003                                 switch ( si->caching_reason ) {
2004                                 case PC_POSITIVE:
2005                                         cache_entries( op, rs, &qc->q_uuid );
2006                                         break;
2007
2008                                 case PC_SIZELIMIT:
2009                                         qc->q_sizelimit = rs->sr_nentries;
2010                                         break;
2011                                 }
2012                                 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2013                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2014                                 cm->num_cached_queries++;
2015                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2016                                                 cm->num_cached_queries, 0, 0 );
2017                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2018
2019                                 /* If the consistency checker suspended itself,
2020                                  * wake it back up
2021                                  */
2022                                 if ( cm->cc_paused ) {
2023                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2024                                         if ( cm->cc_paused ) {
2025                                                 cm->cc_paused = 0;
2026                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2027                                         }
2028                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2029                                 }
2030
2031                         } else if ( si->count ) {
2032                                 /* duplicate query, free it */
2033                                 Entry *e;
2034                                 for (;si->head; si->head=e) {
2035                                         e = si->head->e_private;
2036                                         si->head->e_private = NULL;
2037                                         entry_free(si->head);
2038                                 }
2039                         }
2040
2041                 } else {
2042                         filter_free( si->query.filter );
2043                 }
2044         }
2045
2046         return SLAP_CB_CONTINUE;
2047 }
2048
2049 static int
2050 pcache_response(
2051         Operation       *op,
2052         SlapReply       *rs )
2053 {
2054         struct search_info *si = op->o_callback->sc_private;
2055
2056         if ( si->save_attrs != NULL ) {
2057                 rs->sr_attrs = si->save_attrs;
2058                 op->ors_attrs = si->save_attrs;
2059         }
2060
2061         if ( rs->sr_type == REP_SEARCH ) {
2062                 /* don't return more entries than requested by the client */
2063                 if ( si->slimit_exceeded ) {
2064                         return 0;
2065                 }
2066
2067         } else if ( rs->sr_type == REP_RESULT ) {
2068
2069                 if ( si->count ) {
2070                         if ( rs->sr_err == LDAP_SUCCESS ) {
2071                                 si->caching_reason = PC_POSITIVE;
2072
2073                         } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2074                                 && si->qtemp->limitttl )
2075                         {
2076                                 si->caching_reason = PC_SIZELIMIT;
2077                         }
2078
2079                 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2080                                 rs->sr_err == LDAP_SUCCESS )
2081                 {
2082                         si->caching_reason = PC_NEGATIVE;
2083                 }
2084
2085
2086                 if ( si->slimit_exceeded ) {
2087                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2088                 }
2089         }
2090
2091         return SLAP_CB_CONTINUE;
2092 }
2093
2094 static int
2095 add_filter_attrs(
2096         Operation *op,
2097         AttributeName** new_attrs,
2098         struct attr_set *attrs,
2099         AttributeName* filter_attrs,
2100         int fattr_cnt,
2101         int fattr_got_oc)
2102 {
2103         int alluser = 0;
2104         int allop = 0;
2105         int i, j;
2106         int count;
2107         int addoc = 0;
2108
2109         /* duplicate attrs */
2110         count = attrs->count + fattr_cnt;
2111         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2112                 addoc = 1;
2113                 count++;
2114         }
2115
2116         *new_attrs = (AttributeName*)ch_calloc( count + 1,
2117                 sizeof(AttributeName) );
2118         for (i=0; i<attrs->count; i++) {
2119                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2120                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2121         }
2122         BER_BVZERO( &(*new_attrs)[i].an_name );
2123         alluser = an_find(*new_attrs, &AllUser);
2124         allop = an_find(*new_attrs, &AllOper);
2125
2126         j = i;
2127         for ( i=0; i<fattr_cnt; i++ ) {
2128                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2129                         continue;
2130                 }
2131                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2132                         if ( allop ) {
2133                                 continue;
2134                         }
2135                 } else if ( alluser ) {
2136                         continue;
2137                 }
2138                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2139                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2140                 (*new_attrs)[j].an_oc = NULL;
2141                 (*new_attrs)[j].an_oc_exclude = 0;
2142                 j++;
2143         }
2144         if ( addoc ) {
2145                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2146                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2147                 (*new_attrs)[j].an_oc = NULL;
2148                 (*new_attrs)[j].an_oc_exclude = 0;
2149                 j++;
2150         }
2151         BER_BVZERO( &(*new_attrs)[j].an_name );
2152
2153         return count;
2154 }
2155
2156 /* NOTE: this is a quick workaround to let pcache minimally interact
2157  * with pagedResults.  A more articulated solutions would be to
2158  * perform the remote query without control and cache all results,
2159  * performing the pagedResults search only within the client
2160  * and the proxy.  This requires pcache to understand pagedResults. */
2161 static int
2162 pcache_chk_controls(
2163         Operation       *op,
2164         SlapReply       *rs )
2165 {
2166         const char      *non = "";
2167         const char      *stripped = "";
2168
2169         switch( op->o_pagedresults ) {
2170         case SLAP_CONTROL_NONCRITICAL:
2171                 non = "non-";
2172                 stripped = "; stripped";
2173                 /* fallthru */
2174
2175         case SLAP_CONTROL_CRITICAL:
2176                 Debug( pcache_debug, "%s: "
2177                         "%scritical pagedResults control "
2178                         "disabled with proxy cache%s.\n",
2179                         op->o_log_prefix, non, stripped );
2180                 
2181                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2182                 break;
2183
2184         default:
2185                 rs->sr_err = SLAP_CB_CONTINUE;
2186                 break;
2187         }
2188
2189         return rs->sr_err;
2190 }
2191
2192 #ifdef PCACHE_CONTROL_PRIVDB
2193 static int
2194 pcache_op_privdb(
2195         Operation               *op,
2196         SlapReply               *rs )
2197 {
2198         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
2199         cache_manager   *cm = on->on_bi.bi_private;
2200         slap_callback   *save_cb;
2201         slap_op_t       type;
2202
2203         /* skip if control is unset */
2204         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2205                 return SLAP_CB_CONTINUE;
2206         }
2207
2208         /* FIXME: might be a little bit exaggerated... */
2209         if ( !be_isroot( op ) ) {
2210                 save_cb = op->o_callback;
2211                 op->o_callback = NULL;
2212                 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2213                         "pcachePrivDB: operation not allowed" );
2214                 op->o_callback = save_cb;
2215
2216                 return rs->sr_err;
2217         }
2218
2219         /* map tag to operation */
2220         type = slap_req2op( op->o_tag );
2221         if ( type != SLAP_OP_LAST ) {
2222                 BI_op_func      **func;
2223                 int             rc;
2224
2225                 /* execute, if possible */
2226                 func = &cm->db.be_bind;
2227                 if ( func[ type ] != NULL ) {
2228                         Operation       op2 = *op;
2229         
2230                         op2.o_bd = &cm->db;
2231
2232                         rc = func[ type ]( &op2, rs );
2233                         if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2234                                 op->o_conn->c_authz_cookie = cm->db.be_private;
2235                         }
2236                 }
2237         }
2238
2239         /* otherwise fall back to error */
2240         save_cb = op->o_callback;
2241         op->o_callback = NULL;
2242         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2243                 "operation not supported with pcachePrivDB control" );
2244         op->o_callback = save_cb;
2245
2246         return rs->sr_err;
2247 }
2248 #endif /* PCACHE_CONTROL_PRIVDB */
2249
2250 static int
2251 pcache_op_search(
2252         Operation       *op,
2253         SlapReply       *rs )
2254 {
2255         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2256         cache_manager *cm = on->on_bi.bi_private;
2257         query_manager*          qm = cm->qm;
2258
2259         int i = -1;
2260
2261         AttributeName   *filter_attrs = NULL;
2262
2263         Query           query;
2264         QueryTemplate   *qtemp = NULL;
2265
2266         int             attr_set = -1;
2267         CachedQuery     *answerable = NULL;
2268         int             cacheable = 0;
2269         int             fattr_cnt=0;
2270         int             fattr_got_oc = 0;
2271
2272         struct berval   tempstr;
2273
2274 #ifdef PCACHE_CONTROL_PRIVDB
2275         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2276                 return pcache_op_privdb( op, rs );
2277         }
2278 #endif /* PCACHE_CONTROL_PRIVDB */
2279
2280         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2281         tempstr.bv_len = 0;
2282         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2283                 &fattr_cnt, &fattr_got_oc )) {
2284                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2285                 return SLAP_CB_CONTINUE;
2286         }
2287
2288         Debug( pcache_debug, "query template of incoming query = %s\n",
2289                                         tempstr.bv_val, 0, 0 );
2290
2291         /* FIXME: cannot cache/answer requests with pagedResults control */
2292
2293         /* find attr set */
2294         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2295
2296         query.filter = op->ors_filter;
2297         query.base = op->o_req_ndn;
2298         query.scope = op->ors_scope;
2299
2300         /* check for query containment */
2301         if (attr_set > -1) {
2302                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2303                 for (; qt; qt = qt->qtnext ) {
2304                         /* find if template i can potentially answer tempstr */
2305                         if (qt->querystr.bv_len != tempstr.bv_len ||
2306                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2307                                 continue;
2308                         cacheable = 1;
2309                         qtemp = qt;
2310                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
2311                                         op->ors_filterstr.bv_val, 0, 0 );
2312                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2313
2314                         if (answerable)
2315                                 break;
2316                 }
2317         }
2318         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2319
2320         if (answerable) {
2321                 /* Need to clear the callbacks of the original operation,
2322                  * in case there are other overlays */
2323                 BackendDB       *save_bd = op->o_bd;
2324                 slap_callback   *save_cb = op->o_callback;
2325
2326                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2327                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2328                 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
2329                 if ( BER_BVISNULL( &answerable->q_uuid )) {
2330                         /* No entries cached, just an empty result set */
2331                         i = rs->sr_err = 0;
2332                         send_ldap_result( op, rs );
2333                 } else {
2334                         op->o_bd = &cm->db;
2335                         op->o_callback = NULL;
2336                         i = cm->db.bd_info->bi_op_search( op, rs );
2337                 }
2338                 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
2339                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2340                 op->o_bd = save_bd;
2341                 op->o_callback = save_cb;
2342                 return i;
2343         }
2344
2345         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2346
2347         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2348         if (cm->num_cached_queries >= cm->max_queries) {
2349                 cacheable = 0;
2350         }
2351         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2352
2353         if (op->ors_attrsonly)
2354                 cacheable = 0;
2355
2356         if (cacheable) {
2357                 slap_callback           *cb;
2358                 struct search_info      *si;
2359
2360                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2361                 query.filter = filter_dup(op->ors_filter, NULL);
2362                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2363                 if ( !qtemp->t_attrs.count ) {
2364                         qtemp->t_attrs.count = add_filter_attrs(op,
2365                                 &qtemp->t_attrs.attrs,
2366                                 &qm->attr_sets[attr_set],
2367                                 filter_attrs, fattr_cnt, fattr_got_oc);
2368                 }
2369                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2370
2371                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2372                 cb->sc_response = pcache_response;
2373                 cb->sc_cleanup = pcache_op_cleanup;
2374                 cb->sc_private = (cb+1);
2375                 si = cb->sc_private;
2376                 si->on = on;
2377                 si->query = query;
2378                 si->qtemp = qtemp;
2379                 si->max = cm->num_entries_limit ;
2380                 si->over = 0;
2381                 si->count = 0;
2382                 si->slimit = 0;
2383                 si->slimit_exceeded = 0;
2384                 si->caching_reason = PC_IGNORE;
2385                 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2386                         si->slimit = op->ors_slimit;
2387                         op->ors_slimit = cm->num_entries_limit;
2388                 }
2389                 si->head = NULL;
2390                 si->tail = NULL;
2391                 si->save_attrs = op->ors_attrs;
2392
2393                 op->ors_attrs = qtemp->t_attrs.attrs;
2394
2395                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2396                         cb->sc_next = op->o_callback;
2397                         op->o_callback = cb;
2398
2399                 } else {
2400                         slap_callback           **pcb;
2401
2402                         /* need to move the callback at the end, in case other
2403                          * overlays are present, so that the final entry is
2404                          * actually cached */
2405                         cb->sc_next = NULL;
2406                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2407                         *pcb = cb;
2408                 }
2409
2410         } else {
2411                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2412                                         0, 0, 0);
2413         }
2414
2415         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2416
2417         return SLAP_CB_CONTINUE;
2418 }
2419
2420 static int
2421 get_attr_set(
2422         AttributeName* attrs,
2423         query_manager* qm,
2424         int num )
2425 {
2426         int i;
2427         int count = 0;
2428
2429         if ( attrs ) {
2430                 for ( ; attrs[count].an_name.bv_val; count++ );
2431         }
2432
2433         /* recognize a single "*" or a "1.1" */
2434         if ( count == 0 ) {
2435                 count = 1;
2436                 attrs = slap_anlist_all_user_attributes;
2437
2438         } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2439                 count = 0;
2440                 attrs = NULL;
2441         }
2442
2443         for ( i = 0; i < num; i++ ) {
2444                 AttributeName *a2;
2445                 int found = 1;
2446
2447                 if ( count > qm->attr_sets[i].count ) {
2448                         continue;
2449                 }
2450
2451                 if ( !count ) {
2452                         if ( !qm->attr_sets[i].count ) {
2453                                 break;
2454                         }
2455                         continue;
2456                 }
2457
2458                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2459                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2460                                 found = 0;
2461                                 break;
2462                         }
2463                 }
2464
2465                 if ( found ) {
2466                         break;
2467                 }
2468         }
2469
2470         if ( i == num ) {
2471                 i = -1;
2472         }
2473
2474         return i;
2475 }
2476
2477 static void*
2478 consistency_check(
2479         void *ctx,
2480         void *arg )
2481 {
2482         struct re_s *rtask = arg;
2483         slap_overinst *on = rtask->arg;
2484         cache_manager *cm = on->on_bi.bi_private;
2485         query_manager *qm = cm->qm;
2486         Connection conn = {0};
2487         OperationBuffer opbuf;
2488         Operation *op;
2489
2490         SlapReply rs = {REP_RESULT};
2491         CachedQuery* query;
2492         int return_val, pause = 1;
2493         QueryTemplate* templ;
2494
2495         connection_fake_init( &conn, &opbuf, ctx );
2496         op = &opbuf.ob_op;
2497
2498         op->o_bd = &cm->db;
2499         op->o_dn = cm->db.be_rootdn;
2500         op->o_ndn = cm->db.be_rootndn;
2501
2502         cm->cc_arg = arg;
2503
2504         for (templ = qm->templates; templ; templ=templ->qmnext) {
2505                 query = templ->query_last;
2506                 if ( query ) pause = 0;
2507                 op->o_time = slap_get_time();
2508                 while (query && (query->expiry_time < op->o_time)) {
2509                         int rem = 0;
2510                         Debug( pcache_debug, "Lock CR index = %p\n",
2511                                         (void *) templ, 0, 0 );
2512                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2513                         if ( query == templ->query_last ) {
2514                                 rem = 1;
2515                                 remove_from_template(query, templ);
2516                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2517                                                 (void *) templ, templ->no_of_queries, 0 );
2518                                 Debug( pcache_debug, "Unlock CR index = %p\n",
2519                                                 (void *) templ, 0, 0 );
2520                         }
2521                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2522                         if ( !rem ) {
2523                                 query = templ->query_last;
2524                                 continue;
2525                         }
2526                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2527                         remove_query(qm, query);
2528                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2529                         if ( BER_BVISNULL( &query->q_uuid ))
2530                                 return_val = 0;
2531                         else
2532                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
2533                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2534                                                 return_val, 0, 0 );
2535                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2536                         cm->cur_entries -= return_val;
2537                         cm->num_cached_queries--;
2538                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
2539                                         cm->num_cached_queries, 0, 0 );
2540                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2541                         Debug( pcache_debug,
2542                                 "STALE QUERY REMOVED, CACHE ="
2543                                 "%d entries\n",
2544                                 cm->cur_entries, 0, 0 );
2545                         free_query(query);
2546                         query = templ->query_last;
2547                 }
2548         }
2549         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2550         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2551                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2552         }
2553         /* If there were no queries, defer processing for a while */
2554         cm->cc_paused = pause;
2555         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2556
2557         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2558         return NULL;
2559 }
2560
2561
2562 #define MAX_ATTR_SETS 500
2563
2564 enum {
2565         PC_MAIN = 1,
2566         PC_ATTR,
2567         PC_TEMP,
2568         PC_RESP,
2569         PC_QUERIES
2570 };
2571
2572 static ConfigDriver pc_cf_gen;
2573 static ConfigLDAPadd pc_ldadd;
2574 static ConfigCfAdd pc_cfadd;
2575
2576 static ConfigTable pccfg[] = {
2577         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2578                                 "<cycle_time",
2579                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2580                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2581                         "DESC 'ProxyCache basic parameters' "
2582                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2583         { "proxyattrset", "index> <attributes...",
2584                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2585                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2586                         "DESC 'A set of attributes to cache' "
2587                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2588         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2589                 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2590                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2591                         "DESC 'Filter template, attrset, cache TTL, "
2592                                 "optional negative TTL, optional sizelimit TTL' "
2593                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2594         { "response-callback", "head|tail(default)",
2595                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2596                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2597                         "DESC 'Response callback position in overlay stack' "
2598                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2599         { "proxyCacheQueries", "queries",
2600                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2601                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2602                         "DESC 'Maximum number of queries to cache' "
2603                         "SYNTAX OMsInteger )", NULL, NULL },
2604         { "proxySaveQueries", "TRUE|FALSE",
2605                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2606                 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2607                         "DESC 'Save cached queries for hot restart' "
2608                         "SYNTAX OMsBoolean )", NULL, NULL },
2609
2610         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2611 };
2612
2613 static ConfigOCs pcocs[] = {
2614         { "( OLcfgOvOc:2.1 "
2615                 "NAME 'olcPcacheConfig' "
2616                 "DESC 'ProxyCache configuration' "
2617                 "SUP olcOverlayConfig "
2618                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2619                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2620                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2621         { "( OLcfgOvOc:2.2 "
2622                 "NAME 'olcPcacheDatabase' "
2623                 "DESC 'Cache database configuration' "
2624                 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2625         { NULL, 0, NULL }
2626 };
2627
2628 static int
2629 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2630 {
2631         slap_overinst *on;
2632         cache_manager *cm;
2633
2634         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2635                 p->ce_bi->bi_cf_ocs != pcocs )
2636                 return LDAP_CONSTRAINT_VIOLATION;
2637
2638         on = (slap_overinst *)p->ce_bi;
2639         cm = on->on_bi.bi_private;
2640         ca->be = &cm->db;
2641         return LDAP_SUCCESS;
2642 }
2643
2644 static int
2645 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2646 {
2647         CfEntryInfo *pe = p->e_private;
2648         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2649         cache_manager *cm = on->on_bi.bi_private;
2650         struct berval bv;
2651
2652         /* FIXME: should not hardcode "olcDatabase" here */
2653         bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
2654                 "olcDatabase=%s", cm->db.bd_info->bi_type );
2655         if ( bv.bv_len < 0 || bv.bv_len >= sizeof( ca->cr_msg ) ) {
2656                 return -1;
2657         }
2658         bv.bv_val = ca->cr_msg;
2659         ca->be = &cm->db;
2660
2661         /* We can only create this entry if the database is table-driven
2662          */
2663         if ( cm->db.bd_info->bi_cf_ocs )
2664                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2665                         &pcocs[1] );
2666
2667         return 0;
2668 }
2669
2670 static int
2671 pc_cf_gen( ConfigArgs *c )
2672 {
2673         slap_overinst   *on = (slap_overinst *)c->bi;
2674         cache_manager*  cm = on->on_bi.bi_private;
2675         query_manager*  qm = cm->qm;
2676         QueryTemplate*  temp;
2677         AttributeName*  attr_name;
2678         AttributeName*  attrarray;
2679         const char*     text=NULL;
2680         int             i, num, rc = 0;
2681         char            *ptr;
2682         unsigned long   t;
2683
2684         if ( c->op == SLAP_CONFIG_EMIT ) {
2685                 struct berval bv;
2686                 switch( c->type ) {
2687                 case PC_MAIN:
2688                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2689                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2690                                 cm->num_entries_limit, cm->cc_period );
2691                         bv.bv_val = c->cr_msg;
2692                         value_add_one( &c->rvalue_vals, &bv );
2693                         break;
2694                 case PC_ATTR:
2695                         for (i=0; i<cm->numattrsets; i++) {
2696                                 if ( !qm->attr_sets[i].count ) continue;
2697
2698                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2699
2700                                 /* count the attr length */
2701                                 for ( attr_name = qm->attr_sets[i].attrs;
2702                                         attr_name->an_name.bv_val; attr_name++ )
2703                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2704
2705                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2706                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2707                                 for ( attr_name = qm->attr_sets[i].attrs;
2708                                         attr_name->an_name.bv_val; attr_name++ ) {
2709                                         *ptr++ = ' ';
2710                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2711                                 }
2712                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2713                         }
2714                         if ( !c->rvalue_vals )
2715                                 rc = 1;
2716                         break;
2717                 case PC_TEMP:
2718                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2719                                 /* HEADS-UP: always print all;
2720                                  * if optional == 0, ignore */
2721                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2722                                         " %d %ld %ld %ld",
2723                                         temp->attr_set_index,
2724                                         temp->ttl,
2725                                         temp->negttl,
2726                                         temp->limitttl );
2727                                 bv.bv_len += temp->querystr.bv_len + 2;
2728                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2729                                 ptr = bv.bv_val;
2730                                 *ptr++ = '"';
2731                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2732                                 *ptr++ = '"';
2733                                 strcpy( ptr, c->cr_msg );
2734                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2735                         }
2736                         if ( !c->rvalue_vals )
2737                                 rc = 1;
2738                         break;
2739                 case PC_RESP:
2740                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2741                                 BER_BVSTR( &bv, "head" );
2742                         } else {
2743                                 BER_BVSTR( &bv, "tail" );
2744                         }
2745                         value_add_one( &c->rvalue_vals, &bv );
2746                         break;
2747                 case PC_QUERIES:
2748                         c->value_int = cm->max_queries;
2749                         break;
2750                 }
2751                 return rc;
2752         } else if ( c->op == LDAP_MOD_DELETE ) {
2753                 return 1;       /* FIXME */
2754 #if 0
2755                 switch( c->type ) {
2756                 case PC_ATTR:
2757                 case PC_TEMP:
2758                 }
2759                 return rc;
2760 #endif
2761         }
2762
2763         switch( c->type ) {
2764         case PC_MAIN:
2765                 if ( cm->numattrsets > 0 ) {
2766                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2767                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2768                         return( 1 );
2769                 }
2770
2771                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2772                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2773                                 c->argv[3] );
2774                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2775                         return( 1 );
2776                 }
2777                 if ( cm->numattrsets <= 0 ) {
2778                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2779                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2780                         return( 1 );
2781                 }
2782                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2783                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2784                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2785                         return( 1 );
2786                 }
2787
2788                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2789                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2790                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2791                         return( 1 );
2792                 }
2793
2794                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2795                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2796                                 c->argv[2] );
2797                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2798                         return( 1 );
2799                 }
2800                 if ( cm->max_entries <= 0 ) {
2801                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2802                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2803                         return( 1 );
2804                 }
2805
2806                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2807                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2808                                 c->argv[4] );
2809                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2810                         return( 1 );
2811                 }
2812                 if ( cm->num_entries_limit <= 0 ) {
2813                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2814                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2815                         return( 1 );
2816                 }
2817                 if ( cm->num_entries_limit > cm->max_entries ) {
2818                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2819                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2820                         return( 1 );
2821                 }
2822
2823                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2824                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2825                                 c->argv[5] );
2826                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2827                         return( 1 );
2828                 }
2829                 cm->cc_period = (time_t)t;
2830                 Debug( pcache_debug,
2831                                 "Total # of attribute sets to be cached = %d.\n",
2832                                 cm->numattrsets, 0, 0 );
2833                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2834                                                 sizeof( struct attr_set ) );
2835                 break;
2836         case PC_ATTR:
2837                 if ( cm->numattrsets == 0 ) {
2838                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2839                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2840                         return( 1 );
2841                 }
2842                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2843                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2844                                 c->argv[1] );
2845                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2846                         return( 1 );
2847                 }
2848
2849                 if ( num < 0 || num >= cm->numattrsets ) {
2850                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2851                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2852                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2853                         return 1;
2854                 }
2855                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2856                 if ( c->argc == 2 ) {
2857                         /* assume "1.1" */
2858                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2859                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2860                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2861                         return 1;
2862
2863                 } else if ( c->argc == 3 ) {
2864                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2865                                 qm->attr_sets[num].count = 1;
2866                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2867                                         sizeof( AttributeName ) );
2868                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2869                                 break;
2870
2871                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2872                                 qm->attr_sets[num].count = 1;
2873                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2874                                         sizeof( AttributeName ) );
2875                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2876                                 break;
2877
2878                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2879                                 break;
2880                         }
2881                         /* else: fallthru */
2882
2883                 } else if ( c->argc == 4 ) {
2884                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2885                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2886                         {
2887                                 qm->attr_sets[num].count = 2;
2888                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2889                                         sizeof( AttributeName ) );
2890                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2891                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2892                                 break;
2893                         }
2894                         /* else: fallthru */
2895                 }
2896
2897                 if ( c->argc > 2 ) {
2898                         int all_user = 0, all_op = 0;
2899
2900                         qm->attr_sets[num].count = c->argc - 2;
2901                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2902                                 sizeof( AttributeName ) );
2903                         attr_name = qm->attr_sets[num].attrs;
2904                         for ( i = 2; i < c->argc; i++ ) {
2905                                 attr_name->an_desc = NULL;
2906                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2907                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2908                                                 "invalid attr #%d \"%s\" in attrlist",
2909                                                 i - 2, c->argv[i] );
2910                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2911                                         ch_free( qm->attr_sets[num].attrs );
2912                                         qm->attr_sets[num].attrs = NULL;
2913                                         qm->attr_sets[num].count = 0;
2914                                         return 1;
2915                                 }
2916                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2917                                         all_user = 1;
2918                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2919                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2920                                         all_op = 1;
2921                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2922                                 } else {
2923                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2924                                                 strcpy( c->cr_msg, text );
2925                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2926                                                 ch_free( qm->attr_sets[num].attrs );
2927                                                 qm->attr_sets[num].attrs = NULL;
2928                                                 qm->attr_sets[num].count = 0;
2929                                                 return 1;
2930                                         }
2931                                         attr_name->an_name = attr_name->an_desc->ad_cname;
2932                                 }
2933                                 attr_name->an_oc = NULL;
2934                                 attr_name->an_oc_exclude = 0;
2935                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2936                                         qm->attr_sets[num].flags |= PC_GOT_OC;
2937                                 attr_name++;
2938                                 BER_BVZERO( &attr_name->an_name );
2939                         }
2940
2941                         /* warn if list contains both "*" and "+" */
2942                         if ( i > 4 && all_user && all_op ) {
2943                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2944                                         "warning: attribute list contains \"*\" and \"+\"" );
2945                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2946                         }
2947                 }
2948                 break;
2949         case PC_TEMP:
2950                 if ( cm->numattrsets == 0 ) {
2951                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2952                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2953                         return( 1 );
2954                 }
2955                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2956                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2957                                 c->argv[2] );
2958                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2959                         return( 1 );
2960                 }
2961
2962                 if ( i < 0 || i >= cm->numattrsets || 
2963                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2964                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2965                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2966                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2967                         return 1;
2968                 }
2969                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2970                 temp->qmnext = qm->templates;
2971                 qm->templates = temp;
2972                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2973                 temp->query = temp->query_last = NULL;
2974                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2975                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2976                                 "unable to parse template ttl=\"%s\"",
2977                                 c->argv[3] );
2978                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2979                         return( 1 );
2980                 }
2981                 temp->ttl = (time_t)t;
2982                 temp->negttl = (time_t)0;
2983                 temp->limitttl = (time_t)0;
2984                 switch ( c->argc ) {
2985                 case 6:
2986                         if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2987                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2988                                         "unable to parse template sizelimit ttl=\"%s\"",
2989                                         c->argv[5] );
2990                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2991                                         return( 1 );
2992                         }
2993                         temp->limitttl = (time_t)t;
2994                         /* fallthru */
2995
2996                 case 5:
2997                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2998                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2999                                         "unable to parse template negative ttl=\"%s\"",
3000                                         c->argv[4] );
3001                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3002                                         return( 1 );
3003                         }
3004                         temp->negttl = (time_t)t;
3005                         break;
3006                 }
3007
3008                 temp->no_of_queries = 0;
3009
3010                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3011                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3012                 Debug( pcache_debug, "  query template: %s\n",
3013                                 temp->querystr.bv_val, 0, 0 );
3014                 temp->attr_set_index = i;
3015                 qm->attr_sets[i].flags |= PC_REFERENCED;
3016                 temp->qtnext = qm->attr_sets[i].templates;
3017                 qm->attr_sets[i].templates = temp;
3018                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
3019                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3020                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
3021                                 Debug( pcache_debug, "\t%s\n",
3022                                         attrarray[i].an_name.bv_val, 0, 0 );
3023                 }
3024                 break;
3025         case PC_RESP:
3026                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3027                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3028
3029                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3030                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3031
3032                 } else {
3033                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3034                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3035                         return 1;
3036                 }
3037                 break;
3038         case PC_QUERIES:
3039                 if ( c->value_int <= 0 ) {
3040                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3041                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3042                         return( 1 );
3043                 }
3044                 cm->max_queries = c->value_int;
3045                 break;
3046         }
3047         return rc;
3048 }
3049
3050 static int
3051 pcache_db_config(
3052         BackendDB       *be,
3053         const char      *fname,
3054         int             lineno,
3055         int             argc,
3056         char            **argv
3057 )
3058 {
3059         slap_overinst   *on = (slap_overinst *)be->bd_info;
3060         cache_manager*  cm = on->on_bi.bi_private;
3061
3062         /* Something for the cache database? */
3063         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3064                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3065                         argc, argv );
3066         return SLAP_CONF_UNKNOWN;
3067 }
3068
3069 static int
3070 pcache_db_init(
3071         BackendDB *be,
3072         ConfigReply *cr)
3073 {
3074         slap_overinst *on = (slap_overinst *)be->bd_info;
3075         cache_manager *cm;
3076         query_manager *qm;
3077
3078         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3079         on->on_bi.bi_private = cm;
3080
3081         qm = (query_manager*)ch_malloc(sizeof(query_manager));
3082
3083         cm->db = *be;
3084         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3085         cm->db.be_private = NULL;
3086         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
3087         cm->qm = qm;
3088         cm->numattrsets = 0;
3089         cm->num_entries_limit = 5;
3090         cm->num_cached_queries = 0;
3091         cm->max_entries = 0;
3092         cm->cur_entries = 0;
3093         cm->max_queries = 10000;
3094         cm->save_queries = 0;
3095         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3096         cm->cc_period = 1000;
3097         cm->cc_paused = 0;
3098
3099         qm->attr_sets = NULL;
3100         qm->templates = NULL;
3101         qm->lru_top = NULL;
3102         qm->lru_bottom = NULL;
3103
3104         qm->qcfunc = query_containment;
3105         qm->crfunc = cache_replacement;
3106         qm->addfunc = add_query;
3107         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3108
3109         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3110         return 0;
3111 }
3112
3113 static int
3114 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3115 {
3116         assert( op->o_tag == LDAP_REQ_SEARCH );
3117
3118         if ( rs->sr_type == REP_SEARCH ) {
3119                 Attribute       *a;
3120
3121                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3122                 if ( a != NULL ) {
3123                         BerVarray       *valsp;
3124
3125                         assert( a->a_nvals != NULL );
3126
3127                         valsp = op->o_callback->sc_private;
3128                         assert( *valsp == NULL );
3129
3130                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3131                 }
3132         }
3133
3134         return 0;
3135 }
3136
3137 static int
3138 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3139 {
3140         assert( op->o_tag == LDAP_REQ_SEARCH );
3141
3142         if ( rs->sr_type == REP_SEARCH ) {
3143                 int     *countp = (int *)op->o_callback->sc_private;
3144
3145                 (*countp)++;
3146         }
3147
3148         return 0;
3149 }
3150
3151 static int
3152 pcache_db_open(
3153         BackendDB *be,
3154         ConfigReply *cr )
3155 {
3156         slap_overinst   *on = (slap_overinst *)be->bd_info;
3157         cache_manager   *cm = on->on_bi.bi_private;
3158         query_manager*  qm = cm->qm;
3159         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3160
3161         /* check attr sets */
3162         for ( i = 0; i < cm->numattrsets; i++) {
3163                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3164                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3165                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3166                                 rf++;
3167
3168                         } else {
3169                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3170                         }
3171                         ncf++;
3172
3173                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3174                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3175                         nrf++;
3176                 }
3177         }
3178
3179         if ( ncf || rf || nrf ) {
3180                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3181                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3182                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3183
3184                 if ( rf > 0 ) {
3185                         return 1;
3186                 }
3187         }
3188
3189         /* need to inherit something from the original database... */
3190         cm->db.be_def_limit = be->be_def_limit;
3191         cm->db.be_limits = be->be_limits;
3192         cm->db.be_acl = be->be_acl;
3193         cm->db.be_dfltaccess = be->be_dfltaccess;
3194
3195         if ( SLAP_DBMONITORING( be ) ) {
3196                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3197
3198         } else {
3199                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3200         }
3201
3202         rc = backend_startup_one( &cm->db, NULL );
3203
3204         /* There is no runqueue in TOOL mode */
3205         if ( slapMode & SLAP_SERVER_MODE ) {
3206                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3207                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3208                         consistency_check, on,
3209                         "pcache_consistency", be->be_suffix[0].bv_val );
3210                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3211
3212                 /* Cached database must have the rootdn */
3213                 if ( BER_BVISNULL( &cm->db.be_rootndn )
3214                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3215                 {
3216                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3217                                 "underlying database of type \"%s\"\n"
3218                                 "    serving naming context \"%s\"\n"
3219                                 "    has no \"rootdn\", required by \"proxycache\".\n",
3220                                 on->on_info->oi_orig->bi_type,
3221                                 cm->db.be_suffix[0].bv_val, 0 );
3222                         return 1;
3223                 }
3224
3225                 if ( cm->save_queries ) {
3226                         void            *thrctx = ldap_pvt_thread_pool_context();
3227                         Connection      conn = { 0 };
3228                         OperationBuffer opbuf;
3229                         Operation       *op;
3230                         slap_callback   cb = { 0 };
3231                         SlapReply       rs = { 0 };
3232                         BerVarray       vals = NULL;
3233                         Filter          f = { 0 }, f2 = { 0 };
3234                         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
3235                         AttributeName   attrs[ 2 ] = { 0 };
3236
3237                         connection_fake_init( &conn, &opbuf, thrctx );
3238                         op = &opbuf.ob_op;
3239
3240                         op->o_bd = &cm->db;
3241
3242                         op->o_tag = LDAP_REQ_SEARCH;
3243                         op->o_protocol = LDAP_VERSION3;
3244                         cb.sc_response = pcache_cachedquery_open_cb;
3245                         cb.sc_private = &vals;
3246                         op->o_callback = &cb;
3247                         op->o_time = slap_get_time();
3248                         op->o_do_not_cache = 1;
3249                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
3250
3251                         op->o_dn = cm->db.be_rootdn;
3252                         op->o_ndn = cm->db.be_rootndn;
3253                         op->o_req_dn = cm->db.be_suffix[ 0 ];
3254                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3255
3256                         op->ors_scope = LDAP_SCOPE_BASE;
3257                         op->ors_deref = LDAP_DEREF_NEVER;
3258                         op->ors_slimit = 1;
3259                         op->ors_tlimit = SLAP_NO_LIMIT;
3260                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3261                         f.f_choice = LDAP_FILTER_PRESENT;
3262                         f.f_desc = ad_cachedQueryURL;
3263                         op->ors_filter = &f;
3264                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
3265                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3266                         op->ors_attrs = attrs;
3267                         op->ors_attrsonly = 0;
3268
3269                         rc = op->o_bd->be_search( op, &rs );
3270                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
3271                                 int     i;
3272
3273                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3274                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3275                                                 cm->num_cached_queries++;
3276                                         }
3277                                 }
3278
3279                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3280                         }
3281
3282                         /* count cached entries */
3283                         f.f_choice = LDAP_FILTER_NOT;
3284                         f.f_not = &f2;
3285                         f2.f_choice = LDAP_FILTER_EQUALITY;
3286                         f2.f_ava = &ava;
3287                         f2.f_av_desc = slap_schema.si_ad_objectClass;
3288                         BER_BVSTR( &f2.f_av_value, "glue" );
3289                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3290
3291                         op->ors_slimit = SLAP_NO_LIMIT;
3292                         op->ors_scope = LDAP_SCOPE_SUBTREE;
3293                         op->ors_attrs = slap_anlist_no_attrs;
3294
3295                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
3296                         rs.sr_nentries = 0;
3297                         op->o_callback->sc_private = &rs.sr_nentries;
3298
3299                         rc = op->o_bd->be_search( op, &rs );
3300
3301                         cm->cur_entries = rs.sr_nentries;
3302
3303                         /* ignore errors */
3304                         rc = 0;
3305                 }
3306         }
3307
3308         return rc;
3309 }
3310
3311 static void
3312 pcache_free_qbase( void *v )
3313 {
3314         Qbase *qb = v;
3315         int i;
3316
3317         for (i=0; i<3; i++)
3318                 tavl_free( qb->scopes[i], NULL );
3319         ch_free( qb );
3320 }
3321
3322 static int
3323 pcache_db_close(
3324         BackendDB *be,
3325         ConfigReply *cr
3326 )
3327 {
3328         slap_overinst *on = (slap_overinst *)be->bd_info;
3329         cache_manager *cm = on->on_bi.bi_private;
3330         query_manager *qm = cm->qm;
3331         QueryTemplate *tm;
3332         int i, rc = 0;
3333
3334         if ( cm->save_queries ) {
3335                 CachedQuery     *qc;
3336                 BerVarray       vals = NULL;
3337
3338                 void            *thrctx;
3339                 Connection      conn = { 0 };
3340                 OperationBuffer opbuf;
3341                 Operation       *op;
3342                 slap_callback   cb = { 0 };
3343
3344                 SlapReply       rs = { REP_RESULT };
3345                 Modifications   mod = { 0 };
3346
3347                 thrctx = ldap_pvt_thread_pool_context();
3348
3349                 connection_fake_init( &conn, &opbuf, thrctx );
3350                 op = &opbuf.ob_op;
3351
3352                 if ( qm->templates != NULL ) {
3353                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3354                                 for ( qc = tm->query; qc; qc = qc->next ) {
3355                                         struct berval   bv;
3356
3357                                         if ( query2url( op, qc, &bv ) == 0 ) {
3358                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3359                                         }
3360                                 }
3361                         }
3362                 }
3363
3364                 op->o_bd = &cm->db;
3365                 op->o_dn = cm->db.be_rootdn;
3366                 op->o_ndn = cm->db.be_rootndn;
3367
3368                 op->o_tag = LDAP_REQ_MODIFY;
3369                 op->o_protocol = LDAP_VERSION3;
3370                 cb.sc_response = slap_null_cb;
3371                 op->o_callback = &cb;
3372                 op->o_time = slap_get_time();
3373                 op->o_do_not_cache = 1;
3374                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3375
3376                 op->o_req_dn = op->o_bd->be_suffix[0];
3377                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3378
3379                 mod.sml_op = LDAP_MOD_REPLACE;
3380                 mod.sml_flags = 0;
3381                 mod.sml_desc = ad_cachedQueryURL;
3382                 mod.sml_type = ad_cachedQueryURL->ad_cname;
3383                 mod.sml_values = vals;
3384                 mod.sml_nvalues = NULL;
3385                 mod.sml_numvals = 1;
3386                 mod.sml_next = NULL;
3387                 Debug( pcache_debug,
3388                         "%sSETTING CACHED QUERY URLS\n",
3389                         vals == NULL ? "RE" : "", 0, 0 );
3390
3391                 op->orm_modlist = &mod;
3392
3393                 op->o_bd->be_modify( op, &rs );
3394
3395                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3396         }
3397
3398         /* cleanup stuff inherited from the original database... */
3399         cm->db.be_limits = NULL;
3400         cm->db.be_acl = NULL;
3401
3402         /* stop the thread ... */
3403         if ( cm->cc_arg ) {
3404                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3405                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3406                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3407                 }
3408                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3409                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3410         }
3411
3412         if ( cm->db.bd_info->bi_db_close ) {
3413                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3414         }
3415         while ( (tm = qm->templates) != NULL ) {
3416                 CachedQuery *qc, *qn;
3417                 qm->templates = tm->qmnext;
3418                 for ( qc = tm->query; qc; qc = qn ) {
3419                         qn = qc->next;
3420                         free_query( qc );
3421                 }
3422                 avl_free( tm->qbase, pcache_free_qbase );
3423                 free( tm->querystr.bv_val );
3424                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3425                 free( tm->t_attrs.attrs );
3426                 free( tm );
3427         }
3428
3429         for ( i=0; i<cm->numattrsets; i++ ) {
3430                 free( qm->attr_sets[i].attrs );
3431         }
3432         free( qm->attr_sets );
3433         qm->attr_sets = NULL;
3434
3435         return rc;
3436 }
3437
3438 static int
3439 pcache_db_destroy(
3440         BackendDB *be,
3441         ConfigReply *cr
3442 )
3443 {
3444         slap_overinst *on = (slap_overinst *)be->bd_info;
3445         cache_manager *cm = on->on_bi.bi_private;
3446         query_manager *qm = cm->qm;
3447
3448         if ( cm->db.be_private != NULL ) {
3449                 backend_stopdown_one( &cm->db );
3450         }
3451
3452         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3453         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3454         free( qm );
3455         free( cm );
3456
3457         return 0;
3458 }
3459
3460 #ifdef PCACHE_CONTROL_PRIVDB
3461 /*
3462         Control ::= SEQUENCE {
3463              controlType             LDAPOID,
3464              criticality             BOOLEAN DEFAULT FALSE,
3465              controlValue            OCTET STRING OPTIONAL }
3466
3467         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3468
3469  * criticality must be TRUE; controlValue must be absent.
3470  */
3471 static int
3472 parse_privdb_ctrl(
3473         Operation       *op,
3474         SlapReply       *rs,
3475         LDAPControl     *ctrl )
3476 {
3477         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3478                 rs->sr_text = "privateDB control specified multiple times";
3479                 return LDAP_PROTOCOL_ERROR;
3480         }
3481
3482         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3483                 rs->sr_text = "privateDB control value not absent";
3484                 return LDAP_PROTOCOL_ERROR;
3485         }
3486
3487         if ( !ctrl->ldctl_iscritical ) {
3488                 rs->sr_text = "privateDB control criticality required";
3489                 return LDAP_PROTOCOL_ERROR;
3490         }
3491
3492         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3493
3494         return LDAP_SUCCESS;
3495 }
3496
3497 static char *extops[] = {
3498         LDAP_EXOP_MODIFY_PASSWD,
3499         NULL
3500 };
3501 #endif /* PCACHE_CONTROL_PRIVDB */
3502
3503 #ifdef PCACHE_EXOP_QUERY_DELETE
3504 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3505
3506 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3507 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3508 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3509
3510 /*
3511         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3512              requestName      [0] LDAPOID,
3513              requestValue     [1] OCTET STRING OPTIONAL }
3514
3515         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3516
3517         requestValue ::= SEQUENCE { CHOICE {
3518                   baseDN           [0] LDAPDN
3519                   entryDN          [1] LDAPDN },
3520              queryID          [2] OCTET STRING (SIZE(16))
3521                   -- constrained to UUID }
3522
3523  * Either baseDN or entryDN must be present, to allow database selection.
3524  *
3525  * 1. if baseDN and queryID are present, then the query corresponding
3526  *    to queryID is deleted;
3527  * 2. if baseDN is present and queryID is absent, then all queries
3528  *    are deleted;
3529  * 3. if entryDN is present and queryID is absent, then all queries
3530  *    corresponding to the queryID values present in entryDN are deleted;
3531  * 4. if entryDN and queryID are present, then all queries
3532  *    corresponding to the queryID values present in entryDN are deleted,
3533  *    but only if the value of queryID is contained in the entry;
3534  *
3535  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
3536  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3537  * or by removing the database files.
3538
3539         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3540              COMPONENTS OF LDAPResult,
3541              responseName     [10] LDAPOID OPTIONAL,
3542              responseValue    [11] OCTET STRING OPTIONAL }
3543
3544  * responseName and responseValue must be absent.
3545  */
3546
3547 /*
3548  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3549  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3550  * - if ndn != NULL, it is set to the normalized DN in the request
3551  *   corresponding to either the baseDN or the entryDN, according
3552  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
3553  *   be freed by the caller.
3554  * - if uuid != NULL, it is set to point to the normalized UUID;
3555  *   memory is malloc'ed on the Operation's slab, and must
3556  *   be freed by the caller.
3557  */
3558 static int
3559 pcache_parse_query_delete(
3560         struct berval   *in,
3561         ber_tag_t       *tagp,
3562         struct berval   *ndn,
3563         struct berval   *uuid,
3564         const char      **text,
3565         void            *ctx )
3566 {
3567         int                     rc = LDAP_SUCCESS;
3568         ber_tag_t               tag;
3569         ber_len_t               len = -1;
3570         BerElementBuffer        berbuf;
3571         BerElement              *ber = (BerElement *)&berbuf;
3572         struct berval           reqdata = BER_BVNULL;
3573
3574         *text = NULL;
3575
3576         if ( ndn ) {
3577                 BER_BVZERO( ndn );
3578         }
3579
3580         if ( uuid ) {
3581                 BER_BVZERO( uuid );
3582         }
3583
3584         if ( in == NULL || in->bv_len == 0 ) {
3585                 *text = "empty request data field in queryDelete exop";
3586                 return LDAP_PROTOCOL_ERROR;
3587         }
3588
3589         ber_dupbv_x( &reqdata, in, ctx );
3590
3591         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3592         ber_init2( ber, &reqdata, 0 );
3593
3594         tag = ber_scanf( ber, "{" /*}*/ );
3595
3596         if ( tag == LBER_ERROR ) {
3597                 Debug( LDAP_DEBUG_TRACE,
3598                         "pcache_parse_query_delete: decoding error.\n",
3599                         0, 0, 0 );
3600                 goto decoding_error;
3601         }
3602
3603         tag = ber_peek_tag( ber, &len );
3604         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3605                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3606         {
3607                 *tagp = tag;
3608
3609                 if ( ndn != NULL ) {
3610                         struct berval   dn;
3611
3612                         tag = ber_scanf( ber, "m", &dn );
3613                         if ( tag == LBER_ERROR ) {
3614                                 Debug( LDAP_DEBUG_TRACE,
3615                                         "pcache_parse_query_delete: DN parse failed.\n",
3616                                         0, 0, 0 );
3617                                 goto decoding_error;
3618                         }
3619
3620                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3621                         if ( rc != LDAP_SUCCESS ) {
3622                                 *text = "invalid DN in queryDelete exop request data";
3623                                 goto done;
3624                         }
3625
3626                 } else {
3627                         tag = ber_scanf( ber, "x" /* "m" */ );
3628                         if ( tag == LBER_DEFAULT ) {
3629                                 goto decoding_error;
3630                         }
3631                 }
3632
3633                 tag = ber_peek_tag( ber, &len );
3634         }
3635
3636         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3637                 if ( uuid != NULL ) {
3638                         struct berval   bv;
3639                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3640
3641                         tag = ber_scanf( ber, "m", &bv );
3642                         if ( tag == LBER_ERROR ) {
3643                                 Debug( LDAP_DEBUG_TRACE,
3644                                         "pcache_parse_query_delete: UUID parse failed.\n",
3645                                         0, 0, 0 );
3646                                 goto decoding_error;
3647                         }
3648
3649                         if ( bv.bv_len != 16 ) {
3650                                 Debug( LDAP_DEBUG_TRACE,
3651                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3652                                         (unsigned long)bv.bv_len, 0, 0 );
3653                                 goto decoding_error;
3654                         }
3655
3656                         rc = lutil_uuidstr_from_normalized(
3657                                 bv.bv_val, bv.bv_len,
3658                                 uuidbuf, sizeof( uuidbuf ) );
3659                         if ( rc == -1 ) {
3660                                 goto decoding_error;
3661                         }
3662                         ber_str2bv( uuidbuf, rc, 1, uuid );
3663                         rc = LDAP_SUCCESS;
3664
3665                 } else {
3666                         tag = ber_skip_tag( ber, &len );
3667                         if ( tag == LBER_DEFAULT ) {
3668                                 goto decoding_error;
3669                         }
3670
3671                         if ( len != 16 ) {
3672                                 Debug( LDAP_DEBUG_TRACE,
3673                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3674                                         (unsigned long)len, 0, 0 );
3675                                 goto decoding_error;
3676                         }
3677                 }
3678
3679                 tag = ber_peek_tag( ber, &len );
3680         }
3681
3682         if ( tag != LBER_DEFAULT || len != 0 ) {
3683 decoding_error:;
3684                 Debug( LDAP_DEBUG_TRACE,
3685                         "pcache_parse_query_delete: decoding error\n",
3686                         0, 0, 0 );
3687                 rc = LDAP_PROTOCOL_ERROR;
3688                 *text = "queryDelete data decoding error";
3689
3690 done:;
3691                 if ( ndn && !BER_BVISNULL( ndn ) ) {
3692                         slap_sl_free( ndn->bv_val, ctx );
3693                         BER_BVZERO( ndn );
3694                 }
3695
3696                 if ( uuid && !BER_BVISNULL( uuid ) ) {
3697                         slap_sl_free( uuid->bv_val, ctx );
3698                         BER_BVZERO( uuid );
3699                 }
3700         }
3701
3702         if ( !BER_BVISNULL( &reqdata ) ) {
3703                 ber_memfree_x( reqdata.bv_val, ctx );
3704         }
3705
3706         return rc;
3707 }
3708
3709 static int
3710 pcache_exop_query_delete(
3711         Operation       *op,
3712         SlapReply       *rs )
3713 {
3714         BackendDB       *bd = op->o_bd;
3715
3716         struct berval   uuid = BER_BVNULL,
3717                         *uuidp = NULL;
3718         char            buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3719         int             len = 0;
3720         ber_tag_t       tag = LBER_DEFAULT;
3721
3722         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3723                 uuidp = &uuid;
3724         }
3725
3726         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3727                 &tag, &op->o_req_ndn, uuidp,
3728                 &rs->sr_text, op->o_tmpmemctx );
3729         if ( rs->sr_err != LDAP_SUCCESS ) {
3730                 return rs->sr_err;
3731         }
3732
3733         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3734                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3735                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3736
3737                 if ( !BER_BVISNULL( &uuid ) ) {
3738                         snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3739                 }
3740
3741                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3742                         op->o_log_prefix, buf, 0 );
3743         }
3744         op->o_req_dn = op->o_req_ndn;
3745
3746         op->o_bd = select_backend( &op->o_req_ndn, 0 );
3747         rs->sr_err = backend_check_restrictions( op, rs,
3748                 (struct berval *)&pcache_exop_QUERY_DELETE );
3749         if ( rs->sr_err != LDAP_SUCCESS ) {
3750                 goto done;
3751         }
3752
3753         if ( op->o_bd->be_extended == NULL ) {
3754                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3755                         "backend does not support extended operations" );
3756                 goto done;
3757         }
3758
3759         op->o_bd->be_extended( op, rs );
3760
3761 done:;
3762         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3763                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3764                 BER_BVZERO( &op->o_req_ndn );
3765                 BER_BVZERO( &op->o_req_dn );
3766         }
3767
3768         if ( !BER_BVISNULL( &uuid ) ) {
3769                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3770         }
3771
3772         op->o_bd = bd;
3773
3774         return rs->sr_err;
3775 }
3776
3777 static int
3778 pcache_op_extended( Operation *op, SlapReply *rs )
3779 {
3780         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
3781         cache_manager   *cm = on->on_bi.bi_private;
3782
3783 #ifdef PCACHE_CONTROL_PRIVDB
3784         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3785                 return pcache_op_privdb( op, rs );
3786         }
3787 #endif /* PCACHE_CONTROL_PRIVDB */
3788
3789         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3790                 struct berval   uuid = BER_BVNULL;
3791                 ber_tag_t       tag = LBER_DEFAULT;
3792
3793                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3794                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3795                 assert( rs->sr_err == LDAP_SUCCESS );
3796
3797                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3798                         /* remove all queries related to the selected entry */
3799                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3800                                 cm, &op->o_req_ndn, &uuid );
3801
3802                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3803                         if ( !BER_BVISNULL( &uuid ) ) {
3804                                 /* remove the selected query */
3805                                 rs->sr_err = pcache_remove_query_from_cache( op,
3806                                         cm, &uuid );
3807
3808                         } else {
3809                                 /* TODO: remove all queries */
3810                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3811                                 rs->sr_text = "deletion of all queries not implemented";
3812                         }
3813                 }
3814
3815                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3816         }
3817
3818         return rs->sr_err;
3819 }
3820 #endif /* PCACHE_EXOP_QUERY_DELETE */
3821
3822 static slap_overinst pcache;
3823
3824 static char *obsolete_names[] = {
3825         "proxycache",
3826         NULL
3827 };
3828
3829 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3830 static
3831 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3832 int
3833 pcache_initialize()
3834 {
3835         int i, code;
3836         struct berval debugbv = BER_BVC("pcache");
3837
3838         code = slap_loglevel_get( &debugbv, &pcache_debug );
3839         if ( code ) {
3840                 return code;
3841         }
3842
3843 #ifdef PCACHE_CONTROL_PRIVDB
3844         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3845                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3846                 parse_privdb_ctrl, &privDB_cid );
3847         if ( code != LDAP_SUCCESS ) {
3848                 Debug( LDAP_DEBUG_ANY,
3849                         "pcache_initialize: failed to register control %s (%d)\n",
3850                         PCACHE_CONTROL_PRIVDB, code, 0 );
3851                 return code;
3852         }
3853 #endif /* PCACHE_CONTROL_PRIVDB */
3854
3855 #ifdef PCACHE_EXOP_QUERY_DELETE
3856         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3857                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3858                 0 );
3859         if ( code != LDAP_SUCCESS ) {
3860                 Debug( LDAP_DEBUG_ANY,
3861                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
3862                         code, 0, 0 );
3863                 return code;
3864         }
3865 #endif /* PCACHE_EXOP_QUERY_DELETE */
3866
3867         for ( i = 0; as[i].desc != NULL; i++ ) {
3868                 code = register_at( as[i].desc, as[i].adp, 0 );
3869                 if ( code ) {
3870                         Debug( LDAP_DEBUG_ANY,
3871                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3872                         return code;
3873                 }
3874                 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3875         }
3876
3877         pcache.on_bi.bi_type = "pcache";
3878         pcache.on_bi.bi_obsolete_names = obsolete_names;
3879         pcache.on_bi.bi_db_init = pcache_db_init;
3880         pcache.on_bi.bi_db_config = pcache_db_config;
3881         pcache.on_bi.bi_db_open = pcache_db_open;
3882         pcache.on_bi.bi_db_close = pcache_db_close;
3883         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3884
3885         pcache.on_bi.bi_op_search = pcache_op_search;
3886 #ifdef PCACHE_CONTROL_PRIVDB
3887         pcache.on_bi.bi_op_bind = pcache_op_privdb;
3888         pcache.on_bi.bi_op_compare = pcache_op_privdb;
3889         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3890         pcache.on_bi.bi_op_modify = pcache_op_privdb;
3891         pcache.on_bi.bi_op_add = pcache_op_privdb;
3892         pcache.on_bi.bi_op_delete = pcache_op_privdb;
3893 #endif /* PCACHE_CONTROL_PRIVDB */
3894 #ifdef PCACHE_EXOP_QUERY_DELETE
3895         pcache.on_bi.bi_extended = pcache_op_extended;
3896 #elif defined( PCACHE_CONTROL_PRIVDB )
3897         pcache.on_bi.bi_extended = pcache_op_privdb;
3898 #endif
3899
3900         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3901
3902         pcache.on_bi.bi_cf_ocs = pcocs;
3903
3904         code = config_register_schema( pccfg, pcocs );
3905         if ( code ) return code;
3906
3907         return overlay_register( &pcache );
3908 }
3909
3910 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3911 int init_module(int argc, char *argv[]) {
3912         return pcache_initialize();
3913 }
3914 #endif
3915
3916 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */