]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/pcache.c
plug leak
[openldap] / servers / slapd / overlays / pcache.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2003-2007 The OpenLDAP Foundation.
5  * Portions Copyright 2003 IBM Corporation.
6  * Portions Copyright 2003 Symas Corporation.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by Apurva Kumar for inclusion
19  * in OpenLDAP Software and subsequently rewritten by Howard Chu.
20  */
21
22 #include "portable.h"
23
24 #ifdef SLAPD_OVER_PROXYCACHE
25
26 #include <stdio.h>
27
28 #include <ac/string.h>
29 #include <ac/time.h>
30
31 #include "slap.h"
32 #include "lutil.h"
33 #include "ldap_rq.h"
34 #include "avl.h"
35
36 #include "config.h"
37
38 /* query cache structs */
39 /* query */
40
41 typedef struct Query_s {
42         Filter*         filter;         /* Search Filter */
43         struct berval   base;           /* Search Base */
44         int             scope;          /* Search scope */
45 } Query;
46
47 struct query_template_s;
48
49 typedef struct Qbase_s {
50         Avlnode *scopes[4];             /* threaded AVL trees of cached queries */
51         struct berval base;
52         int queries;
53 } Qbase;
54
55 /* struct representing a cached query */
56 typedef struct cached_query_s {
57         Filter                                  *filter;
58         Filter                                  *first;
59         Qbase                                   *qbase;
60         int                                             scope;
61         struct berval                   q_uuid;         /* query identifier */
62         struct query_template_s         *qtemp; /* template of the query */
63         time_t                          expiry_time;    /* time till the query is considered valid */
64         struct cached_query_s           *next;          /* next query in the template */
65         struct cached_query_s           *prev;          /* previous query in the template */
66         struct cached_query_s           *lru_up;        /* previous query in the LRU list */
67         struct cached_query_s           *lru_down;      /* next query in the LRU list */
68 } CachedQuery;
69
70 /*
71  * URL representation:
72  *
73  * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
74  *
75  * <base> ::= CachedQuery.qbase->base
76  * <scope> ::= CachedQuery.scope
77  * <filter> ::= filter2bv(CachedQuery.filter)
78  * <uuid> ::= CachedQuery.q_uuid
79  * <template> ::= CachedQuery.qtemp->querystr           [FIXME: better give it an ID?]
80  * <attrset> ::= CachedQuery.qtemp->attr_set_index      [FIXME: better give it an ID?]
81  * <expiry> ::= CachedQuery.expiry_time
82  *
83  * quick hack: parse URI, call add_query() and then fix
84  * CachedQuery.expiry_time and CachedQuery.q_uuid
85  */
86
87 /*
88  * Represents a set of projected attributes.
89  */
90
91 struct attr_set {
92         struct query_template_s *templates;
93         AttributeName*  attrs;          /* specifies the set */
94         unsigned        flags;
95 #define PC_CONFIGURED   (0x1)
96 #define PC_REFERENCED   (0x2)
97 #define PC_GOT_OC               (0x4)
98         int             count;          /* number of attributes */
99 };
100
101 /* struct representing a query template
102  * e.g. template string = &(cn=)(mail=)
103  */
104 typedef struct query_template_s {
105         struct query_template_s *qtnext;
106         struct query_template_s *qmnext;
107
108         Avlnode*                qbase;
109         CachedQuery*    query;          /* most recent query cached for the template */
110         CachedQuery*    query_last;     /* oldest query cached for the template */
111         ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
112         struct berval   querystr;       /* Filter string corresponding to the QT */
113
114         int             attr_set_index; /* determines the projected attributes */
115         int             no_of_queries;  /* Total number of queries in the template */
116         time_t          ttl;            /* TTL for the queries of this template */
117         time_t          negttl;         /* TTL for negative results */
118         struct attr_set t_attrs;        /* filter attrs + attr_set */
119 } QueryTemplate;
120
121 struct query_manager_s;
122
123 /* prototypes for functions for 1) query containment
124  * 2) query addition, 3) cache replacement
125  */
126 typedef CachedQuery *   (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
127 typedef CachedQuery *   (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
128 typedef void    (CRfunc)(struct query_manager_s*, struct berval * );
129
130 /* LDAP query cache */
131 typedef struct query_manager_s {
132         struct attr_set*        attr_sets;              /* possible sets of projected attributes */
133         QueryTemplate*          templates;              /* cacheable templates */
134
135         CachedQuery*            lru_top;                /* top and bottom of LRU list */
136         CachedQuery*            lru_bottom;
137
138         ldap_pvt_thread_mutex_t         lru_mutex;      /* mutex for accessing LRU list */
139
140         /* Query cache methods */
141         QCfunc                  *qcfunc;                        /* Query containment*/
142         CRfunc                  *crfunc;                        /* cache replacement */
143         AddQueryfunc    *addfunc;                       /* add query */
144 } query_manager;
145
146 /* LDAP query cache manager */
147 typedef struct cache_manager_s {
148         BackendDB       db;     /* underlying database */
149         unsigned long   num_cached_queries;             /* total number of cached queries */
150         unsigned long   max_queries;                    /* upper bound on # of cached queries */
151         int             save_queries;                   /* save cached queries across restarts */
152         int     numattrsets;                    /* number of attribute sets */
153         int     cur_entries;                    /* current number of entries cached */
154         int     max_entries;                    /* max number of entries cached */
155         int     num_entries_limit;              /* max # of entries in a cacheable query */
156
157         char    response_cb;                    /* install the response callback
158                                                  * at the tail of the callback list */
159 #define PCACHE_RESPONSE_CB_HEAD 0
160 #define PCACHE_RESPONSE_CB_TAIL 1
161
162         time_t  cc_period;              /* interval between successive consistency checks (sec) */
163         int     cc_paused;
164         void    *cc_arg;
165
166         ldap_pvt_thread_mutex_t         cache_mutex;
167
168         query_manager*   qm;    /* query cache managed by the cache manager */
169 } cache_manager;
170
171 static int pcache_debug;
172
173 static AttributeDescription *ad_queryid, *ad_cachedQueryURL;
174 static struct {
175         char    *desc;
176         AttributeDescription **adp;
177 } as[] = {
178         { "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
179                 "DESC 'list of queries the entry belongs to' "
180                 "EQUALITY octetStringMatch "
181                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
182                 "NO-USER-MODIFICATION USAGE directoryOperation )",
183                 &ad_queryid },
184         { "(1.3.6.1.4.1.4203.666.1.999999 NAME 'cachedQueryURL' "
185                 "DESC 'URI describing a cached query' "
186                 "EQUALITY caseExactMatch "
187                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
188                 "NO-USER-MODIFICATION USAGE directoryOperation )",
189                 &ad_cachedQueryURL },
190         { NULL }
191 };
192
193 static int
194 filter2template(
195         Operation               *op,
196         Filter                  *f,
197         struct                  berval *fstr,
198         AttributeName**         filter_attrs,
199         int*                    filter_cnt,
200         int*                    filter_got_oc );
201
202 static CachedQuery *
203 add_query(
204         Operation *op,
205         query_manager* qm,
206         Query* query,
207         QueryTemplate *templ,
208         int positive);
209
210 /*
211  * Turn a cached query into its URL representation
212  */
213 static int
214 query2url( CachedQuery *q, struct berval *urlbv )
215 {
216         struct berval   bv_scope,
217                         bv_filter;
218         char            attrset_buf[ 32 ],
219                         expiry_buf[ 32 ],
220                         *ptr;
221         ber_len_t       attrset_len,
222                         expiry_len;
223
224         ldap_pvt_scope2bv( q->scope, &bv_scope );
225         filter2bv( q->filter, &bv_filter );
226         attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
227                 "%lu", (unsigned long)q->qtemp->attr_set_index );
228         expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
229                 "%lu", (unsigned long)q->expiry_time );
230
231         urlbv->bv_len = STRLENOF( "ldap:///" )
232                 + q->qbase->base.bv_len
233                 + STRLENOF( "??" )
234                 + bv_scope.bv_len
235                 + STRLENOF( "?" )
236                 + bv_filter.bv_len
237                 + STRLENOF( "?x-uuid=" )
238                 + q->q_uuid.bv_len
239                 + STRLENOF( ",x-attrset=" )
240                 + attrset_len
241                 + STRLENOF( ",x-expiry=" )
242                 + expiry_len;
243         ptr = urlbv->bv_val = ch_malloc( urlbv->bv_len + 1 );
244         ptr = lutil_strcopy( ptr, "ldap:///" );
245         ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
246         ptr = lutil_strcopy( ptr, "??" );
247         ptr = lutil_strcopy( ptr, bv_scope.bv_val );
248         ptr = lutil_strcopy( ptr, "?" );
249         ptr = lutil_strcopy( ptr, bv_filter.bv_val );
250         ptr = lutil_strcopy( ptr, "?x-uuid=" );
251         ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
252         ptr = lutil_strcopy( ptr, ",x-attrset=" );
253         ptr = lutil_strcopy( ptr, attrset_buf );
254         ptr = lutil_strcopy( ptr, ",x-expiry=" );
255         ptr = lutil_strcopy( ptr, expiry_buf );
256
257         ber_memfree( bv_filter.bv_val );
258
259         return 0;
260 }
261
262 /*
263  * Turn an URL representing a formerly cached query into a cached query,
264  * and try to cache it
265  */
266 static int
267 url2query(
268         char            *url,
269         Operation       *op,
270         query_manager   *qm )
271 {
272         Query           query = { 0 };
273         QueryTemplate   *qt;
274         CachedQuery     *cq;
275         LDAPURLDesc     *lud = NULL;
276         struct berval   base,
277                         tempstr = BER_BVNULL,
278                         uuid;
279         int             attrset;
280         time_t          expiry_time;
281         int             i,
282                         got_uuid = 0,
283                         got_attrset = 0,
284                         got_expiry = 0,
285                         rc = 0;
286
287         rc = ldap_url_parse( url, &lud );
288         if ( rc != LDAP_URL_SUCCESS ) {
289                 return -1;
290         }
291
292         /* non-allowed fields */
293         if ( lud->lud_host != NULL ) {
294                 rc = 1;
295                 goto error;
296         }
297
298         if ( lud->lud_attrs != NULL ) {
299                 rc = 1;
300                 goto error;
301         }
302
303         /* be pedantic */
304         if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
305                 rc = 1;
306                 goto error;
307         }
308
309         /* required fields */
310         if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
311                 rc = 1;
312                 goto error;
313         }
314
315         switch ( lud->lud_scope ) {
316         case LDAP_SCOPE_BASE:
317         case LDAP_SCOPE_ONELEVEL:
318         case LDAP_SCOPE_SUBTREE:
319         case LDAP_SCOPE_SUBORDINATE:
320                 break;
321
322         default:
323                 rc = 1;
324                 goto error;
325         }
326
327         if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
328                 rc = 1;
329                 goto error;
330         }
331
332         if ( lud->lud_exts == NULL ) {
333                 rc = 1;
334                 goto error;
335         }
336
337         for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
338                 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
339                         ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &uuid );
340                         if ( rc ) {
341                                 goto error;
342                         }
343                         got_uuid = 1;
344
345                 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
346                         rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
347                         if ( rc ) {
348                                 goto error;
349                         }
350                         got_attrset = 1;
351
352                 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
353                         unsigned long l;
354
355                         rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
356                         if ( rc ) {
357                                 goto error;
358                         }
359                         expiry_time = (time_t)l;
360                         got_expiry = 1;
361
362                         /* ignore expired queries */
363                         if ( expiry_time <= slap_get_time()) {
364                                 rc = 0;
365                                 goto error;
366                         }
367
368                 } else {
369                         rc = -1;
370                         goto error;
371                 }
372         }
373
374         if ( !got_uuid ) {
375                 rc = 1;
376                 goto error;
377         }
378
379         if ( !got_attrset ) {
380                 rc = 1;
381                 goto error;
382         }
383
384         if ( !got_expiry ) {
385                 rc = 1;
386                 goto error;
387         }
388
389         ber_str2bv( lud->lud_dn, 0, 0, &base );
390         rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
391         if ( rc != LDAP_SUCCESS ) {
392                 goto error;
393         }
394         query.scope = lud->lud_scope;
395         query.filter = str2filter( lud->lud_filter );
396
397         tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
398         tempstr.bv_len = 0;
399         if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
400                 ch_free( tempstr.bv_val );
401                 rc = -1;
402                 goto error;
403         }
404
405         /* check for query containment */
406         qt = qm->attr_sets[attrset].templates;
407         for ( ; qt; qt = qt->qtnext ) {
408                 /* find if template i can potentially answer tempstr */
409                 if ( bvmatch( &qt->querystr, &tempstr ) ) {
410                         break;
411                 }
412         }
413
414         if ( qt == NULL ) {
415                 rc = 1;
416                 goto error;
417         }
418
419
420         cq = add_query( op, qm, &query, qt, 1 );
421         if ( cq != NULL ) {
422                 cq->expiry_time = expiry_time;
423                 ber_dupbv( &cq->q_uuid, &uuid );
424                 /* it's now into cq->filter */
425                 query.filter = NULL;
426
427         } else {
428                 rc = 1;
429         }
430
431 error:;
432         if ( query.filter != NULL ) filter_free( query.filter );
433         if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
434         if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
435         if ( lud != NULL ) ldap_free_urldesc( lud );
436
437         return rc;
438 }
439
440 /* Return 1 for an added entry, else 0 */
441 static int
442 merge_entry(
443         Operation               *op,
444         Entry                   *e,
445         struct berval*          query_uuid )
446 {
447         int             rc;
448         Modifications* modlist = NULL;
449         const char*     text = NULL;
450         Attribute               *attr;
451         char                    textbuf[SLAP_TEXT_BUFLEN];
452         size_t                  textlen = sizeof(textbuf);
453
454         SlapReply sreply = {REP_RESULT};
455
456         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
457
458         attr = e->e_attrs;
459         e->e_attrs = NULL;
460
461         /* add queryid attribute */
462         attr_merge_one( e, ad_queryid, query_uuid, NULL );
463
464         /* append the attribute list from the fetched entry */
465         e->e_attrs->a_next = attr;
466
467         op->o_tag = LDAP_REQ_ADD;
468         op->o_protocol = LDAP_VERSION3;
469         op->o_callback = &cb;
470         op->o_time = slap_get_time();
471         op->o_do_not_cache = 1;
472
473         op->ora_e = e;
474         op->o_req_dn = e->e_name;
475         op->o_req_ndn = e->e_nname;
476         rc = op->o_bd->be_add( op, &sreply );
477
478         if ( rc != LDAP_SUCCESS ) {
479                 if ( rc == LDAP_ALREADY_EXISTS ) {
480                         slap_entry2mods( e, &modlist, &text, textbuf, textlen );
481                         modlist->sml_op = LDAP_MOD_ADD;
482                         op->o_tag = LDAP_REQ_MODIFY;
483                         op->orm_modlist = modlist;
484                         op->o_bd->be_modify( op, &sreply );
485                         slap_mods_free( modlist, 1 );
486                 } else if ( rc == LDAP_REFERRAL ||
487                                         rc == LDAP_NO_SUCH_OBJECT ) {
488                         syncrepl_add_glue( op, e );
489                         e = NULL;
490                         rc = 1;
491                 }
492                 if ( e ) {
493                         entry_free( e );
494                         rc = 0;
495                 }
496         } else {
497                 if ( op->ora_e == e )
498                         be_entry_release_w( op, e );
499                 rc = 1;
500         }
501
502         return rc;
503 }
504
505 /* Length-ordered sort on normalized DNs */
506 static int pcache_dn_cmp( const void *v1, const void *v2 )
507 {
508         const Qbase *q1 = v1, *q2 = v2;
509
510         int rc = q1->base.bv_len - q2->base.bv_len;
511         if ( rc == 0 )
512                 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
513         return rc;
514 }
515
516 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
517 {
518         int len, dif;
519         dif = bv1->bv_len - bv2->bv_len;
520         len = bv1->bv_len;
521         if ( dif > 0 ) len -= dif;
522         len = memcmp( bv1->bv_val, bv2->bv_val, len );
523         if ( !len )
524                 len = dif;
525         return len;
526 }
527
528 /* compare the first value in each filter */
529 static int pcache_filter_cmp( const void *v1, const void *v2 )
530 {
531         const CachedQuery *q1 = v1, *q2 =v2;
532         int rc, weight1, weight2;
533
534         switch( q1->first->f_choice ) {
535         case LDAP_FILTER_PRESENT:
536                 weight1 = 0;
537                 break;
538         case LDAP_FILTER_EQUALITY:
539         case LDAP_FILTER_GE:
540         case LDAP_FILTER_LE:
541                 weight1 = 1;
542                 break;
543         default:
544                 weight1 = 2;
545         }
546         switch( q2->first->f_choice ) {
547         case LDAP_FILTER_PRESENT:
548                 weight2 = 0;
549                 break;
550         case LDAP_FILTER_EQUALITY:
551         case LDAP_FILTER_GE:
552         case LDAP_FILTER_LE:
553                 weight2 = 1;
554                 break;
555         default:
556                 weight2 = 2;
557         }
558         rc = weight1 - weight2;
559         if ( !rc ) {
560                 switch( weight1 ) {
561                 case 0: return 0;
562                 case 1:
563                         rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
564                         break;
565                 case 2:
566                         if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
567                                 rc = 0;
568                                 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
569                                         if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
570                                                 rc = lex_bvcmp( &q1->first->f_sub_initial,
571                                                         &q2->first->f_sub_initial );
572                                         } else {
573                                                 rc = 1;
574                                         }
575                                 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
576                                         rc = -1;
577                                 }
578                                 if ( rc ) break;
579                                 if ( q1->first->f_sub_any ) {
580                                         if ( q2->first->f_sub_any ) {
581                                                 rc = lex_bvcmp( q1->first->f_sub_any,
582                                                         q2->first->f_sub_any );
583                                         } else {
584                                                 rc = 1;
585                                         }
586                                 } else if ( q2->first->f_sub_any ) {
587                                         rc = -1;
588                                 }
589                                 if ( rc ) break;
590                                 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
591                                         if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
592                                                 rc = lex_bvcmp( &q1->first->f_sub_final,
593                                                         &q2->first->f_sub_final );
594                                         } else {
595                                                 rc = 1;
596                                         }
597                                 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
598                                         rc = -1;
599                                 }
600                         } else {
601                                 rc = lex_bvcmp( &q1->first->f_mr_value,
602                                         &q2->first->f_mr_value );
603                         }
604                         break;
605                 }
606         }
607
608         return rc;
609 }
610
611 /* add query on top of LRU list */
612 static void
613 add_query_on_top (query_manager* qm, CachedQuery* qc)
614 {
615         CachedQuery* top = qm->lru_top;
616
617         qm->lru_top = qc;
618
619         if (top)
620                 top->lru_up = qc;
621         else
622                 qm->lru_bottom = qc;
623
624         qc->lru_down = top;
625         qc->lru_up = NULL;
626         Debug( pcache_debug, "Base of added query = %s\n",
627                         qc->qbase->base.bv_val, 0, 0 );
628 }
629
630 /* remove_query from LRU list */
631
632 static void
633 remove_query (query_manager* qm, CachedQuery* qc)
634 {
635         CachedQuery* up;
636         CachedQuery* down;
637
638         if (!qc)
639                 return;
640
641         up = qc->lru_up;
642         down = qc->lru_down;
643
644         if (!up)
645                 qm->lru_top = down;
646
647         if (!down)
648                 qm->lru_bottom = up;
649
650         if (down)
651                 down->lru_up = up;
652
653         if (up)
654                 up->lru_down = down;
655
656         qc->lru_up = qc->lru_down = NULL;
657 }
658
659 /* find and remove string2 from string1
660  * from start if position = 1,
661  * from end if position = 3,
662  * from anywhere if position = 2
663  * string1 is overwritten if position = 2.
664  */
665
666 static int
667 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
668 {
669         int ret=0;
670
671         if ( !ber2->bv_val )
672                 return 1;
673         if ( !ber1->bv_val )
674                 return 0;
675
676         switch( position ) {
677         case 1:
678                 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
679                         ber2->bv_val, ber2->bv_len )) {
680                         ret = 1;
681                         ber1->bv_val += ber2->bv_len;
682                         ber1->bv_len -= ber2->bv_len;
683                 }
684                 break;
685         case 2: {
686                 char *temp;
687                 ber1->bv_val[ber1->bv_len] = '\0';
688                 temp = strstr( ber1->bv_val, ber2->bv_val );
689                 if ( temp ) {
690                         strcpy( temp, temp+ber2->bv_len );
691                         ber1->bv_len -= ber2->bv_len;
692                         ret = 1;
693                 }
694                 break;
695                 }
696         case 3:
697                 if ( ber1->bv_len >= ber2->bv_len &&
698                         !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
699                                 ber2->bv_len )) {
700                         ret = 1;
701                         ber1->bv_len -= ber2->bv_len;
702                 }
703                 break;
704         }
705         return ret;
706 }
707
708
709 static struct berval*
710 merge_init_final(Operation *op, struct berval* init, struct berval* any,
711         struct berval* final)
712 {
713         struct berval* merged, *temp;
714         int i, any_count, count;
715
716         for (any_count=0; any && any[any_count].bv_val; any_count++)
717                 ;
718
719         count = any_count;
720
721         if (init->bv_val)
722                 count++;
723         if (final->bv_val)
724                 count++;
725
726         merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
727                 op->o_tmpmemctx );
728         temp = merged;
729
730         if (init->bv_val) {
731                 ber_dupbv_x( temp, init, op->o_tmpmemctx );
732                 temp++;
733         }
734
735         for (i=0; i<any_count; i++) {
736                 ber_dupbv_x( temp, any, op->o_tmpmemctx );
737                 temp++; any++;
738         }
739
740         if (final->bv_val){
741                 ber_dupbv_x( temp, final, op->o_tmpmemctx );
742                 temp++;
743         }
744         BER_BVZERO( temp );
745         return merged;
746 }
747
748 /* Each element in stored must be found in incoming. Incoming is overwritten.
749  */
750 static int
751 strings_containment(struct berval* stored, struct berval* incoming)
752 {
753         struct berval* element;
754         int k=0;
755         int j, rc = 0;
756
757         for ( element=stored; element->bv_val != NULL; element++ ) {
758                 for (j = k; incoming[j].bv_val != NULL; j++) {
759                         if (find_and_remove(&(incoming[j]), element, 2)) {
760                                 k = j;
761                                 rc = 1;
762                                 break;
763                         }
764                         rc = 0;
765                 }
766                 if ( rc ) {
767                         continue;
768                 } else {
769                         return 0;
770                 }
771         }
772         return 1;
773 }
774
775 static int
776 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
777 {
778         int rc = 0;
779
780         struct berval init_incoming;
781         struct berval final_incoming;
782         struct berval *remaining_incoming = NULL;
783
784         if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
785            || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
786                 return 0;
787
788         init_incoming = incoming->f_sub_initial;
789         final_incoming =  incoming->f_sub_final;
790
791         if (find_and_remove(&init_incoming,
792                         &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
793                         &(stored->f_sub_final), 3))
794         {
795                 if (stored->f_sub_any == NULL) {
796                         rc = 1;
797                         goto final;
798                 }
799                 remaining_incoming = merge_init_final(op, &init_incoming,
800                                                 incoming->f_sub_any, &final_incoming);
801                 rc = strings_containment(stored->f_sub_any, remaining_incoming);
802                 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
803         }
804 final:
805         return rc;
806 }
807
808 static int
809 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
810 {
811         struct berval incoming_val[2];
812         int rc = 0;
813
814         incoming_val[1] = incoming->f_av_value;
815
816         if (find_and_remove(incoming_val+1,
817                         &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
818                         &(stored->f_sub_final), 3)) {
819                 if (stored->f_sub_any == NULL){
820                         rc = 1;
821                         goto final;
822                 }
823                 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
824                 BER_BVZERO( incoming_val+1 );
825                 rc = strings_containment(stored->f_sub_any, incoming_val);
826                 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
827         }
828 final:
829         return rc;
830 }
831
832 static Filter *
833 filter_first( Filter *f )
834 {
835         while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
836                 f = f->f_and;
837         return f;
838 }
839
840
841 static CachedQuery *
842 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
843 {
844         Filter* fs;
845         Filter* fi;
846         MatchingRule* mrule = NULL;
847         int res=0, eqpass= 0;
848         int ret, rc, dir;
849         Avlnode *ptr;
850         CachedQuery cq, *qc;
851
852         cq.filter = inputf;
853         cq.first = first;
854
855         /* substring matches sort to the end, and we just have to
856          * walk the entire list.
857          */
858         if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
859                 ptr = tavl_end( root, 1 );
860                 dir = TAVL_DIR_LEFT;
861         } else {
862                 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
863                 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
864                         TAVL_DIR_RIGHT;
865         }
866
867         while (ptr) {
868                 qc = ptr->avl_data;
869                 fi = inputf;
870                 fs = qc->filter;
871
872                 /* an incoming substr query can only be satisfied by a cached
873                  * substr query.
874                  */
875                 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
876                         qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
877                         break;
878
879                 /* an incoming eq query can be satisfied by a cached eq or substr
880                  * query
881                  */
882                 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
883                         if ( eqpass == 0 ) {
884                                 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
885 nextpass:                       eqpass = 1;
886                                         ptr = tavl_end( root, 1 );
887                                         dir = TAVL_DIR_LEFT;
888                                         continue;
889                                 }
890                         } else {
891                                 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
892                                         break;
893                         }
894                 }
895                 do {
896                         res=0;
897                         switch (fs->f_choice) {
898                         case LDAP_FILTER_EQUALITY:
899                                 if (fi->f_choice == LDAP_FILTER_EQUALITY)
900                                         mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
901                                 else
902                                         ret = 1;
903                                 break;
904                         case LDAP_FILTER_GE:
905                         case LDAP_FILTER_LE:
906                                 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
907                                 break;
908                         default:
909                                 mrule = NULL; 
910                         }
911                         if (mrule) {
912                                 const char *text;
913                                 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
914                                         SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
915                                         &(fi->f_ava->aa_value),
916                                         &(fs->f_ava->aa_value), &text);
917                                 if (rc != LDAP_SUCCESS) {
918                                         return NULL;
919                                 }
920                                 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
921                                         goto nextpass;
922                         }
923                         switch (fs->f_choice) {
924                         case LDAP_FILTER_OR:
925                         case LDAP_FILTER_AND:
926                                 fs = fs->f_and;
927                                 fi = fi->f_and;
928                                 res=1;
929                                 break;
930                         case LDAP_FILTER_SUBSTRINGS:
931                                 /* check if the equality query can be
932                                 * answered with cached substring query */
933                                 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
934                                         && substr_containment_equality( op,
935                                         fs, fi))
936                                         res=1;
937                                 /* check if the substring query can be
938                                 * answered with cached substring query */
939                                 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
940                                         ) && substr_containment_substr( op,
941                                         fs, fi))
942                                         res= 1;
943                                 fs=fs->f_next;
944                                 fi=fi->f_next;
945                                 break;
946                         case LDAP_FILTER_PRESENT:
947                                 res=1;
948                                 fs=fs->f_next;
949                                 fi=fi->f_next;
950                                 break;
951                         case LDAP_FILTER_EQUALITY:
952                                 if (ret == 0)
953                                         res = 1;
954                                 fs=fs->f_next;
955                                 fi=fi->f_next;
956                                 break;
957                         case LDAP_FILTER_GE:
958                                 if (mrule && ret >= 0)
959                                         res = 1;
960                                 fs=fs->f_next;
961                                 fi=fi->f_next;
962                                 break;
963                         case LDAP_FILTER_LE:
964                                 if (mrule && ret <= 0)
965                                         res = 1;
966                                 fs=fs->f_next;
967                                 fi=fi->f_next;
968                                 break;
969                         case LDAP_FILTER_NOT:
970                                 res=0;
971                                 break;
972                         default:
973                                 break;
974                         }
975                 } while((res) && (fi != NULL) && (fs != NULL));
976
977                 if ( res )
978                         return qc;
979                 ptr = tavl_next( ptr, dir );
980         }
981         return NULL;
982 }
983
984 /* check whether query is contained in any of
985  * the cached queries in template
986  */
987 static CachedQuery *
988 query_containment(Operation *op, query_manager *qm,
989                   Query *query,
990                   QueryTemplate *templa)
991 {
992         CachedQuery* qc;
993         int depth = 0, tscope;
994         Qbase qbase, *qbptr = NULL;
995         struct berval pdn;
996
997         if (query->filter != NULL) {
998                 Filter *first;
999
1000                 Debug( pcache_debug, "Lock QC index = %p\n",
1001                                 (void *) templa, 0, 0 );
1002                 qbase.base = query->base;
1003
1004                 first = filter_first( query->filter );
1005
1006                 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1007                 for( ;; ) {
1008                         /* Find the base */
1009                         qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1010                         if ( qbptr ) {
1011                                 tscope = query->scope;
1012                                 /* Find a matching scope:
1013                                  * match at depth 0 OK
1014                                  * scope is BASE,
1015                                  *      one at depth 1 OK
1016                                  *  subord at depth > 0 OK
1017                                  *      subtree at any depth OK
1018                                  * scope is ONE,
1019                                  *  subtree or subord at any depth OK
1020                                  * scope is SUBORD,
1021                                  *  subtree or subord at any depth OK
1022                                  * scope is SUBTREE,
1023                                  *  subord at depth > 0 OK
1024                                  *  subtree at any depth OK
1025                                  */
1026                                 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1027                                         switch ( query->scope ) {
1028                                         case LDAP_SCOPE_BASE:
1029                                                 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1030                                                 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1031                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1032                                                 break;
1033                                         case LDAP_SCOPE_ONE:
1034                                                 if ( tscope == LDAP_SCOPE_BASE )
1035                                                         tscope = LDAP_SCOPE_ONE;
1036                                                 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1037                                                 if ( !depth ) break;
1038                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1039                                                         tscope = LDAP_SCOPE_SUBTREE;
1040                                                 break;
1041                                         case LDAP_SCOPE_SUBTREE:
1042                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1043                                                         tscope = LDAP_SCOPE_SUBTREE;
1044                                                 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1045                                                 break;
1046                                         case LDAP_SCOPE_CHILDREN:
1047                                                 if ( tscope < LDAP_SCOPE_SUBTREE )
1048                                                         tscope = LDAP_SCOPE_SUBTREE;
1049                                                 break;
1050                                         }
1051                                         if ( !qbptr->scopes[tscope] ) continue;
1052
1053                                         /* Find filter */
1054                                         qc = find_filter( op, qbptr->scopes[tscope],
1055                                                         query->filter, first );
1056                                         if ( qc ) {
1057                                                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1058                                                 if (qm->lru_top != qc) {
1059                                                         remove_query(qm, qc);
1060                                                         add_query_on_top(qm, qc);
1061                                                 }
1062                                                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1063                                                 return qc;
1064                                         }
1065                                 }
1066                         }
1067                         if ( be_issuffix( op->o_bd, &qbase.base ))
1068                                 break;
1069                         /* Up a level */
1070                         dnParent( &qbase.base, &pdn );
1071                         qbase.base = pdn;
1072                         depth++;
1073                 }
1074
1075                 Debug( pcache_debug,
1076                         "Not answerable: Unlock QC index=%p\n",
1077                         (void *) templa, 0, 0 );
1078                 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1079         }
1080         return NULL;
1081 }
1082
1083 static void
1084 free_query (CachedQuery* qc)
1085 {
1086         free(qc->q_uuid.bv_val);
1087         filter_free(qc->filter);
1088         free(qc);
1089 }
1090
1091
1092 /* Add query to query cache */
1093 static CachedQuery *
1094 add_query(
1095         Operation *op,
1096         query_manager* qm,
1097         Query* query,
1098         QueryTemplate *templ,
1099         int positive)
1100 {
1101         CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1102         Qbase *qbase, qb;
1103         Filter *first;
1104         int rc;
1105
1106         new_cached_query->qtemp = templ;
1107         BER_BVZERO( &new_cached_query->q_uuid );
1108         if ( positive ) {
1109                 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1110         } else {
1111                 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1112         }
1113         new_cached_query->lru_up = NULL;
1114         new_cached_query->lru_down = NULL;
1115         Debug( pcache_debug, "Added query expires at %ld\n",
1116                         (long) new_cached_query->expiry_time, 0, 0 );
1117
1118         new_cached_query->scope = query->scope;
1119         new_cached_query->filter = query->filter;
1120         new_cached_query->first = first = filter_first( query->filter );
1121
1122         qb.base = query->base;
1123
1124         /* Adding a query    */
1125         Debug( pcache_debug, "Lock AQ index = %p\n",
1126                         (void *) templ, 0, 0 );
1127         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1128         qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1129         if ( !qbase ) {
1130                 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1131                 qbase->base.bv_len = qb.base.bv_len;
1132                 qbase->base.bv_val = (char *)(qbase+1);
1133                 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1134                 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1135                 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1136         }
1137         new_cached_query->next = templ->query;
1138         new_cached_query->prev = NULL;
1139         new_cached_query->qbase = qbase;
1140         rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1141                 pcache_filter_cmp, avl_dup_error );
1142         if ( rc == 0 ) {
1143                 qbase->queries++;
1144                 if (templ->query == NULL)
1145                         templ->query_last = new_cached_query;
1146                 else
1147                         templ->query->prev = new_cached_query;
1148                 templ->query = new_cached_query;
1149                 templ->no_of_queries++;
1150         } else {
1151                 ch_free( new_cached_query );
1152                 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1153                                                         query->filter, first );
1154                 filter_free( query->filter );
1155         }
1156         Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1157                         (void *) templ, templ->no_of_queries, 0 );
1158
1159         Debug( pcache_debug, "Unlock AQ index = %p \n",
1160                         (void *) templ, 0, 0 );
1161         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1162
1163         /* Adding on top of LRU list  */
1164         if ( rc == 0 ) {
1165                 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1166                 add_query_on_top(qm, new_cached_query);
1167                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1168         }
1169         return rc == 0 ? new_cached_query : NULL;
1170 }
1171
1172 static void
1173 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1174 {
1175         if (!qc->prev && !qc->next) {
1176                 template->query_last = template->query = NULL;
1177         } else if (qc->prev == NULL) {
1178                 qc->next->prev = NULL;
1179                 template->query = qc->next;
1180         } else if (qc->next == NULL) {
1181                 qc->prev->next = NULL;
1182                 template->query_last = qc->prev;
1183         } else {
1184                 qc->next->prev = qc->prev;
1185                 qc->prev->next = qc->next;
1186         }
1187         tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1188         qc->qbase->queries--;
1189         if ( qc->qbase->queries == 0 ) {
1190                 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1191                 ch_free( qc->qbase );
1192                 qc->qbase = NULL;
1193         }
1194
1195         template->no_of_queries--;
1196 }
1197
1198 /* remove bottom query of LRU list from the query cache */
1199 static void cache_replacement(query_manager* qm, struct berval *result)
1200 {
1201         CachedQuery* bottom;
1202         QueryTemplate *temp;
1203
1204         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1205         bottom = qm->lru_bottom;
1206
1207         result->bv_val = NULL;
1208         result->bv_len = 0;
1209
1210         if (!bottom) {
1211                 Debug ( pcache_debug,
1212                         "Cache replacement invoked without "
1213                         "any query in LRU list\n", 0, 0, 0 );
1214                 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1215                 return;
1216         }
1217
1218         temp = bottom->qtemp;
1219         remove_query(qm, bottom);
1220         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1221
1222         *result = bottom->q_uuid;
1223         bottom->q_uuid.bv_val = NULL;
1224
1225         Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1226         ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1227         remove_from_template(bottom, temp);
1228         Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1229                 (void *) temp, temp->no_of_queries, 0 );
1230         Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1231         ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1232         free_query(bottom);
1233 }
1234
1235 struct query_info {
1236         struct query_info *next;
1237         struct berval xdn;
1238         int del;
1239 };
1240
1241 static int
1242 remove_func (
1243         Operation       *op,
1244         SlapReply       *rs
1245 )
1246 {
1247         Attribute *attr;
1248         struct query_info *qi;
1249         int count = 0;
1250
1251         if ( rs->sr_type != REP_SEARCH ) return 0;
1252
1253         for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
1254                 if (attr->a_desc == ad_queryid) {
1255                         for (count=0; attr->a_vals[count].bv_val; count++)
1256                                 ;
1257                         break;
1258                 }
1259         }
1260         if ( count == 0 ) return 0;
1261         qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1262         qi->next = op->o_callback->sc_private;
1263         op->o_callback->sc_private = qi;
1264         ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1265         qi->del = ( count == 1 );
1266
1267         return 0;
1268 }
1269
1270 static int
1271 remove_query_data (
1272         Operation       *op,
1273         SlapReply       *rs,
1274         struct berval* query_uuid)
1275 {
1276         struct query_info       *qi, *qnext;
1277         char                    filter_str[64];
1278 #ifdef LDAP_COMP_MATCH
1279         AttributeAssertion      ava = { NULL, BER_BVNULL, NULL };
1280 #else
1281         AttributeAssertion      ava = { NULL, BER_BVNULL };
1282 #endif
1283         Filter                  filter = {LDAP_FILTER_EQUALITY};
1284         SlapReply               sreply = {REP_RESULT};
1285         slap_callback cb = { NULL, remove_func, NULL, NULL };
1286         int deleted = 0;
1287
1288         sreply.sr_entry = NULL;
1289         sreply.sr_nentries = 0;
1290         op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1291                 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
1292         filter.f_ava = &ava;
1293         filter.f_av_desc = ad_queryid;
1294         filter.f_av_value = *query_uuid;
1295
1296         op->o_tag = LDAP_REQ_SEARCH;
1297         op->o_protocol = LDAP_VERSION3;
1298         op->o_callback = &cb;
1299         op->o_time = slap_get_time();
1300         op->o_do_not_cache = 1;
1301
1302         op->o_req_dn = op->o_bd->be_suffix[0];
1303         op->o_req_ndn = op->o_bd->be_nsuffix[0];
1304         op->ors_scope = LDAP_SCOPE_SUBTREE;
1305         op->ors_deref = LDAP_DEREF_NEVER;
1306         op->ors_slimit = SLAP_NO_LIMIT;
1307         op->ors_tlimit = SLAP_NO_LIMIT;
1308         op->ors_filter = &filter;
1309         op->ors_filterstr.bv_val = filter_str;
1310         op->ors_filterstr.bv_len = strlen(filter_str);
1311         op->ors_attrs = NULL;
1312         op->ors_attrsonly = 0;
1313
1314         op->o_bd->be_search( op, &sreply );
1315
1316         for ( qi=cb.sc_private; qi; qi=qnext ) {
1317                 qnext = qi->next;
1318
1319                 op->o_req_dn = qi->xdn;
1320                 op->o_req_ndn = qi->xdn;
1321
1322                 if ( qi->del) {
1323                         Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1324                                 query_uuid->bv_val, 0, 0 );
1325
1326                         op->o_tag = LDAP_REQ_DELETE;
1327
1328                         if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1329                                 deleted++;
1330                         }
1331                 } else {
1332                         Modifications mod;
1333                         struct berval vals[2];
1334
1335                         vals[0] = *query_uuid;
1336                         vals[1].bv_val = NULL;
1337                         vals[1].bv_len = 0;
1338                         mod.sml_op = LDAP_MOD_DELETE;
1339                         mod.sml_flags = 0;
1340                         mod.sml_desc = ad_queryid;
1341                         mod.sml_type = ad_queryid->ad_cname;
1342                         mod.sml_values = vals;
1343                         mod.sml_nvalues = NULL;
1344                         mod.sml_next = NULL;
1345                         Debug( pcache_debug,
1346                                 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1347                                 query_uuid->bv_val, 0, 0 );
1348
1349                         op->orm_modlist = &mod;
1350
1351                         op->o_bd->be_modify( op, &sreply );
1352                 }
1353                 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1354                 op->o_tmpfree( qi, op->o_tmpmemctx );
1355         }
1356         return deleted;
1357 }
1358
1359 static int
1360 get_attr_set(
1361         AttributeName* attrs,
1362         query_manager* qm,
1363         int num
1364 );
1365
1366 static int
1367 filter2template(
1368         Operation               *op,
1369         Filter                  *f,
1370         struct                  berval *fstr,
1371         AttributeName**         filter_attrs,
1372         int*                    filter_cnt,
1373         int*                    filter_got_oc )
1374 {
1375         AttributeDescription *ad;
1376
1377         switch ( f->f_choice ) {
1378         case LDAP_FILTER_EQUALITY:
1379                 ad = f->f_av_desc;
1380                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1381                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1382                 break;
1383
1384         case LDAP_FILTER_GE:
1385                 ad = f->f_av_desc;
1386                 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1387                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1388                 break;
1389
1390         case LDAP_FILTER_LE:
1391                 ad = f->f_av_desc;
1392                 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1393                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1394                 break;
1395
1396         case LDAP_FILTER_APPROX:
1397                 ad = f->f_av_desc;
1398                 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1399                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1400                 break;
1401
1402         case LDAP_FILTER_SUBSTRINGS:
1403                 ad = f->f_sub_desc;
1404                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1405                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1406                 break;
1407
1408         case LDAP_FILTER_PRESENT:
1409                 ad = f->f_desc;
1410                 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1411                 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1412                 break;
1413
1414         case LDAP_FILTER_AND:
1415         case LDAP_FILTER_OR:
1416         case LDAP_FILTER_NOT: {
1417                 int rc = 0;
1418                 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1419                         f->f_choice == LDAP_FILTER_AND ? '&' :
1420                         f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1421                 fstr->bv_len += sizeof("(%") - 1;
1422
1423                 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1424                         rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1425                                 filter_got_oc );
1426                         if ( rc ) break;
1427                 }
1428                 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1429                 fstr->bv_len += sizeof(")") - 1;
1430
1431                 return rc;
1432                 }
1433
1434         default:
1435                 strcpy( fstr->bv_val, "(?=?)" );
1436                 fstr->bv_len += sizeof("(?=?)")-1;
1437                 return -1;
1438         }
1439
1440         if ( filter_attrs != NULL ) {
1441                 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1442                                 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1443
1444                 (*filter_attrs)[*filter_cnt].an_desc = ad;
1445                 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1446                 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1447                 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1448                 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1449                 (*filter_cnt)++;
1450                 if ( ad == slap_schema.si_ad_objectClass )
1451                         *filter_got_oc = 1;
1452         }
1453
1454         return 0;
1455 }
1456
1457 struct search_info {
1458         slap_overinst *on;
1459         Query query;
1460         QueryTemplate *qtemp;
1461         AttributeName*  save_attrs;     /* original attributes, saved for response */
1462         int max;
1463         int over;
1464         int count;
1465         Entry *head, *tail;
1466 };
1467
1468 static int
1469 cache_entries(
1470         Operation       *op,
1471         SlapReply       *rs,
1472         struct berval *query_uuid)
1473 {
1474         struct search_info *si = op->o_callback->sc_private;
1475         slap_overinst *on = si->on;
1476         cache_manager *cm = on->on_bi.bi_private;
1477         query_manager*          qm = cm->qm;
1478         int             return_val = 0;
1479         Entry           *e;
1480         struct berval   crp_uuid;
1481         char            uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1482         Operation op_tmp = *op;
1483
1484         query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1485         ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1486
1487         op_tmp.o_bd = &cm->db;
1488         op_tmp.o_dn = cm->db.be_rootdn;
1489         op_tmp.o_ndn = cm->db.be_rootndn;
1490
1491         Debug( pcache_debug, "UUID for query being added = %s\n",
1492                         uuidbuf, 0, 0 );
1493
1494         for ( e=si->head; e; e=si->head ) {
1495                 si->head = e->e_private;
1496                 e->e_private = NULL;
1497                 while ( cm->cur_entries > (cm->max_entries) ) {
1498                                 qm->crfunc(qm, &crp_uuid);
1499                                 if (crp_uuid.bv_val) {
1500                                         Debug( pcache_debug,
1501                                                 "Removing query UUID %s\n",
1502                                                 crp_uuid.bv_val, 0, 0 );
1503                                         return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1504                                         Debug( pcache_debug,
1505                                                 "QUERY REMOVED, SIZE=%d\n",
1506                                                 return_val, 0, 0);
1507                                         ldap_pvt_thread_mutex_lock(
1508                                                         &cm->cache_mutex );
1509                                         cm->cur_entries -= return_val;
1510                                         cm->num_cached_queries--;
1511                                         Debug( pcache_debug,
1512                                                 "STORED QUERIES = %lu\n",
1513                                                 cm->num_cached_queries, 0, 0 );
1514                                         ldap_pvt_thread_mutex_unlock(
1515                                                         &cm->cache_mutex );
1516                                         Debug( pcache_debug,
1517                                                 "QUERY REMOVED, CACHE ="
1518                                                 "%d entries\n",
1519                                                 cm->cur_entries, 0, 0 );
1520                                 }
1521                 }
1522
1523                 return_val = merge_entry(&op_tmp, e, query_uuid);
1524                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1525                 cm->cur_entries += return_val;
1526                 Debug( pcache_debug,
1527                         "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1528                         cm->cur_entries, 0, 0 );
1529                 return_val = 0;
1530                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1531         }
1532
1533         return return_val;
1534 }
1535
1536 static int
1537 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1538         slap_callback   *cb = op->o_callback;
1539         struct search_info *si = cb->sc_private;
1540         if ( si->save_attrs != NULL ) {
1541                 rs->sr_attrs = si->save_attrs;
1542                 op->ors_attrs = si->save_attrs;
1543         }
1544         op->o_callback = op->o_callback->sc_next;
1545         op->o_tmpfree( cb, op->o_tmpmemctx );
1546         return SLAP_CB_CONTINUE;
1547 }
1548
1549 static int
1550 pcache_response(
1551         Operation       *op,
1552         SlapReply       *rs )
1553 {
1554         struct search_info *si = op->o_callback->sc_private;
1555         slap_overinst *on = si->on;
1556         cache_manager *cm = on->on_bi.bi_private;
1557         query_manager*          qm = cm->qm;
1558
1559         if ( si->save_attrs != NULL ) {
1560                 rs->sr_attrs = si->save_attrs;
1561                 op->ors_attrs = si->save_attrs;
1562         }
1563
1564         if ( rs->sr_type == REP_SEARCH ) {
1565                 Entry *e;
1566                 /* If we haven't exceeded the limit for this query,
1567                  * build a chain of answers to store. If we hit the
1568                  * limit, empty the chain and ignore the rest.
1569                  */
1570                 if ( !si->over ) {
1571                         if ( si->count < si->max ) {
1572                                 si->count++;
1573                                 e = entry_dup( rs->sr_entry );
1574                                 if ( !si->head ) si->head = e;
1575                                 if ( si->tail ) si->tail->e_private = e;
1576                                 si->tail = e;
1577                         } else {
1578                                 si->over = 1;
1579                                 si->count = 0;
1580                                 for (;si->head; si->head=e) {
1581                                         e = si->head->e_private;
1582                                         si->head->e_private = NULL;
1583                                         entry_free(si->head);
1584                                 }
1585                                 si->tail = NULL;
1586                         }
1587                 }
1588
1589         } else if ( rs->sr_type == REP_RESULT ) {
1590                 if ( si->count ||
1591                         ( si->qtemp->negttl && !si->count && !si->over &&
1592                                 rs->sr_err == LDAP_SUCCESS )) {
1593                         CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1594                                 si->count);
1595
1596                         if ( qc != NULL ) {
1597                                 if ( si->count )
1598                                         cache_entries( op, rs, &qc->q_uuid );
1599                                 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1600                                 cm->num_cached_queries++;
1601                                 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1602                                                 cm->num_cached_queries, 0, 0 );
1603                                 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1604
1605                                 /* If the consistency checker suspended itself,
1606                                  * wake it back up
1607                                  */
1608                                 if ( cm->cc_paused ) {
1609                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1610                                         if ( cm->cc_paused ) {
1611                                                 cm->cc_paused = 0;
1612                                                 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1613                                         }
1614                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1615                                 }
1616                         } else if ( si->count ) {
1617                                 /* duplicate query, free it */
1618                                 Entry *e;
1619                                 for (;si->head; si->head=e) {
1620                                         e = si->head->e_private;
1621                                         si->head->e_private = NULL;
1622                                         entry_free(si->head);
1623                                 }
1624                         }
1625                 } else {
1626                         filter_free( si->query.filter );
1627                 }
1628
1629                 op->o_callback->sc_cleanup = pcache_op_cleanup;
1630         }
1631         return SLAP_CB_CONTINUE;
1632 }
1633
1634 static int
1635 add_filter_attrs(
1636         Operation *op,
1637         AttributeName** new_attrs,
1638         struct attr_set *attrs,
1639         AttributeName* filter_attrs,
1640         int fattr_cnt,
1641         int fattr_got_oc)
1642 {
1643         int alluser = 0;
1644         int allop = 0;
1645         int i, j;
1646         int count;
1647         int addoc = 0;
1648
1649         /* duplicate attrs */
1650         count = attrs->count + fattr_cnt;
1651         if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1652                 addoc = 1;
1653                 count++;
1654         }
1655
1656         *new_attrs = (AttributeName*)ch_calloc( count + 1,
1657                 sizeof(AttributeName) );
1658         for (i=0; i<attrs->count; i++) {
1659                 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1660                 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1661         }
1662         BER_BVZERO( &(*new_attrs)[i].an_name );
1663         alluser = an_find(*new_attrs, &AllUser);
1664         allop = an_find(*new_attrs, &AllOper);
1665
1666         j = i;
1667         for ( i=0; i<fattr_cnt; i++ ) {
1668                 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
1669                         continue;
1670                 }
1671                 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1672                         if ( allop ) {
1673                                 continue;
1674                         }
1675                 } else if ( alluser ) {
1676                         continue;
1677                 }
1678                 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1679                 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1680                 (*new_attrs)[j].an_oc = NULL;
1681                 (*new_attrs)[j].an_oc_exclude = 0;
1682                 j++;
1683         }
1684         if ( addoc ) {
1685                 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1686                 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1687                 (*new_attrs)[j].an_oc = NULL;
1688                 (*new_attrs)[j].an_oc_exclude = 0;
1689                 j++;
1690         }
1691         BER_BVZERO( &(*new_attrs)[j].an_name );
1692
1693         return count;
1694 }
1695
1696 /* NOTE: this is a quick workaround to let pcache minimally interact
1697  * with pagedResults.  A more articulated solutions would be to
1698  * perform the remote query without control and cache all results,
1699  * performing the pagedResults search only within the client
1700  * and the proxy.  This requires pcache to understand pagedResults. */
1701 static int
1702 pcache_chk_controls(
1703         Operation       *op,
1704         SlapReply       *rs )
1705 {
1706         const char      *non = "";
1707         const char      *stripped = "";
1708
1709         switch( op->o_pagedresults ) {
1710         case SLAP_CONTROL_NONCRITICAL:
1711                 non = "non-";
1712                 stripped = "; stripped";
1713                 /* fallthru */
1714
1715         case SLAP_CONTROL_CRITICAL:
1716                 Debug( pcache_debug, "%s: "
1717                         "%scritical pagedResults control "
1718                         "disabled with proxy cache%s.\n",
1719                         op->o_log_prefix, non, stripped );
1720                 
1721                 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1722                 break;
1723
1724         default:
1725                 rs->sr_err = SLAP_CB_CONTINUE;
1726                 break;
1727         }
1728
1729         return rs->sr_err;
1730 }
1731
1732 static int
1733 pcache_op_search(
1734         Operation       *op,
1735         SlapReply       *rs )
1736 {
1737         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1738         cache_manager *cm = on->on_bi.bi_private;
1739         query_manager*          qm = cm->qm;
1740
1741         int i = -1;
1742
1743         AttributeName   *filter_attrs = NULL;
1744
1745         Query           query;
1746         QueryTemplate   *qtemp = NULL;
1747
1748         int             attr_set = -1;
1749         CachedQuery     *answerable = NULL;
1750         int             cacheable = 0;
1751         int             fattr_cnt=0;
1752         int             fattr_got_oc = 0;
1753
1754         struct berval tempstr;
1755
1756         tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1757         tempstr.bv_len = 0;
1758         if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1759                 &fattr_cnt, &fattr_got_oc )) {
1760                 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1761                 return SLAP_CB_CONTINUE;
1762         }
1763
1764         Debug( pcache_debug, "query template of incoming query = %s\n",
1765                                         tempstr.bv_val, 0, 0 );
1766
1767         /* FIXME: cannot cache/answer requests with pagedResults control */
1768
1769         /* find attr set */
1770         attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1771
1772         query.filter = op->ors_filter;
1773         query.base = op->o_req_ndn;
1774         query.scope = op->ors_scope;
1775
1776         /* check for query containment */
1777         if (attr_set > -1) {
1778                 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1779                 for (; qt; qt = qt->qtnext ) {
1780                         /* find if template i can potentially answer tempstr */
1781                         if (qt->querystr.bv_len != tempstr.bv_len ||
1782                                 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1783                                 continue;
1784                         cacheable = 1;
1785                         qtemp = qt;
1786                         Debug( pcache_debug, "Entering QC, querystr = %s\n",
1787                                         op->ors_filterstr.bv_val, 0, 0 );
1788                         answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1789
1790                         if (answerable)
1791                                 break;
1792                 }
1793         }
1794         op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1795
1796         if (answerable) {
1797                 /* Need to clear the callbacks of the original operation,
1798                  * in case there are other overlays */
1799                 BackendDB       *save_bd = op->o_bd;
1800                 slap_callback   *save_cb = op->o_callback;
1801
1802                 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1803                 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1804                 if ( BER_BVISNULL( &answerable->q_uuid )) {
1805                         /* No entries cached, just an empty result set */
1806                         i = rs->sr_err = 0;
1807                         send_ldap_result( op, rs );
1808                 } else {
1809                         op->o_bd = &cm->db;
1810                         op->o_callback = NULL;
1811                         i = cm->db.bd_info->bi_op_search( op, rs );
1812                 }
1813                 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1814                 op->o_bd = save_bd;
1815                 op->o_callback = save_cb;
1816                 return i;
1817         }
1818
1819         Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1820
1821         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1822         if (cm->num_cached_queries >= cm->max_queries) {
1823                 cacheable = 0;
1824         }
1825         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1826
1827         if (op->ors_attrsonly)
1828                 cacheable = 0;
1829
1830         if (cacheable) {
1831                 slap_callback           *cb;
1832                 struct search_info      *si;
1833
1834                 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1835                 query.filter = filter_dup(op->ors_filter, NULL);
1836                 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
1837                 if ( !qtemp->t_attrs.count ) {
1838                         qtemp->t_attrs.count = add_filter_attrs(op,
1839                                 &qtemp->t_attrs.attrs,
1840                                 &qm->attr_sets[attr_set],
1841                                 filter_attrs, fattr_cnt, fattr_got_oc);
1842                 }
1843                 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
1844
1845                 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
1846                 cb->sc_response = pcache_response;
1847                 cb->sc_cleanup = NULL;
1848                 cb->sc_private = (cb+1);
1849                 si = cb->sc_private;
1850                 si->on = on;
1851                 si->query = query;
1852                 si->qtemp = qtemp;
1853                 si->max = cm->num_entries_limit ;
1854                 si->over = 0;
1855                 si->count = 0;
1856                 si->head = NULL;
1857                 si->tail = NULL;
1858                 si->save_attrs = op->ors_attrs;
1859
1860                 op->ors_attrs = qtemp->t_attrs.attrs;
1861
1862                 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1863                         cb->sc_next = op->o_callback;
1864                         op->o_callback = cb;
1865
1866                 } else {
1867                         slap_callback           **pcb;
1868
1869                         /* need to move the callback at the end, in case other
1870                          * overlays are present, so that the final entry is
1871                          * actually cached */
1872                         cb->sc_next = NULL;
1873                         for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1874                         *pcb = cb;
1875                 }
1876
1877         } else {
1878                 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1879                                         0, 0, 0);
1880         }
1881
1882         op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1883
1884         return SLAP_CB_CONTINUE;
1885 }
1886
1887 static int
1888 get_attr_set(
1889         AttributeName* attrs,
1890         query_manager* qm,
1891         int num )
1892 {
1893         int i;
1894         int count = 0;
1895
1896         if ( attrs ) {
1897                 for ( ; attrs[count].an_name.bv_val; count++ );
1898         }
1899
1900         /* recognize a single "*" or a "1.1" */
1901         if ( count == 0 ) {
1902                 count = 1;
1903                 attrs = slap_anlist_all_user_attributes;
1904
1905         } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
1906                 count = 0;
1907                 attrs = NULL;
1908         }
1909
1910         for ( i = 0; i < num; i++ ) {
1911                 AttributeName *a2;
1912                 int found = 1;
1913
1914                 if ( count > qm->attr_sets[i].count ) {
1915                         continue;
1916                 }
1917
1918                 if ( !count ) {
1919                         if ( !qm->attr_sets[i].count ) {
1920                                 break;
1921                         }
1922                         continue;
1923                 }
1924
1925                 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1926                         if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
1927                                 found = 0;
1928                                 break;
1929                         }
1930                 }
1931
1932                 if ( found ) {
1933                         break;
1934                 }
1935         }
1936
1937         if ( i == num ) {
1938                 i = -1;
1939         }
1940
1941         return i;
1942 }
1943
1944 static void*
1945 consistency_check(
1946         void *ctx,
1947         void *arg )
1948 {
1949         struct re_s *rtask = arg;
1950         slap_overinst *on = rtask->arg;
1951         cache_manager *cm = on->on_bi.bi_private;
1952         query_manager *qm = cm->qm;
1953         Connection conn = {0};
1954         OperationBuffer opbuf;
1955         Operation *op;
1956
1957         SlapReply rs = {REP_RESULT};
1958         CachedQuery* query;
1959         int return_val, pause = 1;
1960         QueryTemplate* templ;
1961
1962         connection_fake_init( &conn, &opbuf, ctx );
1963         op = &opbuf.ob_op;
1964
1965         op->o_bd = &cm->db;
1966         op->o_dn = cm->db.be_rootdn;
1967         op->o_ndn = cm->db.be_rootndn;
1968
1969         cm->cc_arg = arg;
1970
1971         for (templ = qm->templates; templ; templ=templ->qmnext) {
1972                 query = templ->query_last;
1973                 if ( query ) pause = 0;
1974                 op->o_time = slap_get_time();
1975                 while (query && (query->expiry_time < op->o_time)) {
1976                         int rem = 0;
1977                         Debug( pcache_debug, "Lock CR index = %p\n",
1978                                         (void *) templ, 0, 0 );
1979                         ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1980                         if ( query == templ->query_last ) {
1981                                 rem = 1;
1982                                 remove_from_template(query, templ);
1983                                 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1984                                                 (void *) templ, templ->no_of_queries, 0 );
1985                                 Debug( pcache_debug, "Unlock CR index = %p\n",
1986                                                 (void *) templ, 0, 0 );
1987                         }
1988                         ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1989                         if ( !rem ) {
1990                                 query = templ->query_last;
1991                                 continue;
1992                         }
1993                         ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1994                         remove_query(qm, query);
1995                         ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1996                         if ( BER_BVISNULL( &query->q_uuid ))
1997                                 return_val = 0;
1998                         else
1999                                 return_val = remove_query_data(op, &rs, &query->q_uuid);
2000                         Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2001                                                 return_val, 0, 0 );
2002                         ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2003                         cm->cur_entries -= return_val;
2004                         cm->num_cached_queries--;
2005                         Debug( pcache_debug, "STORED QUERIES = %lu\n",
2006                                         cm->num_cached_queries, 0, 0 );
2007                         ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2008                         Debug( pcache_debug,
2009                                 "STALE QUERY REMOVED, CACHE ="
2010                                 "%d entries\n",
2011                                 cm->cur_entries, 0, 0 );
2012                         free_query(query);
2013                         query = templ->query_last;
2014                 }
2015         }
2016         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2017         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2018                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2019         }
2020         /* If there were no queries, defer processing for a while */
2021         cm->cc_paused = pause;
2022         ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2023
2024         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2025         return NULL;
2026 }
2027
2028
2029 #define MAX_ATTR_SETS 500
2030
2031 enum {
2032         PC_MAIN = 1,
2033         PC_ATTR,
2034         PC_TEMP,
2035         PC_RESP,
2036         PC_QUERIES
2037 };
2038
2039 static ConfigDriver pc_cf_gen;
2040 static ConfigLDAPadd pc_ldadd;
2041 static ConfigCfAdd pc_cfadd;
2042
2043 static ConfigTable pccfg[] = {
2044         { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2045                                 "<cycle_time",
2046                 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2047                 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2048                         "DESC 'ProxyCache basic parameters' "
2049                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2050         { "proxyattrset", "index> <attributes...",
2051                 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2052                 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2053                         "DESC 'A set of attributes to cache' "
2054                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2055         { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2056                 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2057                 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2058                         "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2059                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2060         { "response-callback", "head|tail(default)",
2061                 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2062                 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2063                         "DESC 'Response callback position in overlay stack' "
2064                         "SYNTAX OMsDirectoryString )", NULL, NULL },
2065         { "proxyCacheQueries", "queries",
2066                 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2067                 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2068                         "DESC 'Maximum number of queries to cache' "
2069                         "SYNTAX OMsInteger )", NULL, NULL },
2070         { "proxySaveQueries", "TRUE|FALSE",
2071                 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2072                 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2073                         "DESC 'Save cached queries for hot restart' "
2074                         "SYNTAX OMsBoolean )", NULL, NULL },
2075
2076         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2077 };
2078
2079 static ConfigOCs pcocs[] = {
2080         { "( OLcfgOvOc:2.1 "
2081                 "NAME 'olcPcacheConfig' "
2082                 "DESC 'ProxyCache configuration' "
2083                 "SUP olcOverlayConfig "
2084                 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2085                 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2086                 Cft_Overlay, pccfg, NULL, pc_cfadd },
2087         { "( OLcfgOvOc:2.2 "
2088                 "NAME 'olcPcacheDatabase' "
2089                 "DESC 'Cache database configuration' "
2090                 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2091         { NULL, 0, NULL }
2092 };
2093
2094 static int
2095 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2096 {
2097         slap_overinst *on;
2098         cache_manager *cm;
2099
2100         if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2101                 p->ce_bi->bi_cf_ocs != pcocs )
2102                 return LDAP_CONSTRAINT_VIOLATION;
2103
2104         on = (slap_overinst *)p->ce_bi;
2105         cm = on->on_bi.bi_private;
2106         ca->be = &cm->db;
2107         return LDAP_SUCCESS;
2108 }
2109
2110 static int
2111 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2112 {
2113         CfEntryInfo *pe = p->e_private;
2114         slap_overinst *on = (slap_overinst *)pe->ce_bi;
2115         cache_manager *cm = on->on_bi.bi_private;
2116         struct berval bv;
2117
2118         /* FIXME: should not hardcode "olcDatabase" here */
2119         bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2120         bv.bv_val = ca->cr_msg;
2121         ca->be = &cm->db;
2122
2123         /* We can only create this entry if the database is table-driven
2124          */
2125         if ( cm->db.bd_info->bi_cf_ocs )
2126                 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2127                         &pcocs[1] );
2128
2129         return 0;
2130 }
2131
2132 static int
2133 pc_cf_gen( ConfigArgs *c )
2134 {
2135         slap_overinst   *on = (slap_overinst *)c->bi;
2136         cache_manager*  cm = on->on_bi.bi_private;
2137         query_manager*  qm = cm->qm;
2138         QueryTemplate*  temp;
2139         AttributeName*  attr_name;
2140         AttributeName*  attrarray;
2141         const char*     text=NULL;
2142         int             i, num, rc = 0;
2143         char            *ptr;
2144         unsigned long   t;
2145
2146         if ( c->op == SLAP_CONFIG_EMIT ) {
2147                 struct berval bv;
2148                 switch( c->type ) {
2149                 case PC_MAIN:
2150                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2151                                 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2152                                 cm->num_entries_limit, cm->cc_period );
2153                         bv.bv_val = c->cr_msg;
2154                         value_add_one( &c->rvalue_vals, &bv );
2155                         break;
2156                 case PC_ATTR:
2157                         for (i=0; i<cm->numattrsets; i++) {
2158                                 if ( !qm->attr_sets[i].count ) continue;
2159
2160                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2161
2162                                 /* count the attr length */
2163                                 for ( attr_name = qm->attr_sets[i].attrs;
2164                                         attr_name->an_name.bv_val; attr_name++ )
2165                                         bv.bv_len += attr_name->an_name.bv_len + 1;
2166
2167                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2168                                 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2169                                 for ( attr_name = qm->attr_sets[i].attrs;
2170                                         attr_name->an_name.bv_val; attr_name++ ) {
2171                                         *ptr++ = ' ';
2172                                         ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2173                                 }
2174                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2175                         }
2176                         if ( !c->rvalue_vals )
2177                                 rc = 1;
2178                         break;
2179                 case PC_TEMP:
2180                         for (temp=qm->templates; temp; temp=temp->qmnext) {
2181                                 if ( temp->negttl ) {
2182                                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2183                                                 " %d %ld %ld",
2184                                                 temp->attr_set_index,
2185                                                 temp->ttl,
2186                                                 temp->negttl );
2187                                 } else {
2188                                         bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2189                                                 temp->attr_set_index,
2190                                                 temp->ttl );
2191                                 }
2192                                 bv.bv_len += temp->querystr.bv_len + 2;
2193                                 bv.bv_val = ch_malloc( bv.bv_len+1 );
2194                                 ptr = bv.bv_val;
2195                                 *ptr++ = '"';
2196                                 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2197                                 *ptr++ = '"';
2198                                 strcpy( ptr, c->cr_msg );
2199                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2200                         }
2201                         if ( !c->rvalue_vals )
2202                                 rc = 1;
2203                         break;
2204                 case PC_RESP:
2205                         if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2206                                 BER_BVSTR( &bv, "head" );
2207                         } else {
2208                                 BER_BVSTR( &bv, "tail" );
2209                         }
2210                         value_add_one( &c->rvalue_vals, &bv );
2211                         break;
2212                 case PC_QUERIES:
2213                         c->value_int = cm->max_queries;
2214                         break;
2215                 }
2216                 return rc;
2217         } else if ( c->op == LDAP_MOD_DELETE ) {
2218                 return 1;       /* FIXME */
2219 #if 0
2220                 switch( c->type ) {
2221                 case PC_ATTR:
2222                 case PC_TEMP:
2223                 }
2224                 return rc;
2225 #endif
2226         }
2227
2228         switch( c->type ) {
2229         case PC_MAIN:
2230                 if ( cm->numattrsets > 0 ) {
2231                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2232                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2233                         return( 1 );
2234                 }
2235
2236                 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2237                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2238                                 c->argv[3] );
2239                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2240                         return( 1 );
2241                 }
2242                 if ( cm->numattrsets <= 0 ) {
2243                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2244                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2245                         return( 1 );
2246                 }
2247                 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2248                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2249                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2250                         return( 1 );
2251                 }
2252
2253                 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2254                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2255                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2256                         return( 1 );
2257                 }
2258
2259                 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2260                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2261                                 c->argv[2] );
2262                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2263                         return( 1 );
2264                 }
2265                 if ( cm->max_entries <= 0 ) {
2266                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2267                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2268                         return( 1 );
2269                 }
2270
2271                 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2272                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2273                                 c->argv[4] );
2274                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2275                         return( 1 );
2276                 }
2277                 if ( cm->num_entries_limit <= 0 ) {
2278                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2279                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2280                         return( 1 );
2281                 }
2282                 if ( cm->num_entries_limit > cm->max_entries ) {
2283                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2284                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2285                         return( 1 );
2286                 }
2287
2288                 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2289                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2290                                 c->argv[5] );
2291                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2292                         return( 1 );
2293                 }
2294                 cm->cc_period = (time_t)t;
2295                 Debug( pcache_debug,
2296                                 "Total # of attribute sets to be cached = %d.\n",
2297                                 cm->numattrsets, 0, 0 );
2298                 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2299                                                 sizeof( struct attr_set ) );
2300                 break;
2301         case PC_ATTR:
2302                 if ( cm->numattrsets == 0 ) {
2303                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2304                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2305                         return( 1 );
2306                 }
2307                 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2308                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2309                                 c->argv[1] );
2310                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2311                         return( 1 );
2312                 }
2313
2314                 if ( num < 0 || num >= cm->numattrsets ) {
2315                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2316                                 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2317                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2318                         return 1;
2319                 }
2320                 qm->attr_sets[num].flags |= PC_CONFIGURED;
2321                 if ( c->argc == 2 ) {
2322                         /* assume "1.1" */
2323                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2324                                 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2325                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2326                         return 1;
2327
2328                 } else if ( c->argc == 3 ) {
2329                         if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2330                                 qm->attr_sets[num].count = 1;
2331                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2332                                         sizeof( AttributeName ) );
2333                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2334                                 break;
2335
2336                         } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2337                                 qm->attr_sets[num].count = 1;
2338                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2339                                         sizeof( AttributeName ) );
2340                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2341                                 break;
2342
2343                         } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2344                                 break;
2345                         }
2346                         /* else: fallthru */
2347
2348                 } else if ( c->argc == 4 ) {
2349                         if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2350                                 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2351                         {
2352                                 qm->attr_sets[num].count = 2;
2353                                 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2354                                         sizeof( AttributeName ) );
2355                                 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2356                                 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2357                                 break;
2358                         }
2359                         /* else: fallthru */
2360                 }
2361
2362                 if ( c->argc > 2 ) {
2363                         int all_user = 0, all_op = 0;
2364
2365                         qm->attr_sets[num].count = c->argc - 2;
2366                         qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2367                                 sizeof( AttributeName ) );
2368                         attr_name = qm->attr_sets[num].attrs;
2369                         for ( i = 2; i < c->argc; i++ ) {
2370                                 attr_name->an_desc = NULL;
2371                                 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2372                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
2373                                                 "invalid attr #%d \"%s\" in attrlist",
2374                                                 i - 2, c->argv[i] );
2375                                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2376                                         ch_free( qm->attr_sets[num].attrs );
2377                                         qm->attr_sets[num].attrs = NULL;
2378                                         qm->attr_sets[num].count = 0;
2379                                         return 1;
2380                                 }
2381                                 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2382                                         all_user = 1;
2383                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2384                                 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2385                                         all_op = 1;
2386                                         BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2387                                 } else {
2388                                         if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2389                                                 strcpy( c->cr_msg, text );
2390                                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2391                                                 ch_free( qm->attr_sets[num].attrs );
2392                                                 qm->attr_sets[num].attrs = NULL;
2393                                                 qm->attr_sets[num].count = 0;
2394                                                 return 1;
2395                                         }
2396                                         attr_name->an_name = attr_name->an_desc->ad_cname;
2397                                 }
2398                                 attr_name->an_oc = NULL;
2399                                 attr_name->an_oc_exclude = 0;
2400                                 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2401                                         qm->attr_sets[num].flags |= PC_GOT_OC;
2402                                 attr_name++;
2403                                 BER_BVZERO( &attr_name->an_name );
2404                         }
2405
2406                         /* warn if list contains both "*" and "+" */
2407                         if ( i > 4 && all_user && all_op ) {
2408                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2409                                         "warning: attribute list contains \"*\" and \"+\"" );
2410                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2411                         }
2412                 }
2413                 break;
2414         case PC_TEMP:
2415                 if ( cm->numattrsets == 0 ) {
2416                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2417                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2418                         return( 1 );
2419                 }
2420                 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2421                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2422                                 c->argv[2] );
2423                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2424                         return( 1 );
2425                 }
2426
2427                 if ( i < 0 || i >= cm->numattrsets || 
2428                         !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2429                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2430                                 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2431                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2432                         return 1;
2433                 }
2434                 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2435                 temp->qmnext = qm->templates;
2436                 qm->templates = temp;
2437                 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2438                 temp->query = temp->query_last = NULL;
2439                 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2440                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2441                                 c->argv[3] );
2442                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2443                         return( 1 );
2444                 }
2445                 temp->ttl = (time_t)t;
2446                 if ( c->argc == 5 ) {
2447                         if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2448                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2449                                         "unable to parse template negttl=\"%s\"",
2450                                         c->argv[4] );
2451                                 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2452                                         return( 1 );
2453                         }
2454                         temp->negttl = (time_t)t;
2455                 } else {
2456                         temp->negttl = 0;
2457                 }
2458
2459                 temp->no_of_queries = 0;
2460
2461                 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2462                 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2463                 Debug( pcache_debug, "  query template: %s\n",
2464                                 temp->querystr.bv_val, 0, 0 );
2465                 temp->attr_set_index = i;
2466                 qm->attr_sets[i].flags |= PC_REFERENCED;
2467                 temp->qtnext = qm->attr_sets[i].templates;
2468                 qm->attr_sets[i].templates = temp;
2469                 Debug( pcache_debug, "  attributes: \n", 0, 0, 0 );
2470                 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2471                         for ( i=0; attrarray[i].an_name.bv_val; i++ )
2472                                 Debug( pcache_debug, "\t%s\n",
2473                                         attrarray[i].an_name.bv_val, 0, 0 );
2474                 }
2475                 break;
2476         case PC_RESP:
2477                 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2478                         cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2479
2480                 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2481                         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2482
2483                 } else {
2484                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2485                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2486                         return 1;
2487                 }
2488                 break;
2489         case PC_QUERIES:
2490                 if ( c->value_int <= 0 ) {
2491                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2492                         Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2493                         return( 1 );
2494                 }
2495                 cm->max_queries = c->value_int;
2496                 break;
2497         }
2498         return rc;
2499 }
2500
2501 static int
2502 pcache_db_config(
2503         BackendDB       *be,
2504         const char      *fname,
2505         int             lineno,
2506         int             argc,
2507         char            **argv
2508 )
2509 {
2510         slap_overinst   *on = (slap_overinst *)be->bd_info;
2511         cache_manager*  cm = on->on_bi.bi_private;
2512
2513         /* Something for the cache database? */
2514         if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2515                 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2516                         argc, argv );
2517         return SLAP_CONF_UNKNOWN;
2518 }
2519
2520 static int
2521 pcache_db_init(
2522         BackendDB *be,
2523         ConfigReply *cr)
2524 {
2525         slap_overinst *on = (slap_overinst *)be->bd_info;
2526         cache_manager *cm;
2527         query_manager *qm;
2528
2529         cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2530         on->on_bi.bi_private = cm;
2531
2532         qm = (query_manager*)ch_malloc(sizeof(query_manager));
2533
2534         cm->db = *be;
2535         SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2536         cm->db.be_private = NULL;
2537         cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2538         cm->qm = qm;
2539         cm->numattrsets = 0;
2540         cm->num_entries_limit = 5;
2541         cm->num_cached_queries = 0;
2542         cm->max_entries = 0;
2543         cm->cur_entries = 0;
2544         cm->max_queries = 10000;
2545         cm->save_queries = 0;
2546         cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2547         cm->cc_period = 1000;
2548         cm->cc_paused = 0;
2549
2550         qm->attr_sets = NULL;
2551         qm->templates = NULL;
2552         qm->lru_top = NULL;
2553         qm->lru_bottom = NULL;
2554
2555         qm->qcfunc = query_containment;
2556         qm->crfunc = cache_replacement;
2557         qm->addfunc = add_query;
2558         ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2559
2560         ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2561         return 0;
2562 }
2563
2564 static int
2565 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2566 {
2567         assert( op->o_tag == LDAP_REQ_SEARCH );
2568
2569         if ( rs->sr_type == REP_SEARCH ) {
2570                 Attribute       *a;
2571
2572                 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2573                 if ( a != NULL ) {
2574                         BerVarray       *valsp;
2575
2576                         assert( a->a_nvals != NULL );
2577
2578                         valsp = op->o_callback->sc_private;
2579                         assert( *valsp == NULL );
2580
2581                         ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2582                 }
2583         }
2584
2585         return 0;
2586 }
2587
2588 static int
2589 pcache_db_open(
2590         BackendDB *be,
2591         ConfigReply *cr )
2592 {
2593         slap_overinst   *on = (slap_overinst *)be->bd_info;
2594         cache_manager   *cm = on->on_bi.bi_private;
2595         query_manager*  qm = cm->qm;
2596         int             i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2597
2598         /* check attr sets */
2599         for ( i = 0; i < cm->numattrsets; i++) {
2600                 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2601                         if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2602                                 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2603                                 rf++;
2604
2605                         } else {
2606                                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2607                         }
2608                         ncf++;
2609
2610                 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2611                         Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2612                         nrf++;
2613                 }
2614         }
2615
2616         if ( ncf || rf || nrf ) {
2617                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2618                 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2619                 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2620
2621                 if ( rf > 0 ) {
2622                         return 1;
2623                 }
2624         }
2625
2626         /* need to inherit something from the original database... */
2627         cm->db.be_def_limit = be->be_def_limit;
2628         cm->db.be_limits = be->be_limits;
2629         cm->db.be_acl = be->be_acl;
2630         cm->db.be_dfltaccess = be->be_dfltaccess;
2631
2632         if ( SLAP_DBMONITORING( be ) ) {
2633                 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2634
2635         } else {
2636                 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2637         }
2638
2639         rc = backend_startup_one( &cm->db, NULL );
2640
2641         /* There is no runqueue in TOOL mode */
2642         if ( slapMode & SLAP_SERVER_MODE ) {
2643                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2644                 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2645                         consistency_check, on,
2646                         "pcache_consistency", be->be_suffix[0].bv_val );
2647                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2648
2649                 /* Cached database must have the rootdn */
2650                 if ( BER_BVISNULL( &cm->db.be_rootndn )
2651                                 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2652                 {
2653                         Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2654                                 "underlying database of type \"%s\"\n"
2655                                 "    serving naming context \"%s\"\n"
2656                                 "    has no \"rootdn\", required by \"proxycache\".\n",
2657                                 on->on_info->oi_orig->bi_type,
2658                                 cm->db.be_suffix[0].bv_val, 0 );
2659                         return 1;
2660                 }
2661
2662                 if ( cm->save_queries ) {
2663                         void            *thrctx = ldap_pvt_thread_pool_context();
2664                         Connection      conn = { 0 };
2665                         OperationBuffer opbuf;
2666                         Operation       *op;
2667                         slap_callback   cb = { 0 };
2668                         SlapReply       rs = { 0 };
2669                         BerVarray       vals = NULL;
2670                         AttributeName   attrs[ 2 ] = { 0 };
2671
2672                         connection_fake_init( &conn, &opbuf, thrctx );
2673                         op = &opbuf.ob_op;
2674
2675                         op->o_bd = &cm->db;
2676
2677                         op->o_tag = LDAP_REQ_SEARCH;
2678                         op->o_protocol = LDAP_VERSION3;
2679                         cb.sc_response = pcache_cachedquery_open_cb;
2680                         cb.sc_private = &vals;
2681                         op->o_callback = &cb;
2682                         op->o_time = slap_get_time();
2683                         op->o_do_not_cache = 1;
2684                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
2685
2686                         op->o_dn = cm->db.be_rootdn;
2687                         op->o_ndn = cm->db.be_rootndn;
2688                         op->o_req_dn = cm->db.be_suffix[ 0 ];
2689                         op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2690
2691                         op->ors_scope = LDAP_SCOPE_BASE;
2692                         op->ors_deref = LDAP_DEREF_NEVER;
2693                         op->ors_slimit = 1;
2694                         op->ors_tlimit = SLAP_NO_LIMIT;
2695                         ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
2696                         op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
2697                         if ( op->ors_filter != NULL ) {
2698                                 attrs[ 0 ].an_desc = ad_cachedQueryURL;
2699                                 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
2700                                 op->ors_attrs = attrs;
2701                                 op->ors_attrsonly = 0;
2702
2703                                 rc = op->o_bd->be_search( op, &rs );
2704                                 if ( rc == LDAP_SUCCESS && vals != NULL ) {
2705                                         int     i;
2706
2707                                         for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2708                                                 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
2709                                                         cm->num_cached_queries++;
2710                                                 }
2711                                         }
2712
2713                                         ber_bvarray_free_x( vals, op->o_tmpmemctx );
2714                                 }
2715
2716                                 filter_free_x( op, op->ors_filter );
2717                         }
2718
2719                         /* ignore errors */
2720                         rc = 0;
2721                 }
2722         }
2723
2724         return rc;
2725 }
2726
2727 static void
2728 pcache_free_qbase( void *v )
2729 {
2730         Qbase *qb = v;
2731         int i;
2732
2733         for (i=0; i<3; i++)
2734                 tavl_free( qb->scopes[i], NULL );
2735         ch_free( qb );
2736 }
2737
2738 static int
2739 pcache_db_close(
2740         BackendDB *be,
2741         ConfigReply *cr
2742 )
2743 {
2744         slap_overinst *on = (slap_overinst *)be->bd_info;
2745         cache_manager *cm = on->on_bi.bi_private;
2746         query_manager *qm = cm->qm;
2747         QueryTemplate *tm;
2748         int i, rc = 0;
2749
2750         if ( cm->save_queries && qm->templates != NULL ) {
2751                 CachedQuery     *qc;
2752                 BerVarray       vals = NULL;
2753
2754                 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
2755                         for ( qc = tm->query; qc; qc = qc->next ) {
2756                                 struct berval   bv;
2757
2758                                 if ( query2url( qc, &bv ) == 0 ) {
2759                                         ber_bvarray_add( &vals, &bv );
2760                                 }
2761                         }
2762                 }
2763
2764                 if ( vals != NULL ) {
2765                         void            *thrctx = ldap_pvt_thread_pool_context();
2766                         Connection      conn = { 0 };
2767                         OperationBuffer opbuf;
2768                         Operation       *op;
2769                         slap_callback   cb = { 0 };
2770
2771                         SlapReply       rs = { REP_RESULT };
2772                         Modifications   mod = { 0 };
2773
2774                         connection_fake_init( &conn, &opbuf, thrctx );
2775                         op = &opbuf.ob_op;
2776
2777                         op->o_bd = &cm->db;
2778                         op->o_dn = cm->db.be_rootdn;
2779                         op->o_ndn = cm->db.be_rootndn;
2780
2781                         op->o_tag = LDAP_REQ_MODIFY;
2782                         op->o_protocol = LDAP_VERSION3;
2783                         cb.sc_response = slap_null_cb;
2784                         op->o_callback = &cb;
2785                         op->o_time = slap_get_time();
2786                         op->o_do_not_cache = 1;
2787                         op->o_managedsait = SLAP_CONTROL_CRITICAL;
2788
2789                         op->o_req_dn = op->o_bd->be_suffix[0];
2790                         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2791
2792                         mod.sml_op = LDAP_MOD_REPLACE;
2793                         mod.sml_flags = 0;
2794                         mod.sml_desc = ad_cachedQueryURL;
2795                         mod.sml_type = ad_cachedQueryURL->ad_cname;
2796                         mod.sml_values = vals;
2797                         mod.sml_nvalues = NULL;
2798                         mod.sml_next = NULL;
2799                         Debug( pcache_debug,
2800                                 "SETTING CACHED QUERY URLS\n",
2801                                 0, 0, 0 );
2802
2803                         op->orm_modlist = &mod;
2804
2805                         op->o_bd->be_modify( op, &rs );
2806
2807                         ber_bvarray_free( vals );
2808                 }
2809         }
2810
2811         /* cleanup stuff inherited from the original database... */
2812         cm->db.be_limits = NULL;
2813         cm->db.be_acl = NULL;
2814
2815         /* stop the thread ... */
2816         if ( cm->cc_arg ) {
2817                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2818                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
2819                         ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
2820                 }
2821                 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
2822                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2823         }
2824
2825         if ( cm->db.bd_info->bi_db_close ) {
2826                 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
2827         }
2828         while ( (tm = qm->templates) != NULL ) {
2829                 CachedQuery *qc, *qn;
2830                 qm->templates = tm->qmnext;
2831                 for ( qc = tm->query; qc; qc = qn ) {
2832                         qn = qc->next;
2833                         free_query( qc );
2834                 }
2835                 avl_free( tm->qbase, pcache_free_qbase );
2836                 free( tm->querystr.bv_val );
2837                 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
2838                 free( tm->t_attrs.attrs );
2839                 free( tm );
2840         }
2841
2842         for ( i=0; i<cm->numattrsets; i++ ) {
2843                 free( qm->attr_sets[i].attrs );
2844         }
2845         free( qm->attr_sets );
2846         qm->attr_sets = NULL;
2847
2848         return rc;
2849 }
2850
2851 static int
2852 pcache_db_destroy(
2853         BackendDB *be,
2854         ConfigReply *cr
2855 )
2856 {
2857         slap_overinst *on = (slap_overinst *)be->bd_info;
2858         cache_manager *cm = on->on_bi.bi_private;
2859         query_manager *qm = cm->qm;
2860
2861         if ( cm->db.be_private != NULL ) {
2862                 backend_stopdown_one( &cm->db );
2863         }
2864
2865         ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2866         ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2867         free( qm );
2868         free( cm );
2869
2870         return 0;
2871 }
2872
2873 static slap_overinst pcache;
2874
2875 static char *obsolete_names[] = {
2876         "proxycache",
2877         NULL
2878 };
2879
2880 int pcache_initialize()
2881 {
2882         int i, code;
2883         struct berval debugbv = BER_BVC("pcache");
2884
2885         code = slap_loglevel_get( &debugbv, &pcache_debug );
2886         if ( code ) {
2887                 return code;
2888         }
2889
2890         for ( i = 0; as[i].desc != NULL; i++ ) {
2891                 code = register_at( as[i].desc, as[i].adp, 0 );
2892                 if ( code ) {
2893                         Debug( LDAP_DEBUG_ANY,
2894                                 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
2895                         return code;
2896                 }
2897         }
2898
2899         pcache.on_bi.bi_type = "pcache";
2900         pcache.on_bi.bi_obsolete_names = obsolete_names;
2901         pcache.on_bi.bi_db_init = pcache_db_init;
2902         pcache.on_bi.bi_db_config = pcache_db_config;
2903         pcache.on_bi.bi_db_open = pcache_db_open;
2904         pcache.on_bi.bi_db_close = pcache_db_close;
2905         pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2906
2907         pcache.on_bi.bi_op_search = pcache_op_search;
2908
2909         pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2910
2911         pcache.on_bi.bi_cf_ocs = pcocs;
2912
2913         code = config_register_schema( pccfg, pcocs );
2914         if ( code ) return code;
2915
2916         return overlay_register( &pcache );
2917 }
2918
2919 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2920 int init_module(int argc, char *argv[]) {
2921         return pcache_initialize();
2922 }
2923 #endif
2924
2925 #endif  /* defined(SLAPD_OVER_PROXYCACHE) */