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