]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
ITS#5705
[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 static ConfigOCs pcocs[] = {
2659         { "( OLcfgOvOc:2.1 "
2660                 "NAME 'olcPcacheConfig' "
2661                 "DESC 'ProxyCache configuration' "
2662                 "SUP olcOverlayConfig "
2663                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2664                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries $ olcProxyCheckCacheability ) )",
2665                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2666         { "( OLcfgOvOc:2.2 "
2667                 "NAME 'olcPcacheDatabase' "
2668                 "DESC 'Cache database configuration' "
2669                 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
2670         { NULL, 0, NULL }
2671 };
2672
2673 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
2674
2675 static int
2676 pc_ldadd_cleanup( ConfigArgs *c )
2677 {
2678         slap_overinst *on = c->ca_private;
2679         return pcache_db_open2( on, &c->reply );
2680 }
2681
2682 static int
2683 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2684 {
2685         slap_overinst *on;
2686         cache_manager *cm;
2687
2688         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2689                 p->ce_bi->bi_cf_ocs != pcocs )
2690                 return LDAP_CONSTRAINT_VIOLATION;
2691
2692         on = (slap_overinst *)p->ce_bi;
2693         cm = on->on_bi.bi_private;
2694         ca->be = &cm->db;
2695         /* Defer open if this is an LDAPadd */
2696         if ( CONFIG_ONLINE_ADD( ca ))
2697                 ca->cleanup = pc_ldadd_cleanup;
2698         else
2699                 cm->defer_db_open = 0;
2700         ca->ca_private = on;
2701         return LDAP_SUCCESS;
2702 }
2703
2704 static int
2705 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2706 {
2707         CfEntryInfo *pe = p->e_private;
2708         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2709         cache_manager *cm = on->on_bi.bi_private;
2710         struct berval bv;
2711
2712         /* FIXME: should not hardcode "olcDatabase" here */
2713         bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
2714                 "olcDatabase=%s", cm->db.bd_info->bi_type );
2715         if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
2716                 return -1;
2717         }
2718         bv.bv_val = ca->cr_msg;
2719         ca->be = &cm->db;
2720         cm->defer_db_open = 0;
2721
2722         /* We can only create this entry if the database is table-driven
2723          */
2724         if ( cm->db.bd_info->bi_cf_ocs )
2725                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2726                         &pcocs[1] );
2727
2728         return 0;
2729 }
2730
2731 static int
2732 pc_cf_gen( ConfigArgs *c )
2733 {
2734         slap_overinst   *on = (slap_overinst *)c->bi;
2735         cache_manager*  cm = on->on_bi.bi_private;
2736         query_manager*  qm = cm->qm;
2737         QueryTemplate*  temp;
2738         AttributeName*  attr_name;
2739         AttributeName*  attrarray;
2740         const char*     text=NULL;
2741         int             i, num, rc = 0;
2742         char            *ptr;
2743         unsigned long   t;
2744
2745         if ( c->op == SLAP_CONFIG_EMIT ) {
2746                 struct berval bv;
2747                 switch( c->type ) {
2748                 case PC_MAIN:
2749                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2750                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2751                                 cm->num_entries_limit, cm->cc_period );
2752                         bv.bv_val = c->cr_msg;
2753                         value_add_one( &c->rvalue_vals, &bv );
2754                         break;
2755                 case PC_ATTR:
2756                         for (i=0; i<cm->numattrsets; i++) {
2757                                 if ( !qm->attr_sets[i].count ) continue;
2758
2759                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2760
2761                                 /* count the attr length */
2762                                 for ( attr_name = qm->attr_sets[i].attrs;
2763                                         attr_name->an_name.bv_val; attr_name++ )
2764                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2765
2766                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2767                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2768                                 for ( attr_name = qm->attr_sets[i].attrs;
2769                                         attr_name->an_name.bv_val; attr_name++ ) {
2770                                         *ptr++ = ' ';
2771                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2772                                 }
2773                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2774                         }
2775                         if ( !c->rvalue_vals )
2776                                 rc = 1;
2777                         break;
2778                 case PC_TEMP:
2779                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2780                                 /* HEADS-UP: always print all;
2781                                  * if optional == 0, ignore */
2782                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2783                                         " %d %ld %ld %ld",
2784                                         temp->attr_set_index,
2785                                         temp->ttl,
2786                                         temp->negttl,
2787                                         temp->limitttl );
2788                                 bv.bv_len += temp->querystr.bv_len + 2;
2789                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2790                                 ptr = bv.bv_val;
2791                                 *ptr++ = '"';
2792                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2793                                 *ptr++ = '"';
2794                                 strcpy( ptr, c->cr_msg );
2795                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2796                         }
2797                         if ( !c->rvalue_vals )
2798                                 rc = 1;
2799                         break;
2800                 case PC_RESP:
2801                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2802                                 BER_BVSTR( &bv, "head" );
2803                         } else {
2804                                 BER_BVSTR( &bv, "tail" );
2805                         }
2806                         value_add_one( &c->rvalue_vals, &bv );
2807                         break;
2808                 case PC_QUERIES:
2809                         c->value_int = cm->max_queries;
2810                         break;
2811                 }
2812                 return rc;
2813         } else if ( c->op == LDAP_MOD_DELETE ) {
2814                 return 1;       /* FIXME */
2815 #if 0
2816                 switch( c->type ) {
2817                 case PC_ATTR:
2818                 case PC_TEMP:
2819                 }
2820                 return rc;
2821 #endif
2822         }
2823
2824         switch( c->type ) {
2825         case PC_MAIN:
2826                 if ( cm->numattrsets > 0 ) {
2827                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2828                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2829                         return( 1 );
2830                 }
2831
2832                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2833                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2834                                 c->argv[3] );
2835                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2836                         return( 1 );
2837                 }
2838                 if ( cm->numattrsets <= 0 ) {
2839                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2840                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2841                         return( 1 );
2842                 }
2843                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2844                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2845                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2846                         return( 1 );
2847                 }
2848
2849                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2850                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2851                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2852                         return( 1 );
2853                 }
2854
2855                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2856                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2857                                 c->argv[2] );
2858                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2859                         return( 1 );
2860                 }
2861                 if ( cm->max_entries <= 0 ) {
2862                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2863                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2864                         return( 1 );
2865                 }
2866
2867                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2868                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2869                                 c->argv[4] );
2870                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2871                         return( 1 );
2872                 }
2873                 if ( cm->num_entries_limit <= 0 ) {
2874                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2875                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2876                         return( 1 );
2877                 }
2878                 if ( cm->num_entries_limit > cm->max_entries ) {
2879                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2880                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2881                         return( 1 );
2882                 }
2883
2884                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2885                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2886                                 c->argv[5] );
2887                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2888                         return( 1 );
2889                 }
2890
2891                 cm->cc_period = (time_t)t;
2892                 Debug( pcache_debug,
2893                                 "Total # of attribute sets to be cached = %d.\n",
2894                                 cm->numattrsets, 0, 0 );
2895                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2896                                                 sizeof( struct attr_set ) );
2897                 break;
2898         case PC_ATTR:
2899                 if ( cm->numattrsets == 0 ) {
2900                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2901                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2902                         return( 1 );
2903                 }
2904                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2905                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2906                                 c->argv[1] );
2907                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2908                         return( 1 );
2909                 }
2910
2911                 if ( num < 0 || num >= cm->numattrsets ) {
2912                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2913                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2914                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2915                         return 1;
2916                 }
2917                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2918                 if ( c->argc == 2 ) {
2919                         /* assume "1.1" */
2920                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2921                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2922                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2923                         return 1;
2924
2925                 } else if ( c->argc == 3 ) {
2926                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2927                                 qm->attr_sets[num].count = 1;
2928                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2929                                         sizeof( AttributeName ) );
2930                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2931                                 break;
2932
2933                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2934                                 qm->attr_sets[num].count = 1;
2935                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2936                                         sizeof( AttributeName ) );
2937                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2938                                 break;
2939
2940                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2941                                 break;
2942                         }
2943                         /* else: fallthru */
2944
2945                 } else if ( c->argc == 4 ) {
2946                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2947                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2948                         {
2949                                 qm->attr_sets[num].count = 2;
2950                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2951                                         sizeof( AttributeName ) );
2952                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2953                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2954                                 break;
2955                         }
2956                         /* else: fallthru */
2957                 }
2958
2959                 if ( c->argc > 2 ) {
2960                         int all_user = 0, all_op = 0;
2961
2962                         qm->attr_sets[num].count = c->argc - 2;
2963                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2964                                 sizeof( AttributeName ) );
2965                         attr_name = qm->attr_sets[num].attrs;
2966                         for ( i = 2; i < c->argc; i++ ) {
2967                                 attr_name->an_desc = NULL;
2968                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2969                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2970                                                 "invalid attr #%d \"%s\" in attrlist",
2971                                                 i - 2, c->argv[i] );
2972                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2973                                         ch_free( qm->attr_sets[num].attrs );
2974                                         qm->attr_sets[num].attrs = NULL;
2975                                         qm->attr_sets[num].count = 0;
2976                                         return 1;
2977                                 }
2978                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2979                                         all_user = 1;
2980                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2981                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2982                                         all_op = 1;
2983                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2984                                 } else {
2985                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2986                                                 strcpy( c->cr_msg, text );
2987                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2988                                                 ch_free( qm->attr_sets[num].attrs );
2989                                                 qm->attr_sets[num].attrs = NULL;
2990                                                 qm->attr_sets[num].count = 0;
2991                                                 return 1;
2992                                         }
2993                                         attr_name->an_name = attr_name->an_desc->ad_cname;
2994                                 }
2995                                 attr_name->an_oc = NULL;
2996                                 attr_name->an_oc_exclude = 0;
2997                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2998                                         qm->attr_sets[num].flags |= PC_GOT_OC;
2999                                 attr_name++;
3000                                 BER_BVZERO( &attr_name->an_name );
3001                         }
3002
3003                         /* warn if list contains both "*" and "+" */
3004                         if ( i > 4 && all_user && all_op ) {
3005                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3006                                         "warning: attribute list contains \"*\" and \"+\"" );
3007                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3008                         }
3009                 }
3010                 break;
3011         case PC_TEMP:
3012                 if ( cm->numattrsets == 0 ) {
3013                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3014                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3015                         return( 1 );
3016                 }
3017                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
3018                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
3019                                 c->argv[2] );
3020                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3021                         return( 1 );
3022                 }
3023
3024                 if ( i < 0 || i >= cm->numattrsets || 
3025                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
3026                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
3027                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3028                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3029                         return 1;
3030                 }
3031                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
3032                 temp->qmnext = qm->templates;
3033                 qm->templates = temp;
3034                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
3035                 temp->query = temp->query_last = NULL;
3036                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
3037                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3038                                 "unable to parse template ttl=\"%s\"",
3039                                 c->argv[3] );
3040                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3041                         return( 1 );
3042                 }
3043                 temp->ttl = (time_t)t;
3044                 temp->negttl = (time_t)0;
3045                 temp->limitttl = (time_t)0;
3046                 switch ( c->argc ) {
3047                 case 6:
3048                         if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3049                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3050                                         "unable to parse template sizelimit ttl=\"%s\"",
3051                                         c->argv[5] );
3052                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3053                                         return( 1 );
3054                         }
3055                         temp->limitttl = (time_t)t;
3056                         /* fallthru */
3057
3058                 case 5:
3059                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
3060                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3061                                         "unable to parse template negative ttl=\"%s\"",
3062                                         c->argv[4] );
3063                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3064                                         return( 1 );
3065                         }
3066                         temp->negttl = (time_t)t;
3067                         break;
3068                 }
3069
3070                 temp->no_of_queries = 0;
3071
3072                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3073                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3074                 Debug( pcache_debug, "  query template: %s\n",
3075                                 temp->querystr.bv_val, 0, 0 );
3076                 temp->attr_set_index = i;
3077                 qm->attr_sets[i].flags |= PC_REFERENCED;
3078                 temp->qtnext = qm->attr_sets[i].templates;
3079                 qm->attr_sets[i].templates = temp;
3080                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
3081                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3082                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
3083                                 Debug( pcache_debug, "\t%s\n",
3084                                         attrarray[i].an_name.bv_val, 0, 0 );
3085                 }
3086                 break;
3087         case PC_RESP:
3088                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3089                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3090
3091                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3092                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3093
3094                 } else {
3095                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3096                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3097                         return 1;
3098                 }
3099                 break;
3100         case PC_QUERIES:
3101                 if ( c->value_int <= 0 ) {
3102                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3103                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3104                         return( 1 );
3105                 }
3106                 cm->max_queries = c->value_int;
3107                 break;
3108         }
3109         return rc;
3110 }
3111
3112 static int
3113 pcache_db_config(
3114         BackendDB       *be,
3115         const char      *fname,
3116         int             lineno,
3117         int             argc,
3118         char            **argv
3119 )
3120 {
3121         slap_overinst   *on = (slap_overinst *)be->bd_info;
3122         cache_manager*  cm = on->on_bi.bi_private;
3123
3124         /* Something for the cache database? */
3125         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3126                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3127                         argc, argv );
3128         return SLAP_CONF_UNKNOWN;
3129 }
3130
3131 static int
3132 pcache_db_init(
3133         BackendDB *be,
3134         ConfigReply *cr)
3135 {
3136         slap_overinst *on = (slap_overinst *)be->bd_info;
3137         cache_manager *cm;
3138         query_manager *qm;
3139
3140         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3141         on->on_bi.bi_private = cm;
3142
3143         qm = (query_manager*)ch_malloc(sizeof(query_manager));
3144
3145         cm->db = *be;
3146         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3147         cm->db.be_private = NULL;
3148         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
3149         cm->qm = qm;
3150         cm->numattrsets = 0;
3151         cm->num_entries_limit = 5;
3152         cm->num_cached_queries = 0;
3153         cm->max_entries = 0;
3154         cm->cur_entries = 0;
3155         cm->max_queries = 10000;
3156         cm->save_queries = 0;
3157         cm->check_cacheability = 0;
3158         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3159         cm->defer_db_open = 1;
3160         cm->cc_period = 1000;
3161         cm->cc_paused = 0;
3162         cm->cc_arg = NULL;
3163
3164         qm->attr_sets = NULL;
3165         qm->templates = NULL;
3166         qm->lru_top = NULL;
3167         qm->lru_bottom = NULL;
3168
3169         qm->qcfunc = query_containment;
3170         qm->crfunc = cache_replacement;
3171         qm->addfunc = add_query;
3172         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3173
3174         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3175         return 0;
3176 }
3177
3178 static int
3179 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3180 {
3181         assert( op->o_tag == LDAP_REQ_SEARCH );
3182
3183         if ( rs->sr_type == REP_SEARCH ) {
3184                 Attribute       *a;
3185
3186                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3187                 if ( a != NULL ) {
3188                         BerVarray       *valsp;
3189
3190                         assert( a->a_nvals != NULL );
3191
3192                         valsp = op->o_callback->sc_private;
3193                         assert( *valsp == NULL );
3194
3195                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3196                 }
3197         }
3198
3199         return 0;
3200 }
3201
3202 static int
3203 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3204 {
3205         assert( op->o_tag == LDAP_REQ_SEARCH );
3206
3207         if ( rs->sr_type == REP_SEARCH ) {
3208                 int     *countp = (int *)op->o_callback->sc_private;
3209
3210                 (*countp)++;
3211         }
3212
3213         return 0;
3214 }
3215
3216 static int
3217 pcache_db_open2(
3218         slap_overinst *on,
3219         ConfigReply *cr )
3220 {
3221         cache_manager   *cm = on->on_bi.bi_private;
3222         query_manager*  qm = cm->qm;
3223         int rc;
3224
3225         rc = backend_startup_one( &cm->db, cr );
3226         if ( rc == 0 ) {
3227                 cm->defer_db_open = 0;
3228         }
3229
3230         /* There is no runqueue in TOOL mode */
3231         if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
3232                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3233                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3234                         consistency_check, on,
3235                         "pcache_consistency", cm->db.be_suffix[0].bv_val );
3236                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3237
3238                 /* Cached database must have the rootdn */
3239                 if ( BER_BVISNULL( &cm->db.be_rootndn )
3240                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3241                 {
3242                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3243                                 "underlying database of type \"%s\"\n"
3244                                 "    serving naming context \"%s\"\n"
3245                                 "    has no \"rootdn\", required by \"proxycache\".\n",
3246                                 on->on_info->oi_orig->bi_type,
3247                                 cm->db.be_suffix[0].bv_val, 0 );
3248                         return 1;
3249                 }
3250
3251                 if ( cm->save_queries ) {
3252                         void            *thrctx = ldap_pvt_thread_pool_context();
3253                         Connection      conn = { 0 };
3254                         OperationBuffer opbuf;
3255                         Operation       *op;
3256                         slap_callback   cb = { 0 };
3257                         SlapReply       rs = { 0 };
3258                         BerVarray       vals = NULL;
3259                         Filter          f = { 0 }, f2 = { 0 };
3260                         AttributeAssertion      ava = ATTRIBUTEASSERTION_INIT;
3261                         AttributeName   attrs[ 2 ] = {{{ 0 }}};
3262
3263                         connection_fake_init( &conn, &opbuf, thrctx );
3264                         op = &opbuf.ob_op;
3265
3266                         op->o_bd = &cm->db;
3267
3268                         op->o_tag = LDAP_REQ_SEARCH;
3269                         op->o_protocol = LDAP_VERSION3;
3270                         cb.sc_response = pcache_cachedquery_open_cb;
3271                         cb.sc_private = &vals;
3272                         op->o_callback = &cb;
3273                         op->o_time = slap_get_time();
3274                         op->o_do_not_cache = 1;
3275                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
3276
3277                         op->o_dn = cm->db.be_rootdn;
3278                         op->o_ndn = cm->db.be_rootndn;
3279                         op->o_req_dn = cm->db.be_suffix[ 0 ];
3280                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3281
3282                         op->ors_scope = LDAP_SCOPE_BASE;
3283                         op->ors_deref = LDAP_DEREF_NEVER;
3284                         op->ors_slimit = 1;
3285                         op->ors_tlimit = SLAP_NO_LIMIT;
3286                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3287                         f.f_choice = LDAP_FILTER_PRESENT;
3288                         f.f_desc = ad_cachedQueryURL;
3289                         op->ors_filter = &f;
3290                         attrs[ 0 ].an_desc = ad_cachedQueryURL;
3291                         attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3292                         op->ors_attrs = attrs;
3293                         op->ors_attrsonly = 0;
3294
3295                         rc = op->o_bd->be_search( op, &rs );
3296                         if ( rc == LDAP_SUCCESS && vals != NULL ) {
3297                                 int     i;
3298
3299                                 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3300                                         if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3301                                                 cm->num_cached_queries++;
3302                                         }
3303                                 }
3304
3305                                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3306                         }
3307
3308                         /* count cached entries */
3309                         f.f_choice = LDAP_FILTER_NOT;
3310                         f.f_not = &f2;
3311                         f2.f_choice = LDAP_FILTER_EQUALITY;
3312                         f2.f_ava = &ava;
3313                         f2.f_av_desc = slap_schema.si_ad_objectClass;
3314                         BER_BVSTR( &f2.f_av_value, "glue" );
3315                         ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3316
3317                         op->ors_slimit = SLAP_NO_LIMIT;
3318                         op->ors_scope = LDAP_SCOPE_SUBTREE;
3319                         op->ors_attrs = slap_anlist_no_attrs;
3320
3321                         op->o_callback->sc_response = pcache_cachedquery_count_cb;
3322                         rs.sr_nentries = 0;
3323                         op->o_callback->sc_private = &rs.sr_nentries;
3324
3325                         rc = op->o_bd->be_search( op, &rs );
3326
3327                         cm->cur_entries = rs.sr_nentries;
3328
3329                         /* ignore errors */
3330                         rc = 0;
3331                 }
3332         }
3333         return rc;
3334 }
3335
3336 static int
3337 pcache_db_open(
3338         BackendDB *be,
3339         ConfigReply *cr )
3340 {
3341         slap_overinst   *on = (slap_overinst *)be->bd_info;
3342         cache_manager   *cm = on->on_bi.bi_private;
3343         query_manager*  qm = cm->qm;
3344         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3345
3346         /* check attr sets */
3347         for ( i = 0; i < cm->numattrsets; i++) {
3348                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3349                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3350                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3351                                 rf++;
3352
3353                         } else {
3354                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3355                         }
3356                         ncf++;
3357
3358                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3359                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3360                         nrf++;
3361                 }
3362         }
3363
3364         if ( ncf || rf || nrf ) {
3365                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3366                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3367                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3368
3369                 if ( rf > 0 ) {
3370                         return 1;
3371                 }
3372         }
3373
3374         /* need to inherit something from the original database... */
3375         cm->db.be_def_limit = be->be_def_limit;
3376         cm->db.be_limits = be->be_limits;
3377         cm->db.be_acl = be->be_acl;
3378         cm->db.be_dfltaccess = be->be_dfltaccess;
3379
3380         if ( SLAP_DBMONITORING( be ) ) {
3381                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3382
3383         } else {
3384                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3385         }
3386
3387         if ( !cm->defer_db_open )
3388                 rc = pcache_db_open2( on, cr );
3389
3390         return rc;
3391 }
3392
3393 static void
3394 pcache_free_qbase( void *v )
3395 {
3396         Qbase *qb = v;
3397         int i;
3398
3399         for (i=0; i<3; i++)
3400                 tavl_free( qb->scopes[i], NULL );
3401         ch_free( qb );
3402 }
3403
3404 static int
3405 pcache_db_close(
3406         BackendDB *be,
3407         ConfigReply *cr
3408 )
3409 {
3410         slap_overinst *on = (slap_overinst *)be->bd_info;
3411         cache_manager *cm = on->on_bi.bi_private;
3412         query_manager *qm = cm->qm;
3413         QueryTemplate *tm;
3414         int i, rc = 0;
3415
3416         if ( cm->save_queries ) {
3417                 CachedQuery     *qc;
3418                 BerVarray       vals = NULL;
3419
3420                 void            *thrctx;
3421                 Connection      conn = { 0 };
3422                 OperationBuffer opbuf;
3423                 Operation       *op;
3424                 slap_callback   cb = { 0 };
3425
3426                 SlapReply       rs = { REP_RESULT };
3427                 Modifications   mod = {{ 0 }};
3428
3429                 thrctx = ldap_pvt_thread_pool_context();
3430
3431                 connection_fake_init( &conn, &opbuf, thrctx );
3432                 op = &opbuf.ob_op;
3433
3434                 if ( qm->templates != NULL ) {
3435                         for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3436                                 for ( qc = tm->query; qc; qc = qc->next ) {
3437                                         struct berval   bv;
3438
3439                                         if ( query2url( op, qc, &bv ) == 0 ) {
3440                                                 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3441                                         }
3442                                 }
3443                         }
3444                 }
3445
3446                 op->o_bd = &cm->db;
3447                 op->o_dn = cm->db.be_rootdn;
3448                 op->o_ndn = cm->db.be_rootndn;
3449
3450                 op->o_tag = LDAP_REQ_MODIFY;
3451                 op->o_protocol = LDAP_VERSION3;
3452                 cb.sc_response = slap_null_cb;
3453                 op->o_callback = &cb;
3454                 op->o_time = slap_get_time();
3455                 op->o_do_not_cache = 1;
3456                 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3457
3458                 op->o_req_dn = op->o_bd->be_suffix[0];
3459                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3460
3461                 mod.sml_op = LDAP_MOD_REPLACE;
3462                 mod.sml_flags = 0;
3463                 mod.sml_desc = ad_cachedQueryURL;
3464                 mod.sml_type = ad_cachedQueryURL->ad_cname;
3465                 mod.sml_values = vals;
3466                 mod.sml_nvalues = NULL;
3467                 mod.sml_numvals = 1;
3468                 mod.sml_next = NULL;
3469                 Debug( pcache_debug,
3470                         "%sSETTING CACHED QUERY URLS\n",
3471                         vals == NULL ? "RE" : "", 0, 0 );
3472
3473                 op->orm_modlist = &mod;
3474
3475                 op->o_bd->be_modify( op, &rs );
3476
3477                 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3478         }
3479
3480         /* cleanup stuff inherited from the original database... */
3481         cm->db.be_limits = NULL;
3482         cm->db.be_acl = NULL;
3483
3484         /* stop the thread ... */
3485         if ( cm->cc_arg ) {
3486                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3487                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3488                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3489                 }
3490                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3491                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3492         }
3493
3494         if ( cm->db.bd_info->bi_db_close ) {
3495                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3496         }
3497         while ( (tm = qm->templates) != NULL ) {
3498                 CachedQuery *qc, *qn;
3499                 qm->templates = tm->qmnext;
3500                 for ( qc = tm->query; qc; qc = qn ) {
3501                         qn = qc->next;
3502                         free_query( qc );
3503                 }
3504                 avl_free( tm->qbase, pcache_free_qbase );
3505                 free( tm->querystr.bv_val );
3506                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3507                 free( tm->t_attrs.attrs );
3508                 free( tm );
3509         }
3510
3511         for ( i=0; i<cm->numattrsets; i++ ) {
3512                 free( qm->attr_sets[i].attrs );
3513         }
3514         free( qm->attr_sets );
3515         qm->attr_sets = NULL;
3516
3517         return rc;
3518 }
3519
3520 static int
3521 pcache_db_destroy(
3522         BackendDB *be,
3523         ConfigReply *cr
3524 )
3525 {
3526         slap_overinst *on = (slap_overinst *)be->bd_info;
3527         cache_manager *cm = on->on_bi.bi_private;
3528         query_manager *qm = cm->qm;
3529
3530         if ( cm->db.be_private != NULL ) {
3531                 backend_stopdown_one( &cm->db );
3532         }
3533
3534         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3535         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3536         free( qm );
3537         free( cm );
3538
3539         return 0;
3540 }
3541
3542 #ifdef PCACHE_CONTROL_PRIVDB
3543 /*
3544         Control ::= SEQUENCE {
3545              controlType             LDAPOID,
3546              criticality             BOOLEAN DEFAULT FALSE,
3547              controlValue            OCTET STRING OPTIONAL }
3548
3549         controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3550
3551  * criticality must be TRUE; controlValue must be absent.
3552  */
3553 static int
3554 parse_privdb_ctrl(
3555         Operation       *op,
3556         SlapReply       *rs,
3557         LDAPControl     *ctrl )
3558 {
3559         if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3560                 rs->sr_text = "privateDB control specified multiple times";
3561                 return LDAP_PROTOCOL_ERROR;
3562         }
3563
3564         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3565                 rs->sr_text = "privateDB control value not absent";
3566                 return LDAP_PROTOCOL_ERROR;
3567         }
3568
3569         if ( !ctrl->ldctl_iscritical ) {
3570                 rs->sr_text = "privateDB control criticality required";
3571                 return LDAP_PROTOCOL_ERROR;
3572         }
3573
3574         op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3575
3576         return LDAP_SUCCESS;
3577 }
3578
3579 static char *extops[] = {
3580         LDAP_EXOP_MODIFY_PASSWD,
3581         NULL
3582 };
3583 #endif /* PCACHE_CONTROL_PRIVDB */
3584
3585 #ifdef PCACHE_EXOP_QUERY_DELETE
3586 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3587
3588 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3589 #define LDAP_TAG_EXOP_QUERY_DELETE_DN   ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3590 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3591
3592 /*
3593         ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3594              requestName      [0] LDAPOID,
3595              requestValue     [1] OCTET STRING OPTIONAL }
3596
3597         requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3598
3599         requestValue ::= SEQUENCE { CHOICE {
3600                   baseDN           [0] LDAPDN
3601                   entryDN          [1] LDAPDN },
3602              queryID          [2] OCTET STRING (SIZE(16))
3603                   -- constrained to UUID }
3604
3605  * Either baseDN or entryDN must be present, to allow database selection.
3606  *
3607  * 1. if baseDN and queryID are present, then the query corresponding
3608  *    to queryID is deleted;
3609  * 2. if baseDN is present and queryID is absent, then all queries
3610  *    are deleted;
3611  * 3. if entryDN is present and queryID is absent, then all queries
3612  *    corresponding to the queryID values present in entryDN are deleted;
3613  * 4. if entryDN and queryID are present, then all queries
3614  *    corresponding to the queryID values present in entryDN are deleted,
3615  *    but only if the value of queryID is contained in the entry;
3616  *
3617  * Currently, only 1, 3 and 4 are implemented.  2 can be obtained by either
3618  * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3619  * or by removing the database files.
3620
3621         ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3622              COMPONENTS OF LDAPResult,
3623              responseName     [10] LDAPOID OPTIONAL,
3624              responseValue    [11] OCTET STRING OPTIONAL }
3625
3626  * responseName and responseValue must be absent.
3627  */
3628
3629 /*
3630  * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3631  *   or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3632  * - if ndn != NULL, it is set to the normalized DN in the request
3633  *   corresponding to either the baseDN or the entryDN, according
3634  *   to *tagp; memory is malloc'ed on the Operation's slab, and must
3635  *   be freed by the caller.
3636  * - if uuid != NULL, it is set to point to the normalized UUID;
3637  *   memory is malloc'ed on the Operation's slab, and must
3638  *   be freed by the caller.
3639  */
3640 static int
3641 pcache_parse_query_delete(
3642         struct berval   *in,
3643         ber_tag_t       *tagp,
3644         struct berval   *ndn,
3645         struct berval   *uuid,
3646         const char      **text,
3647         void            *ctx )
3648 {
3649         int                     rc = LDAP_SUCCESS;
3650         ber_tag_t               tag;
3651         ber_len_t               len = -1;
3652         BerElementBuffer        berbuf;
3653         BerElement              *ber = (BerElement *)&berbuf;
3654         struct berval           reqdata = BER_BVNULL;
3655
3656         *text = NULL;
3657
3658         if ( ndn ) {
3659                 BER_BVZERO( ndn );
3660         }
3661
3662         if ( uuid ) {
3663                 BER_BVZERO( uuid );
3664         }
3665
3666         if ( in == NULL || in->bv_len == 0 ) {
3667                 *text = "empty request data field in queryDelete exop";
3668                 return LDAP_PROTOCOL_ERROR;
3669         }
3670
3671         ber_dupbv_x( &reqdata, in, ctx );
3672
3673         /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3674         ber_init2( ber, &reqdata, 0 );
3675
3676         tag = ber_scanf( ber, "{" /*}*/ );
3677
3678         if ( tag == LBER_ERROR ) {
3679                 Debug( LDAP_DEBUG_TRACE,
3680                         "pcache_parse_query_delete: decoding error.\n",
3681                         0, 0, 0 );
3682                 goto decoding_error;
3683         }
3684
3685         tag = ber_peek_tag( ber, &len );
3686         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3687                 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3688         {
3689                 *tagp = tag;
3690
3691                 if ( ndn != NULL ) {
3692                         struct berval   dn;
3693
3694                         tag = ber_scanf( ber, "m", &dn );
3695                         if ( tag == LBER_ERROR ) {
3696                                 Debug( LDAP_DEBUG_TRACE,
3697                                         "pcache_parse_query_delete: DN parse failed.\n",
3698                                         0, 0, 0 );
3699                                 goto decoding_error;
3700                         }
3701
3702                         rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3703                         if ( rc != LDAP_SUCCESS ) {
3704                                 *text = "invalid DN in queryDelete exop request data";
3705                                 goto done;
3706                         }
3707
3708                 } else {
3709                         tag = ber_scanf( ber, "x" /* "m" */ );
3710                         if ( tag == LBER_DEFAULT ) {
3711                                 goto decoding_error;
3712                         }
3713                 }
3714
3715                 tag = ber_peek_tag( ber, &len );
3716         }
3717
3718         if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3719                 if ( uuid != NULL ) {
3720                         struct berval   bv;
3721                         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3722
3723                         tag = ber_scanf( ber, "m", &bv );
3724                         if ( tag == LBER_ERROR ) {
3725                                 Debug( LDAP_DEBUG_TRACE,
3726                                         "pcache_parse_query_delete: UUID parse failed.\n",
3727                                         0, 0, 0 );
3728                                 goto decoding_error;
3729                         }
3730
3731                         if ( bv.bv_len != 16 ) {
3732                                 Debug( LDAP_DEBUG_TRACE,
3733                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3734                                         (unsigned long)bv.bv_len, 0, 0 );
3735                                 goto decoding_error;
3736                         }
3737
3738                         rc = lutil_uuidstr_from_normalized(
3739                                 bv.bv_val, bv.bv_len,
3740                                 uuidbuf, sizeof( uuidbuf ) );
3741                         if ( rc == -1 ) {
3742                                 goto decoding_error;
3743                         }
3744                         ber_str2bv( uuidbuf, rc, 1, uuid );
3745                         rc = LDAP_SUCCESS;
3746
3747                 } else {
3748                         tag = ber_skip_tag( ber, &len );
3749                         if ( tag == LBER_DEFAULT ) {
3750                                 goto decoding_error;
3751                         }
3752
3753                         if ( len != 16 ) {
3754                                 Debug( LDAP_DEBUG_TRACE,
3755                                         "pcache_parse_query_delete: invalid UUID length %lu.\n",
3756                                         (unsigned long)len, 0, 0 );
3757                                 goto decoding_error;
3758                         }
3759                 }
3760
3761                 tag = ber_peek_tag( ber, &len );
3762         }
3763
3764         if ( tag != LBER_DEFAULT || len != 0 ) {
3765 decoding_error:;
3766                 Debug( LDAP_DEBUG_TRACE,
3767                         "pcache_parse_query_delete: decoding error\n",
3768                         0, 0, 0 );
3769                 rc = LDAP_PROTOCOL_ERROR;
3770                 *text = "queryDelete data decoding error";
3771
3772 done:;
3773                 if ( ndn && !BER_BVISNULL( ndn ) ) {
3774                         slap_sl_free( ndn->bv_val, ctx );
3775                         BER_BVZERO( ndn );
3776                 }
3777
3778                 if ( uuid && !BER_BVISNULL( uuid ) ) {
3779                         slap_sl_free( uuid->bv_val, ctx );
3780                         BER_BVZERO( uuid );
3781                 }
3782         }
3783
3784         if ( !BER_BVISNULL( &reqdata ) ) {
3785                 ber_memfree_x( reqdata.bv_val, ctx );
3786         }
3787
3788         return rc;
3789 }
3790
3791 static int
3792 pcache_exop_query_delete(
3793         Operation       *op,
3794         SlapReply       *rs )
3795 {
3796         BackendDB       *bd = op->o_bd;
3797
3798         struct berval   uuid = BER_BVNULL,
3799                         *uuidp = NULL;
3800         char            buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3801         int             len = 0;
3802         ber_tag_t       tag = LBER_DEFAULT;
3803
3804         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3805                 uuidp = &uuid;
3806         }
3807
3808         rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3809                 &tag, &op->o_req_ndn, uuidp,
3810                 &rs->sr_text, op->o_tmpmemctx );
3811         if ( rs->sr_err != LDAP_SUCCESS ) {
3812                 return rs->sr_err;
3813         }
3814
3815         if ( LogTest( LDAP_DEBUG_STATS ) ) {
3816                 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3817                 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3818
3819                 if ( !BER_BVISNULL( &uuid ) ) {
3820                         snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3821                 }
3822
3823                 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3824                         op->o_log_prefix, buf, 0 );
3825         }
3826         op->o_req_dn = op->o_req_ndn;
3827
3828         op->o_bd = select_backend( &op->o_req_ndn, 0 );
3829         rs->sr_err = backend_check_restrictions( op, rs,
3830                 (struct berval *)&pcache_exop_QUERY_DELETE );
3831         if ( rs->sr_err != LDAP_SUCCESS ) {
3832                 goto done;
3833         }
3834
3835         if ( op->o_bd->be_extended == NULL ) {
3836                 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3837                         "backend does not support extended operations" );
3838                 goto done;
3839         }
3840
3841         op->o_bd->be_extended( op, rs );
3842
3843 done:;
3844         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3845                 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3846                 BER_BVZERO( &op->o_req_ndn );
3847                 BER_BVZERO( &op->o_req_dn );
3848         }
3849
3850         if ( !BER_BVISNULL( &uuid ) ) {
3851                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3852         }
3853
3854         op->o_bd = bd;
3855
3856         return rs->sr_err;
3857 }
3858
3859 static int
3860 pcache_op_extended( Operation *op, SlapReply *rs )
3861 {
3862         slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
3863         cache_manager   *cm = on->on_bi.bi_private;
3864
3865 #ifdef PCACHE_CONTROL_PRIVDB
3866         if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3867                 return pcache_op_privdb( op, rs );
3868         }
3869 #endif /* PCACHE_CONTROL_PRIVDB */
3870
3871         if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3872                 struct berval   uuid = BER_BVNULL;
3873                 ber_tag_t       tag = LBER_DEFAULT;
3874
3875                 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3876                         &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3877                 assert( rs->sr_err == LDAP_SUCCESS );
3878
3879                 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3880                         /* remove all queries related to the selected entry */
3881                         rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3882                                 cm, &op->o_req_ndn, &uuid );
3883
3884                 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3885                         if ( !BER_BVISNULL( &uuid ) ) {
3886                                 /* remove the selected query */
3887                                 rs->sr_err = pcache_remove_query_from_cache( op,
3888                                         cm, &uuid );
3889
3890                         } else {
3891                                 /* TODO: remove all queries */
3892                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3893                                 rs->sr_text = "deletion of all queries not implemented";
3894                         }
3895                 }
3896
3897                 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3898         }
3899
3900         return rs->sr_err;
3901 }
3902 #endif /* PCACHE_EXOP_QUERY_DELETE */
3903
3904 static slap_overinst pcache;
3905
3906 static char *obsolete_names[] = {
3907         "proxycache",
3908         NULL
3909 };
3910
3911 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3912 static
3913 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3914 int
3915 pcache_initialize()
3916 {
3917         int i, code;
3918         struct berval debugbv = BER_BVC("pcache");
3919
3920         code = slap_loglevel_get( &debugbv, &pcache_debug );
3921         if ( code ) {
3922                 return code;
3923         }
3924
3925 #ifdef PCACHE_CONTROL_PRIVDB
3926         code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3927                 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3928                 parse_privdb_ctrl, &privDB_cid );
3929         if ( code != LDAP_SUCCESS ) {
3930                 Debug( LDAP_DEBUG_ANY,
3931                         "pcache_initialize: failed to register control %s (%d)\n",
3932                         PCACHE_CONTROL_PRIVDB, code, 0 );
3933                 return code;
3934         }
3935 #endif /* PCACHE_CONTROL_PRIVDB */
3936
3937 #ifdef PCACHE_EXOP_QUERY_DELETE
3938         code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3939                 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3940                 0 );
3941         if ( code != LDAP_SUCCESS ) {
3942                 Debug( LDAP_DEBUG_ANY,
3943                         "pcache_initialize: unable to register queryDelete exop: %d.\n",
3944                         code, 0, 0 );
3945                 return code;
3946         }
3947 #endif /* PCACHE_EXOP_QUERY_DELETE */
3948
3949         for ( i = 0; as[i].desc != NULL; i++ ) {
3950                 code = register_at( as[i].desc, as[i].adp, 0 );
3951                 if ( code ) {
3952                         Debug( LDAP_DEBUG_ANY,
3953                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3954                         return code;
3955                 }
3956                 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3957         }
3958
3959         pcache.on_bi.bi_type = "pcache";
3960         pcache.on_bi.bi_obsolete_names = obsolete_names;
3961         pcache.on_bi.bi_db_init = pcache_db_init;
3962         pcache.on_bi.bi_db_config = pcache_db_config;
3963         pcache.on_bi.bi_db_open = pcache_db_open;
3964         pcache.on_bi.bi_db_close = pcache_db_close;
3965         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3966
3967         pcache.on_bi.bi_op_search = pcache_op_search;
3968 #ifdef PCACHE_CONTROL_PRIVDB
3969         pcache.on_bi.bi_op_bind = pcache_op_privdb;
3970         pcache.on_bi.bi_op_compare = pcache_op_privdb;
3971         pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3972         pcache.on_bi.bi_op_modify = pcache_op_privdb;
3973         pcache.on_bi.bi_op_add = pcache_op_privdb;
3974         pcache.on_bi.bi_op_delete = pcache_op_privdb;
3975 #endif /* PCACHE_CONTROL_PRIVDB */
3976 #ifdef PCACHE_EXOP_QUERY_DELETE
3977         pcache.on_bi.bi_extended = pcache_op_extended;
3978 #elif defined( PCACHE_CONTROL_PRIVDB )
3979         pcache.on_bi.bi_extended = pcache_op_privdb;
3980 #endif
3981
3982         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3983
3984         pcache.on_bi.bi_cf_ocs = pcocs;
3985
3986         code = config_register_schema( pccfg, pcocs );
3987         if ( code ) return code;
3988
3989         return overlay_register( &pcache );
3990 }
3991
3992 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3993 int init_module(int argc, char *argv[]) {
3994         return pcache_initialize();
3995 }
3996 #endif
3997
3998 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */