2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2007 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
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>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
40 * Control that allows to access the private DB
41 * instead of the public one
43 #define PCACHE_CONTROL_PRIVDB "1.3.6.1.4.1.4203.666.11.9.5.1"
46 * Extended Operation that allows to remove a query from the cache
48 #define PCACHE_EXOP_QUERY_DELETE "1.3.6.1.4.1.4203.666.11.9.6.1"
51 /* query cache structs */
54 typedef struct Query_s {
55 Filter* filter; /* Search Filter */
56 struct berval base; /* Search Base */
57 int scope; /* Search scope */
60 struct query_template_s;
62 typedef struct Qbase_s {
63 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
68 /* struct representing a cached query */
69 typedef struct cached_query_s {
74 struct berval q_uuid; /* query identifier */
76 struct query_template_s *qtemp; /* template of the query */
77 time_t expiry_time; /* time till the query is considered valid */
78 struct cached_query_s *next; /* next query in the template */
79 struct cached_query_s *prev; /* previous query in the template */
80 struct cached_query_s *lru_up; /* previous query in the LRU list */
81 struct cached_query_s *lru_down; /* next query in the LRU list */
82 ldap_pvt_thread_rdwr_t rwlock;
88 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
90 * <base> ::= CachedQuery.qbase->base
91 * <scope> ::= CachedQuery.scope
92 * <filter> ::= filter2bv(CachedQuery.filter)
93 * <uuid> ::= CachedQuery.q_uuid
94 * <attrset> ::= CachedQuery.qtemp->attr_set_index
95 * <expiry> ::= CachedQuery.expiry_time
97 * quick hack: parse URI, call add_query() and then fix
98 * CachedQuery.expiry_time and CachedQuery.q_uuid
102 * Represents a set of projected attributes.
106 struct query_template_s *templates;
107 AttributeName* attrs; /* specifies the set */
109 #define PC_CONFIGURED (0x1)
110 #define PC_REFERENCED (0x2)
111 #define PC_GOT_OC (0x4)
112 int count; /* number of attributes */
115 /* struct representing a query template
116 * e.g. template string = &(cn=)(mail=)
118 typedef struct query_template_s {
119 struct query_template_s *qtnext;
120 struct query_template_s *qmnext;
123 CachedQuery* query; /* most recent query cached for the template */
124 CachedQuery* query_last; /* oldest query cached for the template */
125 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
126 struct berval querystr; /* Filter string corresponding to the QT */
128 int attr_set_index; /* determines the projected attributes */
129 int no_of_queries; /* Total number of queries in the template */
130 time_t ttl; /* TTL for the queries of this template */
131 time_t negttl; /* TTL for negative results */
132 time_t limitttl; /* TTL for sizelimit exceeding results */
133 struct attr_set t_attrs; /* filter attrs + attr_set */
141 } pc_caching_reason_t;
143 static const char *pc_caching_reason_str[] = {
152 struct query_manager_s;
154 /* prototypes for functions for 1) query containment
155 * 2) query addition, 3) cache replacement
157 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
158 Query*, QueryTemplate*);
159 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
160 Query*, QueryTemplate*, pc_caching_reason_t, int wlock);
161 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
163 /* LDAP query cache */
164 typedef struct query_manager_s {
165 struct attr_set* attr_sets; /* possible sets of projected attributes */
166 QueryTemplate* templates; /* cacheable templates */
168 CachedQuery* lru_top; /* top and bottom of LRU list */
169 CachedQuery* lru_bottom;
171 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
173 /* Query cache methods */
174 QCfunc *qcfunc; /* Query containment*/
175 CRfunc *crfunc; /* cache replacement */
176 AddQueryfunc *addfunc; /* add query */
179 /* LDAP query cache manager */
180 typedef struct cache_manager_s {
181 BackendDB db; /* underlying database */
182 unsigned long num_cached_queries; /* total number of cached queries */
183 unsigned long max_queries; /* upper bound on # of cached queries */
184 int save_queries; /* save cached queries across restarts */
185 int numattrsets; /* number of attribute sets */
186 int cur_entries; /* current number of entries cached */
187 int max_entries; /* max number of entries cached */
188 int num_entries_limit; /* max # of entries in a cacheable query */
190 char response_cb; /* install the response callback
191 * at the tail of the callback list */
192 #define PCACHE_RESPONSE_CB_HEAD 0
193 #define PCACHE_RESPONSE_CB_TAIL 1
195 time_t cc_period; /* interval between successive consistency checks (sec) */
199 ldap_pvt_thread_mutex_t cache_mutex;
201 query_manager* qm; /* query cache managed by the cache manager */
204 static int pcache_debug;
206 #ifdef PCACHE_CONTROL_PRIVDB
207 static int privDB_cid;
208 #endif /* PCACHE_CONTROL_PRIVDB */
210 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
213 AttributeDescription **adp;
215 { "( 1.3.6.1.4.1.4203.666.11.9.1.1 "
217 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
218 "EQUALITY octetStringMatch "
219 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
220 "NO-USER-MODIFICATION "
221 "USAGE directoryOperation )",
223 { "( 1.3.6.1.4.1.4203.666.11.9.1.2 "
224 "NAME 'cachedQueryURL' "
225 "DESC 'URI describing a cached query' "
226 "EQUALITY caseExactMatch "
227 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
228 "NO-USER-MODIFICATION "
229 "USAGE directoryOperation )",
230 &ad_cachedQueryURL },
239 AttributeName** filter_attrs,
241 int* filter_got_oc );
248 QueryTemplate *templ,
249 pc_caching_reason_t why,
256 struct berval *query_uuid );
259 * Turn a cached query into its URL representation
262 query2url( Operation *op, CachedQuery *q, struct berval *urlbv )
264 struct berval bv_scope,
266 char attrset_buf[ 32 ],
269 ber_len_t attrset_len,
272 ldap_pvt_scope2bv( q->scope, &bv_scope );
273 filter2bv_x( op, q->filter, &bv_filter );
274 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
275 "%lu", (unsigned long)q->qtemp->attr_set_index );
276 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
277 "%lu", (unsigned long)q->expiry_time );
279 urlbv->bv_len = STRLENOF( "ldap:///" )
280 + q->qbase->base.bv_len
285 + STRLENOF( "?x-uuid=" )
287 + STRLENOF( ",x-attrset=" )
289 + STRLENOF( ",x-expiry=" )
291 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
292 ptr = lutil_strcopy( ptr, "ldap:///" );
293 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
294 ptr = lutil_strcopy( ptr, "??" );
295 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
296 ptr = lutil_strcopy( ptr, "?" );
297 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
298 ptr = lutil_strcopy( ptr, "?x-uuid=" );
299 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
300 ptr = lutil_strcopy( ptr, ",x-attrset=" );
301 ptr = lutil_strcopy( ptr, attrset_buf );
302 ptr = lutil_strcopy( ptr, ",x-expiry=" );
303 ptr = lutil_strcopy( ptr, expiry_buf );
305 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
311 * Turn an URL representing a formerly cached query into a cached query,
312 * and try to cache it
323 LDAPURLDesc *lud = NULL;
325 tempstr = BER_BVNULL,
335 rc = ldap_url_parse( url, &lud );
336 if ( rc != LDAP_URL_SUCCESS ) {
340 /* non-allowed fields */
341 if ( lud->lud_host != NULL ) {
346 if ( lud->lud_attrs != NULL ) {
352 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
357 /* required fields */
358 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
363 switch ( lud->lud_scope ) {
364 case LDAP_SCOPE_BASE:
365 case LDAP_SCOPE_ONELEVEL:
366 case LDAP_SCOPE_SUBTREE:
367 case LDAP_SCOPE_SUBORDINATE:
375 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
380 if ( lud->lud_exts == NULL ) {
385 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
386 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
387 struct berval tmpUUID;
388 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
390 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
391 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
392 if ( rc != LDAP_SUCCESS ) {
397 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
398 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
404 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
407 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
411 expiry_time = (time_t)l;
425 if ( !got_attrset ) {
435 /* ignore expired queries */
436 if ( expiry_time <= slap_get_time()) {
438 SlapReply rs2 = { 0 };
440 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
442 (void)remove_query_data( &op2, &rs2, &uuid );
447 ber_str2bv( lud->lud_dn, 0, 0, &base );
448 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
449 if ( rc != LDAP_SUCCESS ) {
452 query.scope = lud->lud_scope;
453 query.filter = str2filter( lud->lud_filter );
455 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
457 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
458 ch_free( tempstr.bv_val );
463 /* check for query containment */
464 qt = qm->attr_sets[attrset].templates;
465 for ( ; qt; qt = qt->qtnext ) {
466 /* find if template i can potentially answer tempstr */
467 if ( bvmatch( &qt->querystr, &tempstr ) ) {
477 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
479 cq->expiry_time = expiry_time;
482 /* it's now into cq->filter */
492 if ( query.filter != NULL ) filter_free( query.filter );
493 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
494 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
495 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
496 if ( lud != NULL ) ldap_free_urldesc( lud );
501 /* Return 1 for an added entry, else 0 */
506 struct berval* query_uuid )
509 Modifications* modlist = NULL;
510 const char* text = NULL;
512 char textbuf[SLAP_TEXT_BUFLEN];
513 size_t textlen = sizeof(textbuf);
515 SlapReply sreply = {REP_RESULT};
517 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
522 /* add queryId attribute */
523 attr_merge_one( e, ad_queryId, query_uuid, NULL );
525 /* append the attribute list from the fetched entry */
526 e->e_attrs->a_next = attr;
528 op->o_tag = LDAP_REQ_ADD;
529 op->o_protocol = LDAP_VERSION3;
530 op->o_callback = &cb;
531 op->o_time = slap_get_time();
532 op->o_do_not_cache = 1;
535 op->o_req_dn = e->e_name;
536 op->o_req_ndn = e->e_nname;
537 rc = op->o_bd->be_add( op, &sreply );
539 if ( rc != LDAP_SUCCESS ) {
540 if ( rc == LDAP_ALREADY_EXISTS ) {
541 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
542 modlist->sml_op = LDAP_MOD_ADD;
543 op->o_tag = LDAP_REQ_MODIFY;
544 op->orm_modlist = modlist;
545 op->o_bd->be_modify( op, &sreply );
546 slap_mods_free( modlist, 1 );
547 } else if ( rc == LDAP_REFERRAL ||
548 rc == LDAP_NO_SUCH_OBJECT ) {
549 syncrepl_add_glue( op, e );
558 if ( op->ora_e == e )
559 be_entry_release_w( op, e );
566 /* Length-ordered sort on normalized DNs */
567 static int pcache_dn_cmp( const void *v1, const void *v2 )
569 const Qbase *q1 = v1, *q2 = v2;
571 int rc = q1->base.bv_len - q2->base.bv_len;
573 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
577 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
580 dif = bv1->bv_len - bv2->bv_len;
582 if ( dif > 0 ) len -= dif;
583 len = memcmp( bv1->bv_val, bv2->bv_val, len );
589 /* compare the first value in each filter */
590 static int pcache_filter_cmp( const void *v1, const void *v2 )
592 const CachedQuery *q1 = v1, *q2 =v2;
593 int rc, weight1, weight2;
595 switch( q1->first->f_choice ) {
596 case LDAP_FILTER_PRESENT:
599 case LDAP_FILTER_EQUALITY:
607 switch( q2->first->f_choice ) {
608 case LDAP_FILTER_PRESENT:
611 case LDAP_FILTER_EQUALITY:
619 rc = weight1 - weight2;
624 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
627 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
629 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
630 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
631 rc = lex_bvcmp( &q1->first->f_sub_initial,
632 &q2->first->f_sub_initial );
636 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
640 if ( q1->first->f_sub_any ) {
641 if ( q2->first->f_sub_any ) {
642 rc = lex_bvcmp( q1->first->f_sub_any,
643 q2->first->f_sub_any );
647 } else if ( q2->first->f_sub_any ) {
651 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
652 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
653 rc = lex_bvcmp( &q1->first->f_sub_final,
654 &q2->first->f_sub_final );
658 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
662 rc = lex_bvcmp( &q1->first->f_mr_value,
663 &q2->first->f_mr_value );
672 /* add query on top of LRU list */
674 add_query_on_top (query_manager* qm, CachedQuery* qc)
676 CachedQuery* top = qm->lru_top;
687 Debug( pcache_debug, "Base of added query = %s\n",
688 qc->qbase->base.bv_val, 0, 0 );
691 /* remove_query from LRU list */
694 remove_query (query_manager* qm, CachedQuery* qc)
717 qc->lru_up = qc->lru_down = NULL;
720 /* find and remove string2 from string1
721 * from start if position = 1,
722 * from end if position = 3,
723 * from anywhere if position = 2
724 * string1 is overwritten if position = 2.
728 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
739 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
740 ber2->bv_val, ber2->bv_len )) {
742 ber1->bv_val += ber2->bv_len;
743 ber1->bv_len -= ber2->bv_len;
748 ber1->bv_val[ber1->bv_len] = '\0';
749 temp = strstr( ber1->bv_val, ber2->bv_val );
751 strcpy( temp, temp+ber2->bv_len );
752 ber1->bv_len -= ber2->bv_len;
758 if ( ber1->bv_len >= ber2->bv_len &&
759 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
762 ber1->bv_len -= ber2->bv_len;
770 static struct berval*
771 merge_init_final(Operation *op, struct berval* init, struct berval* any,
772 struct berval* final)
774 struct berval* merged, *temp;
775 int i, any_count, count;
777 for (any_count=0; any && any[any_count].bv_val; any_count++)
787 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
792 ber_dupbv_x( temp, init, op->o_tmpmemctx );
796 for (i=0; i<any_count; i++) {
797 ber_dupbv_x( temp, any, op->o_tmpmemctx );
802 ber_dupbv_x( temp, final, op->o_tmpmemctx );
809 /* Each element in stored must be found in incoming. Incoming is overwritten.
812 strings_containment(struct berval* stored, struct berval* incoming)
814 struct berval* element;
818 for ( element=stored; element->bv_val != NULL; element++ ) {
819 for (j = k; incoming[j].bv_val != NULL; j++) {
820 if (find_and_remove(&(incoming[j]), element, 2)) {
837 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
841 struct berval init_incoming;
842 struct berval final_incoming;
843 struct berval *remaining_incoming = NULL;
845 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
846 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
849 init_incoming = incoming->f_sub_initial;
850 final_incoming = incoming->f_sub_final;
852 if (find_and_remove(&init_incoming,
853 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
854 &(stored->f_sub_final), 3))
856 if (stored->f_sub_any == NULL) {
860 remaining_incoming = merge_init_final(op, &init_incoming,
861 incoming->f_sub_any, &final_incoming);
862 rc = strings_containment(stored->f_sub_any, remaining_incoming);
863 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
870 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
872 struct berval incoming_val[2];
875 incoming_val[1] = incoming->f_av_value;
877 if (find_and_remove(incoming_val+1,
878 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
879 &(stored->f_sub_final), 3)) {
880 if (stored->f_sub_any == NULL){
884 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
885 BER_BVZERO( incoming_val+1 );
886 rc = strings_containment(stored->f_sub_any, incoming_val);
887 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
894 filter_first( Filter *f )
896 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
903 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
907 MatchingRule* mrule = NULL;
908 int res=0, eqpass= 0;
916 /* substring matches sort to the end, and we just have to
917 * walk the entire list.
919 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
920 ptr = tavl_end( root, 1 );
923 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
924 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
933 /* an incoming substr query can only be satisfied by a cached
936 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
937 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
940 /* an incoming eq query can be satisfied by a cached eq or substr
943 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
945 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
946 nextpass: eqpass = 1;
947 ptr = tavl_end( root, 1 );
952 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
958 switch (fs->f_choice) {
959 case LDAP_FILTER_EQUALITY:
960 if (fi->f_choice == LDAP_FILTER_EQUALITY)
961 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
967 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
974 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
975 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
976 &(fi->f_ava->aa_value),
977 &(fs->f_ava->aa_value), &text);
978 if (rc != LDAP_SUCCESS) {
981 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
984 switch (fs->f_choice) {
986 case LDAP_FILTER_AND:
991 case LDAP_FILTER_SUBSTRINGS:
992 /* check if the equality query can be
993 * answered with cached substring query */
994 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
995 && substr_containment_equality( op,
998 /* check if the substring query can be
999 * answered with cached substring query */
1000 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1001 ) && substr_containment_substr( op,
1007 case LDAP_FILTER_PRESENT:
1012 case LDAP_FILTER_EQUALITY:
1018 case LDAP_FILTER_GE:
1019 if (mrule && ret >= 0)
1024 case LDAP_FILTER_LE:
1025 if (mrule && ret <= 0)
1030 case LDAP_FILTER_NOT:
1036 } while((res) && (fi != NULL) && (fs != NULL));
1040 ptr = tavl_next( ptr, dir );
1045 /* check whether query is contained in any of
1046 * the cached queries in template
1048 static CachedQuery *
1049 query_containment(Operation *op, query_manager *qm,
1051 QueryTemplate *templa)
1054 int depth = 0, tscope;
1055 Qbase qbase, *qbptr = NULL;
1058 if (query->filter != NULL) {
1061 Debug( pcache_debug, "Lock QC index = %p\n",
1062 (void *) templa, 0, 0 );
1063 qbase.base = query->base;
1065 first = filter_first( query->filter );
1067 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1070 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1072 tscope = query->scope;
1073 /* Find a matching scope:
1074 * match at depth 0 OK
1077 * subord at depth > 0 OK
1078 * subtree at any depth OK
1080 * subtree or subord at any depth OK
1082 * subtree or subord at any depth OK
1084 * subord at depth > 0 OK
1085 * subtree at any depth OK
1087 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1088 switch ( query->scope ) {
1089 case LDAP_SCOPE_BASE:
1090 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1091 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1092 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1094 case LDAP_SCOPE_ONE:
1095 if ( tscope == LDAP_SCOPE_BASE )
1096 tscope = LDAP_SCOPE_ONE;
1097 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1098 if ( !depth ) break;
1099 if ( tscope < LDAP_SCOPE_SUBTREE )
1100 tscope = LDAP_SCOPE_SUBTREE;
1102 case LDAP_SCOPE_SUBTREE:
1103 if ( tscope < LDAP_SCOPE_SUBTREE )
1104 tscope = LDAP_SCOPE_SUBTREE;
1105 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1107 case LDAP_SCOPE_CHILDREN:
1108 if ( tscope < LDAP_SCOPE_SUBTREE )
1109 tscope = LDAP_SCOPE_SUBTREE;
1112 if ( !qbptr->scopes[tscope] ) continue;
1115 qc = find_filter( op, qbptr->scopes[tscope],
1116 query->filter, first );
1118 if ( qc->q_sizelimit ) {
1119 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1122 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1123 if (qm->lru_top != qc) {
1124 remove_query(qm, qc);
1125 add_query_on_top(qm, qc);
1127 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1132 if ( be_issuffix( op->o_bd, &qbase.base ))
1135 dnParent( &qbase.base, &pdn );
1140 Debug( pcache_debug,
1141 "Not answerable: Unlock QC index=%p\n",
1142 (void *) templa, 0, 0 );
1143 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1149 free_query (CachedQuery* qc)
1151 free(qc->q_uuid.bv_val);
1152 filter_free(qc->filter);
1157 /* Add query to query cache, the returned Query is locked for writing */
1158 static CachedQuery *
1163 QueryTemplate *templ,
1164 pc_caching_reason_t why,
1167 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1173 new_cached_query->qtemp = templ;
1174 BER_BVZERO( &new_cached_query->q_uuid );
1175 new_cached_query->q_sizelimit = 0;
1183 ttl = templ->negttl;
1187 ttl = templ->limitttl;
1194 new_cached_query->expiry_time = slap_get_time() + ttl;
1195 new_cached_query->lru_up = NULL;
1196 new_cached_query->lru_down = NULL;
1197 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1198 (long) new_cached_query->expiry_time,
1199 pc_caching_reason_str[ why ], 0 );
1201 new_cached_query->scope = query->scope;
1202 new_cached_query->filter = query->filter;
1203 new_cached_query->first = first = filter_first( query->filter );
1205 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1207 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1209 qb.base = query->base;
1211 /* Adding a query */
1212 Debug( pcache_debug, "Lock AQ index = %p\n",
1213 (void *) templ, 0, 0 );
1214 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1215 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1217 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1218 qbase->base.bv_len = qb.base.bv_len;
1219 qbase->base.bv_val = (char *)(qbase+1);
1220 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1221 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1222 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1224 new_cached_query->next = templ->query;
1225 new_cached_query->prev = NULL;
1226 new_cached_query->qbase = qbase;
1227 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1228 pcache_filter_cmp, avl_dup_error );
1231 if (templ->query == NULL)
1232 templ->query_last = new_cached_query;
1234 templ->query->prev = new_cached_query;
1235 templ->query = new_cached_query;
1236 templ->no_of_queries++;
1238 ch_free( new_cached_query );
1239 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1240 query->filter, first );
1241 filter_free( query->filter );
1243 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1244 (void *) templ, templ->no_of_queries, 0 );
1246 Debug( pcache_debug, "Unlock AQ index = %p \n",
1247 (void *) templ, 0, 0 );
1248 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1250 /* Adding on top of LRU list */
1252 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1253 add_query_on_top(qm, new_cached_query);
1254 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1256 return rc == 0 ? new_cached_query : NULL;
1260 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1262 if (!qc->prev && !qc->next) {
1263 template->query_last = template->query = NULL;
1264 } else if (qc->prev == NULL) {
1265 qc->next->prev = NULL;
1266 template->query = qc->next;
1267 } else if (qc->next == NULL) {
1268 qc->prev->next = NULL;
1269 template->query_last = qc->prev;
1271 qc->next->prev = qc->prev;
1272 qc->prev->next = qc->next;
1274 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1275 qc->qbase->queries--;
1276 if ( qc->qbase->queries == 0 ) {
1277 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1278 ch_free( qc->qbase );
1282 template->no_of_queries--;
1285 /* remove bottom query of LRU list from the query cache */
1287 * NOTE: slight change in functionality.
1289 * - if result->bv_val is NULL, the query at the bottom of the LRU
1291 * - otherwise, the query whose UUID is *result is removed
1292 * - if not found, result->bv_val is zeroed
1295 cache_replacement(query_manager* qm, struct berval *result)
1297 CachedQuery* bottom;
1298 QueryTemplate *temp;
1300 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1301 if ( BER_BVISNULL( result ) ) {
1302 bottom = qm->lru_bottom;
1305 Debug ( pcache_debug,
1306 "Cache replacement invoked without "
1307 "any query in LRU list\n", 0, 0, 0 );
1308 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1313 for ( bottom = qm->lru_bottom;
1315 bottom = bottom->lru_up )
1317 if ( bvmatch( result, &bottom->q_uuid ) ) {
1323 Debug ( pcache_debug,
1324 "Could not find query with uuid=\"%s\""
1325 "in LRU list\n", result->bv_val, 0, 0 );
1326 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1327 BER_BVZERO( result );
1332 temp = bottom->qtemp;
1333 remove_query(qm, bottom);
1334 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1336 *result = bottom->q_uuid;
1337 BER_BVZERO( &bottom->q_uuid );
1339 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1340 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1341 remove_from_template(bottom, temp);
1342 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1343 (void *) temp, temp->no_of_queries, 0 );
1344 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1345 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1350 struct query_info *next;
1362 struct query_info *qi;
1365 if ( rs->sr_type != REP_SEARCH ) return 0;
1367 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1368 if ( attr == NULL ) return 0;
1370 for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1372 assert( count > 0 );
1373 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1374 qi->next = op->o_callback->sc_private;
1375 op->o_callback->sc_private = qi;
1376 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1377 qi->del = ( count == 1 );
1386 struct berval *query_uuid )
1388 struct query_info *qi, *qnext;
1389 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1390 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1391 Filter filter = {LDAP_FILTER_EQUALITY};
1392 SlapReply sreply = {REP_RESULT};
1393 slap_callback cb = { NULL, remove_func, NULL, NULL };
1396 sreply.sr_entry = NULL;
1397 sreply.sr_nentries = 0;
1398 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1399 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1400 filter.f_ava = &ava;
1401 filter.f_av_desc = ad_queryId;
1402 filter.f_av_value = *query_uuid;
1404 op->o_tag = LDAP_REQ_SEARCH;
1405 op->o_protocol = LDAP_VERSION3;
1406 op->o_callback = &cb;
1407 op->o_time = slap_get_time();
1408 op->o_do_not_cache = 1;
1410 op->o_req_dn = op->o_bd->be_suffix[0];
1411 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1412 op->ors_scope = LDAP_SCOPE_SUBTREE;
1413 op->ors_deref = LDAP_DEREF_NEVER;
1414 op->ors_slimit = SLAP_NO_LIMIT;
1415 op->ors_tlimit = SLAP_NO_LIMIT;
1416 op->ors_filter = &filter;
1417 op->ors_filterstr.bv_val = filter_str;
1418 op->ors_filterstr.bv_len = strlen(filter_str);
1419 op->ors_attrs = NULL;
1420 op->ors_attrsonly = 0;
1422 op->o_bd->be_search( op, &sreply );
1424 for ( qi=cb.sc_private; qi; qi=qnext ) {
1427 op->o_req_dn = qi->xdn;
1428 op->o_req_ndn = qi->xdn;
1431 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1432 query_uuid->bv_val, 0, 0 );
1434 op->o_tag = LDAP_REQ_DELETE;
1436 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1442 struct berval vals[2];
1444 vals[0] = *query_uuid;
1445 vals[1].bv_val = NULL;
1447 mod.sml_op = LDAP_MOD_DELETE;
1449 mod.sml_desc = ad_queryId;
1450 mod.sml_type = ad_queryId->ad_cname;
1451 mod.sml_values = vals;
1452 mod.sml_nvalues = NULL;
1453 mod.sml_next = NULL;
1454 Debug( pcache_debug,
1455 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1456 query_uuid->bv_val, 0, 0 );
1458 op->orm_modlist = &mod;
1460 op->o_bd->be_modify( op, &sreply );
1462 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1463 op->o_tmpfree( qi, op->o_tmpmemctx );
1470 AttributeName* attrs,
1479 struct berval *fstr,
1480 AttributeName** filter_attrs,
1482 int* filter_got_oc )
1484 AttributeDescription *ad;
1486 switch ( f->f_choice ) {
1487 case LDAP_FILTER_EQUALITY:
1489 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1490 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1493 case LDAP_FILTER_GE:
1495 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1496 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1499 case LDAP_FILTER_LE:
1501 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1502 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1505 case LDAP_FILTER_APPROX:
1507 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1508 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1511 case LDAP_FILTER_SUBSTRINGS:
1513 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1514 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1517 case LDAP_FILTER_PRESENT:
1519 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1520 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1523 case LDAP_FILTER_AND:
1524 case LDAP_FILTER_OR:
1525 case LDAP_FILTER_NOT: {
1527 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1528 f->f_choice == LDAP_FILTER_AND ? '&' :
1529 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1530 fstr->bv_len += sizeof("(%") - 1;
1532 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1533 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1537 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1538 fstr->bv_len += sizeof(")") - 1;
1544 strcpy( fstr->bv_val, "(?=?)" );
1545 fstr->bv_len += sizeof("(?=?)")-1;
1549 if ( filter_attrs != NULL ) {
1550 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1551 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1553 (*filter_attrs)[*filter_cnt].an_desc = ad;
1554 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1555 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1556 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1557 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1559 if ( ad == slap_schema.si_ad_objectClass )
1566 struct search_info {
1569 QueryTemplate *qtemp;
1570 AttributeName* save_attrs; /* original attributes, saved for response */
1575 int slimit_exceeded;
1576 pc_caching_reason_t caching_reason;
1581 remove_query_and_data(
1585 struct berval *uuid )
1587 query_manager* qm = cm->qm;
1589 qm->crfunc( qm, uuid );
1590 if ( !BER_BVISNULL( uuid ) ) {
1593 Debug( pcache_debug,
1594 "Removing query UUID %s\n",
1595 uuid->bv_val, 0, 0 );
1596 return_val = remove_query_data( op, rs, uuid );
1597 Debug( pcache_debug,
1598 "QUERY REMOVED, SIZE=%d\n",
1600 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1601 cm->cur_entries -= return_val;
1602 cm->num_cached_queries--;
1603 Debug( pcache_debug,
1604 "STORED QUERIES = %lu\n",
1605 cm->num_cached_queries, 0, 0 );
1606 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1607 Debug( pcache_debug,
1608 "QUERY REMOVED, CACHE ="
1610 cm->cur_entries, 0, 0 );
1615 * Callback used to fetch queryId values based on entryUUID;
1616 * used by pcache_remove_entries_from_cache()
1619 fetch_queryId_cb( Operation *op, SlapReply *rs )
1623 /* only care about searchEntry responses */
1624 if ( rs->sr_type != REP_SEARCH ) {
1628 /* allow only one response per entryUUID */
1629 if ( op->o_callback->sc_private != NULL ) {
1635 /* copy all queryId values into callback's private data */
1636 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1638 BerVarray vals = NULL;
1640 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1641 op->o_callback->sc_private = (void *)vals;
1645 /* clear entry if required */
1646 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1647 entry_free( rs->sr_entry );
1648 rs->sr_entry = NULL;
1649 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1656 * Call that allows to remove a set of entries from the cache,
1657 * by forcing the removal of all the related queries.
1660 pcache_remove_entries_from_cache(
1663 BerVarray entryUUIDs )
1665 Connection conn = { 0 };
1666 OperationBuffer opbuf;
1668 slap_callback sc = { 0 };
1669 SlapReply rs = { REP_RESULT };
1671 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1672 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1673 AttributeName attrs[ 2 ] = { 0 };
1677 void *thrctx = ldap_pvt_thread_pool_context();
1679 connection_fake_init( &conn, &opbuf, thrctx );
1687 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1688 op->ors_scope = LDAP_SCOPE_SUBTREE;
1689 op->ors_deref = LDAP_DEREF_NEVER;
1690 f.f_choice = LDAP_FILTER_EQUALITY;
1692 ava.aa_desc = slap_schema.si_ad_entryUUID;
1693 op->ors_filter = &f;
1695 op->ors_tlimit = SLAP_NO_LIMIT;
1696 attrs[ 0 ].an_desc = ad_queryId;
1697 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1698 op->ors_attrs = attrs;
1699 op->ors_attrsonly = 0;
1701 op->o_req_dn = cm->db.be_suffix[ 0 ];
1702 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1704 op->o_tag = LDAP_REQ_SEARCH;
1705 op->o_protocol = LDAP_VERSION3;
1706 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1708 op->o_dn = op->o_bd->be_rootdn;
1709 op->o_ndn = op->o_bd->be_rootndn;
1710 sc.sc_response = fetch_queryId_cb;
1711 op->o_callback = ≻
1713 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1714 BerVarray vals = NULL;
1716 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1717 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1718 op->ors_filterstr.bv_val = filtbuf;
1719 ava.aa_value = entryUUIDs[ s ];
1721 rc = op->o_bd->be_search( op, &rs );
1722 if ( rc != LDAP_SUCCESS ) {
1726 vals = (BerVarray)op->o_callback->sc_private;
1727 if ( vals != NULL ) {
1730 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1731 struct berval val = vals[ i ];
1733 remove_query_and_data( op, &rs, cm, &val );
1735 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1736 ch_free( val.bv_val );
1740 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1741 op->o_callback->sc_private = NULL;
1749 * Call that allows to remove a query from the cache.
1752 pcache_remove_query_from_cache(
1755 struct berval *queryid )
1757 Operation op2 = *op;
1758 SlapReply rs2 = { 0 };
1762 /* remove the selected query */
1763 remove_query_and_data( &op2, &rs2, cm, queryid );
1765 return LDAP_SUCCESS;
1769 * Call that allows to remove a set of queries related to an entry
1770 * from the cache; if queryid is not null, the entry must belong to
1771 * the query indicated by queryid.
1774 pcache_remove_entry_queries_from_cache(
1778 struct berval *queryid )
1780 Connection conn = { 0 };
1781 OperationBuffer opbuf;
1783 slap_callback sc = { 0 };
1784 SlapReply rs = { REP_RESULT };
1786 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1787 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1788 AttributeName attrs[ 2 ] = { 0 };
1791 BerVarray vals = NULL;
1794 void *thrctx = ldap_pvt_thread_pool_context();
1796 connection_fake_init( &conn, &opbuf, thrctx );
1804 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1805 op->ors_scope = LDAP_SCOPE_BASE;
1806 op->ors_deref = LDAP_DEREF_NEVER;
1807 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1808 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1809 f.f_choice = LDAP_FILTER_PRESENT;
1810 f.f_desc = slap_schema.si_ad_objectClass;
1813 op->ors_filterstr.bv_len = snprintf( filter_str,
1814 sizeof( filter_str ), "(%s=%s)",
1815 ad_queryId->ad_cname.bv_val, queryid->bv_val );
1816 f.f_choice = LDAP_FILTER_EQUALITY;
1818 f.f_av_desc = ad_queryId;
1819 f.f_av_value = *queryid;
1821 op->ors_filter = &f;
1823 op->ors_tlimit = SLAP_NO_LIMIT;
1824 attrs[ 0 ].an_desc = ad_queryId;
1825 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1826 op->ors_attrs = attrs;
1827 op->ors_attrsonly = 0;
1829 op->o_req_dn = *ndn;
1830 op->o_req_ndn = *ndn;
1832 op->o_tag = LDAP_REQ_SEARCH;
1833 op->o_protocol = LDAP_VERSION3;
1834 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1836 op->o_dn = op->o_bd->be_rootdn;
1837 op->o_ndn = op->o_bd->be_rootndn;
1838 sc.sc_response = fetch_queryId_cb;
1839 op->o_callback = ≻
1841 rc = op->o_bd->be_search( op, &rs );
1842 if ( rc != LDAP_SUCCESS ) {
1846 vals = (BerVarray)op->o_callback->sc_private;
1847 if ( vals != NULL ) {
1850 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1851 struct berval val = vals[ i ];
1853 remove_query_and_data( op, &rs, cm, &val );
1855 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1856 ch_free( val.bv_val );
1860 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1863 return LDAP_SUCCESS;
1870 struct berval *query_uuid )
1872 struct search_info *si = op->o_callback->sc_private;
1873 slap_overinst *on = si->on;
1874 cache_manager *cm = on->on_bi.bi_private;
1877 struct berval crp_uuid;
1878 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1879 Operation op_tmp = *op;
1881 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1882 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1884 op_tmp.o_bd = &cm->db;
1885 op_tmp.o_dn = cm->db.be_rootdn;
1886 op_tmp.o_ndn = cm->db.be_rootndn;
1888 Debug( pcache_debug, "UUID for query being added = %s\n",
1891 for ( e=si->head; e; e=si->head ) {
1892 si->head = e->e_private;
1893 e->e_private = NULL;
1894 while ( cm->cur_entries > (cm->max_entries) ) {
1895 BER_BVZERO( &crp_uuid );
1896 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1899 return_val = merge_entry(&op_tmp, e, query_uuid);
1900 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1901 cm->cur_entries += return_val;
1902 Debug( pcache_debug,
1903 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1904 cm->cur_entries, 0, 0 );
1906 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1913 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1914 slap_callback *cb = op->o_callback;
1915 struct search_info *si = cb->sc_private;
1916 slap_overinst *on = si->on;
1917 cache_manager *cm = on->on_bi.bi_private;
1918 query_manager* qm = cm->qm;
1920 if ( rs->sr_type == REP_SEARCH ) {
1923 /* don't return more entries than requested by the client */
1924 if ( si->slimit && rs->sr_nentries >= si->slimit ) {
1925 si->slimit_exceeded = 1;
1928 /* If we haven't exceeded the limit for this query,
1929 * build a chain of answers to store. If we hit the
1930 * limit, empty the chain and ignore the rest.
1933 if ( si->count < si->max ) {
1935 e = entry_dup( rs->sr_entry );
1936 if ( !si->head ) si->head = e;
1937 if ( si->tail ) si->tail->e_private = e;
1943 for (;si->head; si->head=e) {
1944 e = si->head->e_private;
1945 si->head->e_private = NULL;
1946 entry_free(si->head);
1954 if ( rs->sr_type == REP_RESULT ||
1955 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
1957 if ( si->save_attrs != NULL ) {
1958 rs->sr_attrs = si->save_attrs;
1959 op->ors_attrs = si->save_attrs;
1961 if ( op->o_abandon || rs->sr_err == SLAPD_ABANDON ) {
1962 filter_free( si->query.filter );
1964 /* duplicate query, free it */
1966 for (;si->head; si->head=e) {
1967 e = si->head->e_private;
1968 si->head->e_private = NULL;
1969 entry_free(si->head);
1972 op->o_callback = op->o_callback->sc_next;
1973 op->o_tmpfree( cb, op->o_tmpmemctx );
1974 } else if ( si->caching_reason != PC_IGNORE ) {
1975 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
1976 si->qtemp, si->caching_reason, 1 );
1979 switch ( si->caching_reason ) {
1981 cache_entries( op, rs, &qc->q_uuid );
1985 qc->q_sizelimit = rs->sr_nentries;
1988 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
1989 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1990 cm->num_cached_queries++;
1991 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1992 cm->num_cached_queries, 0, 0 );
1993 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1995 /* If the consistency checker suspended itself,
1998 if ( cm->cc_paused ) {
1999 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2000 if ( cm->cc_paused ) {
2002 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2004 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2007 } else if ( si->count ) {
2008 /* duplicate query, free it */
2010 for (;si->head; si->head=e) {
2011 e = si->head->e_private;
2012 si->head->e_private = NULL;
2013 entry_free(si->head);
2018 filter_free( si->query.filter );
2022 return SLAP_CB_CONTINUE;
2030 struct search_info *si = op->o_callback->sc_private;
2032 if ( si->save_attrs != NULL ) {
2033 rs->sr_attrs = si->save_attrs;
2034 op->ors_attrs = si->save_attrs;
2037 if ( rs->sr_type == REP_SEARCH ) {
2038 /* don't return more entries than requested by the client */
2039 if ( si->slimit_exceeded ) {
2043 } else if ( rs->sr_type == REP_RESULT ) {
2046 if ( rs->sr_err == LDAP_SUCCESS ) {
2047 si->caching_reason = PC_POSITIVE;
2049 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2050 && si->qtemp->limitttl )
2052 si->caching_reason = PC_SIZELIMIT;
2055 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2056 rs->sr_err == LDAP_SUCCESS )
2058 si->caching_reason = PC_NEGATIVE;
2062 if ( si->slimit_exceeded ) {
2063 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2067 return SLAP_CB_CONTINUE;
2073 AttributeName** new_attrs,
2074 struct attr_set *attrs,
2075 AttributeName* filter_attrs,
2085 /* duplicate attrs */
2086 count = attrs->count + fattr_cnt;
2087 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2092 *new_attrs = (AttributeName*)ch_calloc( count + 1,
2093 sizeof(AttributeName) );
2094 for (i=0; i<attrs->count; i++) {
2095 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2096 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2098 BER_BVZERO( &(*new_attrs)[i].an_name );
2099 alluser = an_find(*new_attrs, &AllUser);
2100 allop = an_find(*new_attrs, &AllOper);
2103 for ( i=0; i<fattr_cnt; i++ ) {
2104 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2107 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2111 } else if ( alluser ) {
2114 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2115 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2116 (*new_attrs)[j].an_oc = NULL;
2117 (*new_attrs)[j].an_oc_exclude = 0;
2121 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2122 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2123 (*new_attrs)[j].an_oc = NULL;
2124 (*new_attrs)[j].an_oc_exclude = 0;
2127 BER_BVZERO( &(*new_attrs)[j].an_name );
2132 /* NOTE: this is a quick workaround to let pcache minimally interact
2133 * with pagedResults. A more articulated solutions would be to
2134 * perform the remote query without control and cache all results,
2135 * performing the pagedResults search only within the client
2136 * and the proxy. This requires pcache to understand pagedResults. */
2138 pcache_chk_controls(
2142 const char *non = "";
2143 const char *stripped = "";
2145 switch( op->o_pagedresults ) {
2146 case SLAP_CONTROL_NONCRITICAL:
2148 stripped = "; stripped";
2151 case SLAP_CONTROL_CRITICAL:
2152 Debug( pcache_debug, "%s: "
2153 "%scritical pagedResults control "
2154 "disabled with proxy cache%s.\n",
2155 op->o_log_prefix, non, stripped );
2157 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2161 rs->sr_err = SLAP_CB_CONTINUE;
2168 #ifdef PCACHE_CONTROL_PRIVDB
2174 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2175 cache_manager *cm = on->on_bi.bi_private;
2176 slap_callback *save_cb;
2179 /* skip if control is unset */
2180 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2181 return SLAP_CB_CONTINUE;
2184 /* FIXME: might be a little bit exaggerated... */
2185 if ( !be_isroot( op ) ) {
2186 save_cb = op->o_callback;
2187 op->o_callback = NULL;
2188 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2189 "pcachePrivDB: operation not allowed" );
2190 op->o_callback = save_cb;
2195 /* map tag to operation */
2196 type = slap_req2op( op->o_tag );
2197 if ( type != SLAP_OP_LAST ) {
2201 /* execute, if possible */
2202 func = &cm->db.be_bind;
2203 if ( func[ type ] != NULL ) {
2204 Operation op2 = *op;
2208 rc = func[ type ]( &op2, rs );
2209 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2210 op->o_conn->c_authz_cookie = cm->db.be_private;
2215 /* otherwise fall back to error */
2216 save_cb = op->o_callback;
2217 op->o_callback = NULL;
2218 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2219 "operation not supported with pcachePrivDB control" );
2220 op->o_callback = save_cb;
2224 #endif /* PCACHE_CONTROL_PRIVDB */
2231 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2232 cache_manager *cm = on->on_bi.bi_private;
2233 query_manager* qm = cm->qm;
2237 AttributeName *filter_attrs = NULL;
2240 QueryTemplate *qtemp = NULL;
2243 CachedQuery *answerable = NULL;
2246 int fattr_got_oc = 0;
2248 struct berval tempstr;
2250 #ifdef PCACHE_CONTROL_PRIVDB
2251 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2252 return pcache_op_privdb( op, rs );
2254 #endif /* PCACHE_CONTROL_PRIVDB */
2256 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2258 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2259 &fattr_cnt, &fattr_got_oc )) {
2260 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2261 return SLAP_CB_CONTINUE;
2264 Debug( pcache_debug, "query template of incoming query = %s\n",
2265 tempstr.bv_val, 0, 0 );
2267 /* FIXME: cannot cache/answer requests with pagedResults control */
2270 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2272 query.filter = op->ors_filter;
2273 query.base = op->o_req_ndn;
2274 query.scope = op->ors_scope;
2276 /* check for query containment */
2277 if (attr_set > -1) {
2278 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2279 for (; qt; qt = qt->qtnext ) {
2280 /* find if template i can potentially answer tempstr */
2281 if (qt->querystr.bv_len != tempstr.bv_len ||
2282 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2286 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2287 op->ors_filterstr.bv_val, 0, 0 );
2288 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2294 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2297 /* Need to clear the callbacks of the original operation,
2298 * in case there are other overlays */
2299 BackendDB *save_bd = op->o_bd;
2300 slap_callback *save_cb = op->o_callback;
2302 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2303 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2304 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
2305 if ( BER_BVISNULL( &answerable->q_uuid )) {
2306 /* No entries cached, just an empty result set */
2308 send_ldap_result( op, rs );
2311 op->o_callback = NULL;
2312 i = cm->db.bd_info->bi_op_search( op, rs );
2314 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
2315 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2317 op->o_callback = save_cb;
2321 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2323 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2324 if (cm->num_cached_queries >= cm->max_queries) {
2327 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2329 if (op->ors_attrsonly)
2334 struct search_info *si;
2336 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2337 query.filter = filter_dup(op->ors_filter, NULL);
2338 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2339 if ( !qtemp->t_attrs.count ) {
2340 qtemp->t_attrs.count = add_filter_attrs(op,
2341 &qtemp->t_attrs.attrs,
2342 &qm->attr_sets[attr_set],
2343 filter_attrs, fattr_cnt, fattr_got_oc);
2345 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2347 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2348 cb->sc_response = pcache_response;
2349 cb->sc_cleanup = pcache_op_cleanup;
2350 cb->sc_private = (cb+1);
2351 si = cb->sc_private;
2355 si->max = cm->num_entries_limit ;
2359 si->slimit_exceeded = 0;
2360 si->caching_reason = PC_IGNORE;
2361 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2362 si->slimit = op->ors_slimit;
2363 op->ors_slimit = cm->num_entries_limit;
2367 si->save_attrs = op->ors_attrs;
2369 op->ors_attrs = qtemp->t_attrs.attrs;
2371 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2372 cb->sc_next = op->o_callback;
2373 op->o_callback = cb;
2376 slap_callback **pcb;
2378 /* need to move the callback at the end, in case other
2379 * overlays are present, so that the final entry is
2380 * actually cached */
2382 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2387 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2391 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2393 return SLAP_CB_CONTINUE;
2398 AttributeName* attrs,
2406 for ( ; attrs[count].an_name.bv_val; count++ );
2409 /* recognize a single "*" or a "1.1" */
2412 attrs = slap_anlist_all_user_attributes;
2414 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2419 for ( i = 0; i < num; i++ ) {
2423 if ( count > qm->attr_sets[i].count ) {
2428 if ( !qm->attr_sets[i].count ) {
2434 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2435 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2458 struct re_s *rtask = arg;
2459 slap_overinst *on = rtask->arg;
2460 cache_manager *cm = on->on_bi.bi_private;
2461 query_manager *qm = cm->qm;
2462 Connection conn = {0};
2463 OperationBuffer opbuf;
2466 SlapReply rs = {REP_RESULT};
2468 int return_val, pause = 1;
2469 QueryTemplate* templ;
2471 connection_fake_init( &conn, &opbuf, ctx );
2475 op->o_dn = cm->db.be_rootdn;
2476 op->o_ndn = cm->db.be_rootndn;
2480 for (templ = qm->templates; templ; templ=templ->qmnext) {
2481 query = templ->query_last;
2482 if ( query ) pause = 0;
2483 op->o_time = slap_get_time();
2484 while (query && (query->expiry_time < op->o_time)) {
2486 Debug( pcache_debug, "Lock CR index = %p\n",
2487 (void *) templ, 0, 0 );
2488 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2489 if ( query == templ->query_last ) {
2491 remove_from_template(query, templ);
2492 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2493 (void *) templ, templ->no_of_queries, 0 );
2494 Debug( pcache_debug, "Unlock CR index = %p\n",
2495 (void *) templ, 0, 0 );
2497 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2499 query = templ->query_last;
2502 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2503 remove_query(qm, query);
2504 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2505 if ( BER_BVISNULL( &query->q_uuid ))
2508 return_val = remove_query_data(op, &rs, &query->q_uuid);
2509 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2511 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2512 cm->cur_entries -= return_val;
2513 cm->num_cached_queries--;
2514 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2515 cm->num_cached_queries, 0, 0 );
2516 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2517 Debug( pcache_debug,
2518 "STALE QUERY REMOVED, CACHE ="
2520 cm->cur_entries, 0, 0 );
2522 query = templ->query_last;
2525 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2526 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2527 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2529 /* If there were no queries, defer processing for a while */
2530 cm->cc_paused = pause;
2531 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2533 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2538 #define MAX_ATTR_SETS 500
2548 static ConfigDriver pc_cf_gen;
2549 static ConfigLDAPadd pc_ldadd;
2550 static ConfigCfAdd pc_cfadd;
2552 static ConfigTable pccfg[] = {
2553 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2555 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2556 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2557 "DESC 'ProxyCache basic parameters' "
2558 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2559 { "proxyattrset", "index> <attributes...",
2560 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2561 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2562 "DESC 'A set of attributes to cache' "
2563 "SYNTAX OMsDirectoryString )", NULL, NULL },
2564 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2565 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2566 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2567 "DESC 'Filter template, attrset, cache TTL, "
2568 "optional negative TTL, optional sizelimit TTL' "
2569 "SYNTAX OMsDirectoryString )", NULL, NULL },
2570 { "response-callback", "head|tail(default)",
2571 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2572 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2573 "DESC 'Response callback position in overlay stack' "
2574 "SYNTAX OMsDirectoryString )", NULL, NULL },
2575 { "proxyCacheQueries", "queries",
2576 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2577 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2578 "DESC 'Maximum number of queries to cache' "
2579 "SYNTAX OMsInteger )", NULL, NULL },
2580 { "proxySaveQueries", "TRUE|FALSE",
2581 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2582 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2583 "DESC 'Save cached queries for hot restart' "
2584 "SYNTAX OMsBoolean )", NULL, NULL },
2586 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2589 static ConfigOCs pcocs[] = {
2590 { "( OLcfgOvOc:2.1 "
2591 "NAME 'olcPcacheConfig' "
2592 "DESC 'ProxyCache configuration' "
2593 "SUP olcOverlayConfig "
2594 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2595 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2596 Cft_Overlay, pccfg, NULL, pc_cfadd },
2597 { "( OLcfgOvOc:2.2 "
2598 "NAME 'olcPcacheDatabase' "
2599 "DESC 'Cache database configuration' "
2600 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2605 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2610 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2611 p->ce_bi->bi_cf_ocs != pcocs )
2612 return LDAP_CONSTRAINT_VIOLATION;
2614 on = (slap_overinst *)p->ce_bi;
2615 cm = on->on_bi.bi_private;
2617 return LDAP_SUCCESS;
2621 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2623 CfEntryInfo *pe = p->e_private;
2624 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2625 cache_manager *cm = on->on_bi.bi_private;
2628 /* FIXME: should not hardcode "olcDatabase" here */
2629 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2630 bv.bv_val = ca->cr_msg;
2633 /* We can only create this entry if the database is table-driven
2635 if ( cm->db.bd_info->bi_cf_ocs )
2636 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2643 pc_cf_gen( ConfigArgs *c )
2645 slap_overinst *on = (slap_overinst *)c->bi;
2646 cache_manager* cm = on->on_bi.bi_private;
2647 query_manager* qm = cm->qm;
2648 QueryTemplate* temp;
2649 AttributeName* attr_name;
2650 AttributeName* attrarray;
2651 const char* text=NULL;
2656 if ( c->op == SLAP_CONFIG_EMIT ) {
2660 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2661 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2662 cm->num_entries_limit, cm->cc_period );
2663 bv.bv_val = c->cr_msg;
2664 value_add_one( &c->rvalue_vals, &bv );
2667 for (i=0; i<cm->numattrsets; i++) {
2668 if ( !qm->attr_sets[i].count ) continue;
2670 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2672 /* count the attr length */
2673 for ( attr_name = qm->attr_sets[i].attrs;
2674 attr_name->an_name.bv_val; attr_name++ )
2675 bv.bv_len += attr_name->an_name.bv_len + 1;
2677 bv.bv_val = ch_malloc( bv.bv_len+1 );
2678 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2679 for ( attr_name = qm->attr_sets[i].attrs;
2680 attr_name->an_name.bv_val; attr_name++ ) {
2682 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2684 ber_bvarray_add( &c->rvalue_vals, &bv );
2686 if ( !c->rvalue_vals )
2690 for (temp=qm->templates; temp; temp=temp->qmnext) {
2691 /* HEADS-UP: always print all;
2692 * if optional == 0, ignore */
2693 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2695 temp->attr_set_index,
2699 bv.bv_len += temp->querystr.bv_len + 2;
2700 bv.bv_val = ch_malloc( bv.bv_len+1 );
2703 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2705 strcpy( ptr, c->cr_msg );
2706 ber_bvarray_add( &c->rvalue_vals, &bv );
2708 if ( !c->rvalue_vals )
2712 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2713 BER_BVSTR( &bv, "head" );
2715 BER_BVSTR( &bv, "tail" );
2717 value_add_one( &c->rvalue_vals, &bv );
2720 c->value_int = cm->max_queries;
2724 } else if ( c->op == LDAP_MOD_DELETE ) {
2725 return 1; /* FIXME */
2737 if ( cm->numattrsets > 0 ) {
2738 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2739 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2743 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2744 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2746 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2749 if ( cm->numattrsets <= 0 ) {
2750 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2751 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2754 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2755 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2756 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2760 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2761 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2762 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2766 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2767 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2769 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2772 if ( cm->max_entries <= 0 ) {
2773 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2774 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2778 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2779 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2781 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2784 if ( cm->num_entries_limit <= 0 ) {
2785 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2786 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2789 if ( cm->num_entries_limit > cm->max_entries ) {
2790 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2791 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2795 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2796 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2798 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2801 cm->cc_period = (time_t)t;
2802 Debug( pcache_debug,
2803 "Total # of attribute sets to be cached = %d.\n",
2804 cm->numattrsets, 0, 0 );
2805 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2806 sizeof( struct attr_set ) );
2809 if ( cm->numattrsets == 0 ) {
2810 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2811 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2814 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2815 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2817 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2821 if ( num < 0 || num >= cm->numattrsets ) {
2822 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2823 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2824 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2827 qm->attr_sets[num].flags |= PC_CONFIGURED;
2828 if ( c->argc == 2 ) {
2830 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2831 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2832 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2835 } else if ( c->argc == 3 ) {
2836 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2837 qm->attr_sets[num].count = 1;
2838 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2839 sizeof( AttributeName ) );
2840 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2843 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2844 qm->attr_sets[num].count = 1;
2845 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2846 sizeof( AttributeName ) );
2847 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2850 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2853 /* else: fallthru */
2855 } else if ( c->argc == 4 ) {
2856 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2857 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2859 qm->attr_sets[num].count = 2;
2860 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2861 sizeof( AttributeName ) );
2862 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2863 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2866 /* else: fallthru */
2869 if ( c->argc > 2 ) {
2870 int all_user = 0, all_op = 0;
2872 qm->attr_sets[num].count = c->argc - 2;
2873 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2874 sizeof( AttributeName ) );
2875 attr_name = qm->attr_sets[num].attrs;
2876 for ( i = 2; i < c->argc; i++ ) {
2877 attr_name->an_desc = NULL;
2878 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2879 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2880 "invalid attr #%d \"%s\" in attrlist",
2881 i - 2, c->argv[i] );
2882 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2883 ch_free( qm->attr_sets[num].attrs );
2884 qm->attr_sets[num].attrs = NULL;
2885 qm->attr_sets[num].count = 0;
2888 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2890 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2891 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2893 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2895 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2896 strcpy( c->cr_msg, text );
2897 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2898 ch_free( qm->attr_sets[num].attrs );
2899 qm->attr_sets[num].attrs = NULL;
2900 qm->attr_sets[num].count = 0;
2903 attr_name->an_name = attr_name->an_desc->ad_cname;
2905 attr_name->an_oc = NULL;
2906 attr_name->an_oc_exclude = 0;
2907 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2908 qm->attr_sets[num].flags |= PC_GOT_OC;
2910 BER_BVZERO( &attr_name->an_name );
2913 /* warn if list contains both "*" and "+" */
2914 if ( i > 4 && all_user && all_op ) {
2915 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2916 "warning: attribute list contains \"*\" and \"+\"" );
2917 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2922 if ( cm->numattrsets == 0 ) {
2923 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2924 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2927 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2928 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2930 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2934 if ( i < 0 || i >= cm->numattrsets ||
2935 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2936 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2937 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2938 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2941 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2942 temp->qmnext = qm->templates;
2943 qm->templates = temp;
2944 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2945 temp->query = temp->query_last = NULL;
2946 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2947 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2948 "unable to parse template ttl=\"%s\"",
2950 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2953 temp->ttl = (time_t)t;
2954 temp->negttl = (time_t)0;
2955 temp->limitttl = (time_t)0;
2956 switch ( c->argc ) {
2958 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2959 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2960 "unable to parse template sizelimit ttl=\"%s\"",
2962 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2965 temp->limitttl = (time_t)t;
2969 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2970 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2971 "unable to parse template negative ttl=\"%s\"",
2973 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2976 temp->negttl = (time_t)t;
2980 temp->no_of_queries = 0;
2982 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2983 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2984 Debug( pcache_debug, " query template: %s\n",
2985 temp->querystr.bv_val, 0, 0 );
2986 temp->attr_set_index = i;
2987 qm->attr_sets[i].flags |= PC_REFERENCED;
2988 temp->qtnext = qm->attr_sets[i].templates;
2989 qm->attr_sets[i].templates = temp;
2990 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2991 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2992 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2993 Debug( pcache_debug, "\t%s\n",
2994 attrarray[i].an_name.bv_val, 0, 0 );
2998 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2999 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3001 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3002 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3005 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3006 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3011 if ( c->value_int <= 0 ) {
3012 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3013 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3016 cm->max_queries = c->value_int;
3031 slap_overinst *on = (slap_overinst *)be->bd_info;
3032 cache_manager* cm = on->on_bi.bi_private;
3034 /* Something for the cache database? */
3035 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3036 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3038 return SLAP_CONF_UNKNOWN;
3046 slap_overinst *on = (slap_overinst *)be->bd_info;
3050 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3051 on->on_bi.bi_private = cm;
3053 qm = (query_manager*)ch_malloc(sizeof(query_manager));
3056 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3057 cm->db.be_private = NULL;
3058 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
3060 cm->numattrsets = 0;
3061 cm->num_entries_limit = 5;
3062 cm->num_cached_queries = 0;
3063 cm->max_entries = 0;
3064 cm->cur_entries = 0;
3065 cm->max_queries = 10000;
3066 cm->save_queries = 0;
3067 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3068 cm->cc_period = 1000;
3071 qm->attr_sets = NULL;
3072 qm->templates = NULL;
3074 qm->lru_bottom = NULL;
3076 qm->qcfunc = query_containment;
3077 qm->crfunc = cache_replacement;
3078 qm->addfunc = add_query;
3079 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3081 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3086 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3088 assert( op->o_tag == LDAP_REQ_SEARCH );
3090 if ( rs->sr_type == REP_SEARCH ) {
3093 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3097 assert( a->a_nvals != NULL );
3099 valsp = op->o_callback->sc_private;
3100 assert( *valsp == NULL );
3102 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3110 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3112 assert( op->o_tag == LDAP_REQ_SEARCH );
3114 if ( rs->sr_type == REP_SEARCH ) {
3115 int *countp = (int *)op->o_callback->sc_private;
3128 slap_overinst *on = (slap_overinst *)be->bd_info;
3129 cache_manager *cm = on->on_bi.bi_private;
3130 query_manager* qm = cm->qm;
3131 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3133 /* check attr sets */
3134 for ( i = 0; i < cm->numattrsets; i++) {
3135 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3136 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3137 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3141 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3145 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3146 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3151 if ( ncf || rf || nrf ) {
3152 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3153 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3154 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3161 /* need to inherit something from the original database... */
3162 cm->db.be_def_limit = be->be_def_limit;
3163 cm->db.be_limits = be->be_limits;
3164 cm->db.be_acl = be->be_acl;
3165 cm->db.be_dfltaccess = be->be_dfltaccess;
3167 if ( SLAP_DBMONITORING( be ) ) {
3168 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3171 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3174 rc = backend_startup_one( &cm->db, NULL );
3176 /* There is no runqueue in TOOL mode */
3177 if ( slapMode & SLAP_SERVER_MODE ) {
3178 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3179 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3180 consistency_check, on,
3181 "pcache_consistency", be->be_suffix[0].bv_val );
3182 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3184 /* Cached database must have the rootdn */
3185 if ( BER_BVISNULL( &cm->db.be_rootndn )
3186 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3188 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3189 "underlying database of type \"%s\"\n"
3190 " serving naming context \"%s\"\n"
3191 " has no \"rootdn\", required by \"proxycache\".\n",
3192 on->on_info->oi_orig->bi_type,
3193 cm->db.be_suffix[0].bv_val, 0 );
3197 if ( cm->save_queries ) {
3198 void *thrctx = ldap_pvt_thread_pool_context();
3199 Connection conn = { 0 };
3200 OperationBuffer opbuf;
3202 slap_callback cb = { 0 };
3203 SlapReply rs = { 0 };
3204 BerVarray vals = NULL;
3205 Filter f = { 0 }, f2 = { 0 };
3206 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3207 AttributeName attrs[ 2 ] = { 0 };
3209 connection_fake_init( &conn, &opbuf, thrctx );
3214 op->o_tag = LDAP_REQ_SEARCH;
3215 op->o_protocol = LDAP_VERSION3;
3216 cb.sc_response = pcache_cachedquery_open_cb;
3217 cb.sc_private = &vals;
3218 op->o_callback = &cb;
3219 op->o_time = slap_get_time();
3220 op->o_do_not_cache = 1;
3221 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3223 op->o_dn = cm->db.be_rootdn;
3224 op->o_ndn = cm->db.be_rootndn;
3225 op->o_req_dn = cm->db.be_suffix[ 0 ];
3226 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3228 op->ors_scope = LDAP_SCOPE_BASE;
3229 op->ors_deref = LDAP_DEREF_NEVER;
3231 op->ors_tlimit = SLAP_NO_LIMIT;
3232 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3233 f.f_choice = LDAP_FILTER_PRESENT;
3234 f.f_desc = ad_cachedQueryURL;
3235 op->ors_filter = &f;
3236 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3237 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3238 op->ors_attrs = attrs;
3239 op->ors_attrsonly = 0;
3241 rc = op->o_bd->be_search( op, &rs );
3242 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3245 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3246 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3247 cm->num_cached_queries++;
3251 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3254 /* count cached entries */
3255 f.f_choice = LDAP_FILTER_NOT;
3257 f2.f_choice = LDAP_FILTER_EQUALITY;
3259 f2.f_av_desc = slap_schema.si_ad_objectClass;
3260 BER_BVSTR( &f2.f_av_value, "glue" );
3261 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3263 op->ors_slimit = SLAP_NO_LIMIT;
3264 op->ors_scope = LDAP_SCOPE_SUBTREE;
3265 op->ors_attrs = slap_anlist_no_attrs;
3267 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3269 op->o_callback->sc_private = &rs.sr_nentries;
3271 rc = op->o_bd->be_search( op, &rs );
3273 cm->cur_entries = rs.sr_nentries;
3284 pcache_free_qbase( void *v )
3290 tavl_free( qb->scopes[i], NULL );
3300 slap_overinst *on = (slap_overinst *)be->bd_info;
3301 cache_manager *cm = on->on_bi.bi_private;
3302 query_manager *qm = cm->qm;
3306 if ( cm->save_queries ) {
3308 BerVarray vals = NULL;
3311 Connection conn = { 0 };
3312 OperationBuffer opbuf;
3314 slap_callback cb = { 0 };
3316 SlapReply rs = { REP_RESULT };
3317 Modifications mod = { 0 };
3319 thrctx = ldap_pvt_thread_pool_context();
3321 connection_fake_init( &conn, &opbuf, thrctx );
3324 if ( qm->templates != NULL ) {
3325 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3326 for ( qc = tm->query; qc; qc = qc->next ) {
3329 if ( query2url( op, qc, &bv ) == 0 ) {
3330 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3337 op->o_dn = cm->db.be_rootdn;
3338 op->o_ndn = cm->db.be_rootndn;
3340 op->o_tag = LDAP_REQ_MODIFY;
3341 op->o_protocol = LDAP_VERSION3;
3342 cb.sc_response = slap_null_cb;
3343 op->o_callback = &cb;
3344 op->o_time = slap_get_time();
3345 op->o_do_not_cache = 1;
3346 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3348 op->o_req_dn = op->o_bd->be_suffix[0];
3349 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3351 mod.sml_op = LDAP_MOD_REPLACE;
3353 mod.sml_desc = ad_cachedQueryURL;
3354 mod.sml_type = ad_cachedQueryURL->ad_cname;
3355 mod.sml_values = vals;
3356 mod.sml_nvalues = NULL;
3357 mod.sml_next = NULL;
3358 Debug( pcache_debug,
3359 "%sSETTING CACHED QUERY URLS\n",
3360 vals == NULL ? "RE" : "", 0, 0 );
3362 op->orm_modlist = &mod;
3364 op->o_bd->be_modify( op, &rs );
3366 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3369 /* cleanup stuff inherited from the original database... */
3370 cm->db.be_limits = NULL;
3371 cm->db.be_acl = NULL;
3373 /* stop the thread ... */
3375 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3376 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3377 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3379 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3380 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3383 if ( cm->db.bd_info->bi_db_close ) {
3384 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3386 while ( (tm = qm->templates) != NULL ) {
3387 CachedQuery *qc, *qn;
3388 qm->templates = tm->qmnext;
3389 for ( qc = tm->query; qc; qc = qn ) {
3393 avl_free( tm->qbase, pcache_free_qbase );
3394 free( tm->querystr.bv_val );
3395 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3396 free( tm->t_attrs.attrs );
3400 for ( i=0; i<cm->numattrsets; i++ ) {
3401 free( qm->attr_sets[i].attrs );
3403 free( qm->attr_sets );
3404 qm->attr_sets = NULL;
3415 slap_overinst *on = (slap_overinst *)be->bd_info;
3416 cache_manager *cm = on->on_bi.bi_private;
3417 query_manager *qm = cm->qm;
3419 if ( cm->db.be_private != NULL ) {
3420 backend_stopdown_one( &cm->db );
3423 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3424 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3431 #ifdef PCACHE_CONTROL_PRIVDB
3433 Control ::= SEQUENCE {
3434 controlType LDAPOID,
3435 criticality BOOLEAN DEFAULT FALSE,
3436 controlValue OCTET STRING OPTIONAL }
3438 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3440 * criticality must be TRUE; controlValue must be absent.
3448 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3449 rs->sr_text = "privateDB control specified multiple times";
3450 return LDAP_PROTOCOL_ERROR;
3453 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3454 rs->sr_text = "privateDB control value not absent";
3455 return LDAP_PROTOCOL_ERROR;
3458 if ( !ctrl->ldctl_iscritical ) {
3459 rs->sr_text = "privateDB control criticality required";
3460 return LDAP_PROTOCOL_ERROR;
3463 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3465 return LDAP_SUCCESS;
3468 static char *extops[] = {
3469 LDAP_EXOP_MODIFY_PASSWD,
3472 #endif /* PCACHE_CONTROL_PRIVDB */
3474 #ifdef PCACHE_EXOP_QUERY_DELETE
3475 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3477 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3478 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3479 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3482 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3483 requestName [0] LDAPOID,
3484 requestValue [1] OCTET STRING OPTIONAL }
3486 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3488 requestValue ::= SEQUENCE { CHOICE {
3490 entryDN [1] LDAPDN },
3491 queryID [2] OCTET STRING (SIZE(16))
3492 -- constrained to UUID }
3494 * Either baseDN or entryDN must be present, to allow database selection.
3496 * 1. if baseDN and queryID are present, then the query corresponding
3497 * to queryID is deleted;
3498 * 2. if baseDN is present and queryID is absent, then all queries
3500 * 3. if entryDN is present and queryID is absent, then all queries
3501 * corresponding to the queryID values present in entryDN are deleted;
3502 * 4. if entryDN and queryID are present, then all queries
3503 * corresponding to the queryID values present in entryDN are deleted,
3504 * but only if the value of queryID is contained in the entry;
3506 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3507 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3508 * or by removing the database files.
3510 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3511 COMPONENTS OF LDAPResult,
3512 responseName [10] LDAPOID OPTIONAL,
3513 responseValue [11] OCTET STRING OPTIONAL }
3515 * responseName and responseValue must be absent.
3519 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3520 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3521 * - if ndn != NULL, it is set to the normalized DN in the request
3522 * corresponding to either the baseDN or the entryDN, according
3523 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3524 * be freed by the caller.
3525 * - if uuid != NULL, it is set to point to the normalized UUID;
3526 * memory is malloc'ed on the Operation's slab, and must
3527 * be freed by the caller.
3530 pcache_parse_query_delete(
3534 struct berval *uuid,
3538 int rc = LDAP_SUCCESS;
3541 BerElementBuffer berbuf;
3542 BerElement *ber = (BerElement *)&berbuf;
3543 struct berval reqdata = BER_BVNULL;
3555 if ( in == NULL || in->bv_len == 0 ) {
3556 *text = "empty request data field in queryDelete exop";
3557 return LDAP_PROTOCOL_ERROR;
3560 ber_dupbv_x( &reqdata, in, ctx );
3562 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3563 ber_init2( ber, &reqdata, 0 );
3565 tag = ber_scanf( ber, "{" /*}*/ );
3567 if ( tag == LBER_ERROR ) {
3568 Debug( LDAP_DEBUG_TRACE,
3569 "pcache_parse_query_delete: decoding error.\n",
3571 goto decoding_error;
3574 tag = ber_peek_tag( ber, &len );
3575 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3576 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3580 if ( ndn != NULL ) {
3583 tag = ber_scanf( ber, "m", &dn );
3584 if ( tag == LBER_ERROR ) {
3585 Debug( LDAP_DEBUG_TRACE,
3586 "pcache_parse_query_delete: DN parse failed.\n",
3588 goto decoding_error;
3591 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3592 if ( rc != LDAP_SUCCESS ) {
3593 *text = "invalid DN in queryDelete exop request data";
3598 tag = ber_scanf( ber, "x" /* "m" */ );
3599 if ( tag == LBER_DEFAULT ) {
3600 goto decoding_error;
3604 tag = ber_peek_tag( ber, &len );
3607 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3608 if ( uuid != NULL ) {
3610 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3612 tag = ber_scanf( ber, "m", &bv );
3613 if ( tag == LBER_ERROR ) {
3614 Debug( LDAP_DEBUG_TRACE,
3615 "pcache_parse_query_delete: UUID parse failed.\n",
3617 goto decoding_error;
3620 if ( bv.bv_len != 16 ) {
3621 Debug( LDAP_DEBUG_TRACE,
3622 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3623 (unsigned long)bv.bv_len, 0, 0 );
3624 goto decoding_error;
3627 rc = lutil_uuidstr_from_normalized(
3628 bv.bv_val, bv.bv_len,
3629 uuidbuf, sizeof( uuidbuf ) );
3631 goto decoding_error;
3633 ber_str2bv( uuidbuf, rc, 1, uuid );
3637 tag = ber_skip_tag( ber, &len );
3638 if ( tag == LBER_DEFAULT ) {
3639 goto decoding_error;
3643 Debug( LDAP_DEBUG_TRACE,
3644 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3645 (unsigned long)len, 0, 0 );
3646 goto decoding_error;
3650 tag = ber_peek_tag( ber, &len );
3653 if ( tag != LBER_DEFAULT || len != 0 ) {
3655 Debug( LDAP_DEBUG_TRACE,
3656 "pcache_parse_query_delete: decoding error\n",
3658 rc = LDAP_PROTOCOL_ERROR;
3659 *text = "queryDelete data decoding error";
3662 if ( ndn && !BER_BVISNULL( ndn ) ) {
3663 slap_sl_free( ndn->bv_val, ctx );
3667 if ( uuid && !BER_BVISNULL( uuid ) ) {
3668 slap_sl_free( uuid->bv_val, ctx );
3673 if ( !BER_BVISNULL( &reqdata ) ) {
3674 ber_memfree_x( reqdata.bv_val, ctx );
3681 pcache_exop_query_delete(
3685 BackendDB *bd = op->o_bd;
3687 struct berval uuid = BER_BVNULL,
3689 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3691 ber_tag_t tag = LBER_DEFAULT;
3693 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3697 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3698 &tag, &op->o_req_ndn, uuidp,
3699 &rs->sr_text, op->o_tmpmemctx );
3700 if ( rs->sr_err != LDAP_SUCCESS ) {
3704 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3705 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3706 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3708 if ( !BER_BVISNULL( &uuid ) ) {
3709 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3712 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3713 op->o_log_prefix, buf, 0 );
3715 op->o_req_dn = op->o_req_ndn;
3717 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3718 rs->sr_err = backend_check_restrictions( op, rs,
3719 (struct berval *)&pcache_exop_QUERY_DELETE );
3720 if ( rs->sr_err != LDAP_SUCCESS ) {
3724 if ( op->o_bd->be_extended == NULL ) {
3725 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3726 "backend does not support extended operations" );
3730 op->o_bd->be_extended( op, rs );
3733 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3734 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3735 BER_BVZERO( &op->o_req_ndn );
3736 BER_BVZERO( &op->o_req_dn );
3739 if ( !BER_BVISNULL( &uuid ) ) {
3740 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3749 pcache_op_extended( Operation *op, SlapReply *rs )
3751 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3752 cache_manager *cm = on->on_bi.bi_private;
3754 #ifdef PCACHE_CONTROL_PRIVDB
3755 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3756 return pcache_op_privdb( op, rs );
3758 #endif /* PCACHE_CONTROL_PRIVDB */
3760 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3761 struct berval uuid = BER_BVNULL;
3762 ber_tag_t tag = LBER_DEFAULT;
3764 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3765 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3766 assert( rs->sr_err == LDAP_SUCCESS );
3768 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3769 /* remove all queries related to the selected entry */
3770 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3771 cm, &op->o_req_ndn, &uuid );
3773 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3774 if ( !BER_BVISNULL( &uuid ) ) {
3775 /* remove the selected query */
3776 rs->sr_err = pcache_remove_query_from_cache( op,
3780 /* TODO: remove all queries */
3781 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3782 rs->sr_text = "deletion of all queries not implemented";
3786 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3791 #endif /* PCACHE_EXOP_QUERY_DELETE */
3793 static slap_overinst pcache;
3795 static char *obsolete_names[] = {
3800 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3802 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3807 struct berval debugbv = BER_BVC("pcache");
3809 code = slap_loglevel_get( &debugbv, &pcache_debug );
3814 #ifdef PCACHE_CONTROL_PRIVDB
3815 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3816 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3817 parse_privdb_ctrl, &privDB_cid );
3818 if ( code != LDAP_SUCCESS ) {
3819 Debug( LDAP_DEBUG_ANY,
3820 "pcache_initialize: failed to register control %s (%d)\n",
3821 PCACHE_CONTROL_PRIVDB, code, 0 );
3824 #endif /* PCACHE_CONTROL_PRIVDB */
3826 #ifdef PCACHE_EXOP_QUERY_DELETE
3827 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3828 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3830 if ( code != LDAP_SUCCESS ) {
3831 Debug( LDAP_DEBUG_ANY,
3832 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3836 #endif /* PCACHE_EXOP_QUERY_DELETE */
3838 for ( i = 0; as[i].desc != NULL; i++ ) {
3839 code = register_at( as[i].desc, as[i].adp, 0 );
3841 Debug( LDAP_DEBUG_ANY,
3842 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3845 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3848 pcache.on_bi.bi_type = "pcache";
3849 pcache.on_bi.bi_obsolete_names = obsolete_names;
3850 pcache.on_bi.bi_db_init = pcache_db_init;
3851 pcache.on_bi.bi_db_config = pcache_db_config;
3852 pcache.on_bi.bi_db_open = pcache_db_open;
3853 pcache.on_bi.bi_db_close = pcache_db_close;
3854 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3856 pcache.on_bi.bi_op_search = pcache_op_search;
3857 #ifdef PCACHE_CONTROL_PRIVDB
3858 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3859 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3860 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3861 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3862 pcache.on_bi.bi_op_add = pcache_op_privdb;
3863 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3864 #endif /* PCACHE_CONTROL_PRIVDB */
3865 #ifdef PCACHE_EXOP_QUERY_DELETE
3866 pcache.on_bi.bi_extended = pcache_op_extended;
3867 #elif defined( PCACHE_CONTROL_PRIVDB )
3868 pcache.on_bi.bi_extended = pcache_op_privdb;
3871 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3873 pcache.on_bi.bi_cf_ocs = pcocs;
3875 code = config_register_schema( pccfg, pcocs );
3876 if ( code ) return code;
3878 return overlay_register( &pcache );
3881 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3882 int init_module(int argc, char *argv[]) {
3883 return pcache_initialize();
3887 #endif /* defined(SLAPD_OVER_PROXYCACHE) */