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 count = attr->a_numvals;
1371 assert( count > 0 );
1372 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1373 qi->next = op->o_callback->sc_private;
1374 op->o_callback->sc_private = qi;
1375 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1376 qi->del = ( count == 1 );
1385 struct berval *query_uuid )
1387 struct query_info *qi, *qnext;
1388 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1389 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1390 Filter filter = {LDAP_FILTER_EQUALITY};
1391 SlapReply sreply = {REP_RESULT};
1392 slap_callback cb = { NULL, remove_func, NULL, NULL };
1395 sreply.sr_entry = NULL;
1396 sreply.sr_nentries = 0;
1397 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1398 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1399 filter.f_ava = &ava;
1400 filter.f_av_desc = ad_queryId;
1401 filter.f_av_value = *query_uuid;
1403 op->o_tag = LDAP_REQ_SEARCH;
1404 op->o_protocol = LDAP_VERSION3;
1405 op->o_callback = &cb;
1406 op->o_time = slap_get_time();
1407 op->o_do_not_cache = 1;
1409 op->o_req_dn = op->o_bd->be_suffix[0];
1410 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1411 op->ors_scope = LDAP_SCOPE_SUBTREE;
1412 op->ors_deref = LDAP_DEREF_NEVER;
1413 op->ors_slimit = SLAP_NO_LIMIT;
1414 op->ors_tlimit = SLAP_NO_LIMIT;
1415 op->ors_filter = &filter;
1416 op->ors_filterstr.bv_val = filter_str;
1417 op->ors_filterstr.bv_len = strlen(filter_str);
1418 op->ors_attrs = NULL;
1419 op->ors_attrsonly = 0;
1421 op->o_bd->be_search( op, &sreply );
1423 for ( qi=cb.sc_private; qi; qi=qnext ) {
1426 op->o_req_dn = qi->xdn;
1427 op->o_req_ndn = qi->xdn;
1430 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1431 query_uuid->bv_val, 0, 0 );
1433 op->o_tag = LDAP_REQ_DELETE;
1435 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1441 struct berval vals[2];
1443 vals[0] = *query_uuid;
1444 vals[1].bv_val = NULL;
1446 mod.sml_op = LDAP_MOD_DELETE;
1448 mod.sml_desc = ad_queryId;
1449 mod.sml_type = ad_queryId->ad_cname;
1450 mod.sml_values = vals;
1451 mod.sml_nvalues = NULL;
1452 mod.sml_numvals = 1;
1453 mod.sml_next = NULL;
1454 Debug( pcache_debug,
1455 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1456 query_uuid->bv_val, 0, 0 );
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;
1487 switch ( f->f_choice ) {
1488 case LDAP_FILTER_EQUALITY:
1490 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1491 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1492 assert( ret == len );
1493 fstr->bv_len += len;
1496 case LDAP_FILTER_GE:
1498 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1499 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1500 assert( ret == len );
1501 fstr->bv_len += len;
1504 case LDAP_FILTER_LE:
1506 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1507 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1508 assert( ret == len );
1509 fstr->bv_len += len;
1512 case LDAP_FILTER_APPROX:
1514 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1515 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1516 assert( ret == len );
1517 fstr->bv_len += len;
1520 case LDAP_FILTER_SUBSTRINGS:
1522 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1523 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1524 assert( ret == len );
1525 fstr->bv_len += len;
1528 case LDAP_FILTER_PRESENT:
1530 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1531 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1532 assert( ret == len );
1533 fstr->bv_len += len;
1536 case LDAP_FILTER_AND:
1537 case LDAP_FILTER_OR:
1538 case LDAP_FILTER_NOT: {
1540 fstr->bv_val[fstr->bv_len++] = '(';
1541 switch ( f->f_choice ) {
1542 case LDAP_FILTER_AND:
1543 fstr->bv_val[fstr->bv_len] = '&';
1545 case LDAP_FILTER_OR:
1546 fstr->bv_val[fstr->bv_len] = '|';
1548 case LDAP_FILTER_NOT:
1549 fstr->bv_val[fstr->bv_len] = '!';
1554 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1555 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1559 fstr->bv_val[fstr->bv_len++] = ')';
1560 fstr->bv_val[fstr->bv_len] = '\0';
1566 /* a filter should at least have room for "()",
1567 * an "=" and for a 1-char attr */
1568 strcpy( fstr->bv_val, "(?=)" );
1569 fstr->bv_len += STRLENOF("(?=)");
1573 if ( filter_attrs != NULL ) {
1574 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1575 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1577 (*filter_attrs)[*filter_cnt].an_desc = ad;
1578 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1579 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1580 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1581 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1583 if ( ad == slap_schema.si_ad_objectClass )
1590 struct search_info {
1593 QueryTemplate *qtemp;
1594 AttributeName* save_attrs; /* original attributes, saved for response */
1599 int slimit_exceeded;
1600 pc_caching_reason_t caching_reason;
1605 remove_query_and_data(
1609 struct berval *uuid )
1611 query_manager* qm = cm->qm;
1613 qm->crfunc( qm, uuid );
1614 if ( !BER_BVISNULL( uuid ) ) {
1617 Debug( pcache_debug,
1618 "Removing query UUID %s\n",
1619 uuid->bv_val, 0, 0 );
1620 return_val = remove_query_data( op, rs, uuid );
1621 Debug( pcache_debug,
1622 "QUERY REMOVED, SIZE=%d\n",
1624 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1625 cm->cur_entries -= return_val;
1626 cm->num_cached_queries--;
1627 Debug( pcache_debug,
1628 "STORED QUERIES = %lu\n",
1629 cm->num_cached_queries, 0, 0 );
1630 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1631 Debug( pcache_debug,
1632 "QUERY REMOVED, CACHE ="
1634 cm->cur_entries, 0, 0 );
1639 * Callback used to fetch queryId values based on entryUUID;
1640 * used by pcache_remove_entries_from_cache()
1643 fetch_queryId_cb( Operation *op, SlapReply *rs )
1647 /* only care about searchEntry responses */
1648 if ( rs->sr_type != REP_SEARCH ) {
1652 /* allow only one response per entryUUID */
1653 if ( op->o_callback->sc_private != NULL ) {
1659 /* copy all queryId values into callback's private data */
1660 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1662 BerVarray vals = NULL;
1664 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1665 op->o_callback->sc_private = (void *)vals;
1669 /* clear entry if required */
1670 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1671 entry_free( rs->sr_entry );
1672 rs->sr_entry = NULL;
1673 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1680 * Call that allows to remove a set of entries from the cache,
1681 * by forcing the removal of all the related queries.
1684 pcache_remove_entries_from_cache(
1687 BerVarray entryUUIDs )
1689 Connection conn = { 0 };
1690 OperationBuffer opbuf;
1692 slap_callback sc = { 0 };
1693 SlapReply rs = { REP_RESULT };
1695 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1696 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1697 AttributeName attrs[ 2 ] = { 0 };
1701 void *thrctx = ldap_pvt_thread_pool_context();
1703 connection_fake_init( &conn, &opbuf, thrctx );
1711 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1712 op->ors_scope = LDAP_SCOPE_SUBTREE;
1713 op->ors_deref = LDAP_DEREF_NEVER;
1714 f.f_choice = LDAP_FILTER_EQUALITY;
1716 ava.aa_desc = slap_schema.si_ad_entryUUID;
1717 op->ors_filter = &f;
1719 op->ors_tlimit = SLAP_NO_LIMIT;
1720 attrs[ 0 ].an_desc = ad_queryId;
1721 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1722 op->ors_attrs = attrs;
1723 op->ors_attrsonly = 0;
1725 op->o_req_dn = cm->db.be_suffix[ 0 ];
1726 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1728 op->o_tag = LDAP_REQ_SEARCH;
1729 op->o_protocol = LDAP_VERSION3;
1730 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1732 op->o_dn = op->o_bd->be_rootdn;
1733 op->o_ndn = op->o_bd->be_rootndn;
1734 sc.sc_response = fetch_queryId_cb;
1735 op->o_callback = ≻
1737 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1738 BerVarray vals = NULL;
1740 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1741 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1742 op->ors_filterstr.bv_val = filtbuf;
1743 ava.aa_value = entryUUIDs[ s ];
1745 rc = op->o_bd->be_search( op, &rs );
1746 if ( rc != LDAP_SUCCESS ) {
1750 vals = (BerVarray)op->o_callback->sc_private;
1751 if ( vals != NULL ) {
1754 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1755 struct berval val = vals[ i ];
1757 remove_query_and_data( op, &rs, cm, &val );
1759 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1760 ch_free( val.bv_val );
1764 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1765 op->o_callback->sc_private = NULL;
1773 * Call that allows to remove a query from the cache.
1776 pcache_remove_query_from_cache(
1779 struct berval *queryid )
1781 Operation op2 = *op;
1782 SlapReply rs2 = { 0 };
1786 /* remove the selected query */
1787 remove_query_and_data( &op2, &rs2, cm, queryid );
1789 return LDAP_SUCCESS;
1793 * Call that allows to remove a set of queries related to an entry
1794 * from the cache; if queryid is not null, the entry must belong to
1795 * the query indicated by queryid.
1798 pcache_remove_entry_queries_from_cache(
1802 struct berval *queryid )
1804 Connection conn = { 0 };
1805 OperationBuffer opbuf;
1807 slap_callback sc = { 0 };
1808 SlapReply rs = { REP_RESULT };
1810 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1811 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1812 AttributeName attrs[ 2 ] = { 0 };
1815 BerVarray vals = NULL;
1818 void *thrctx = ldap_pvt_thread_pool_context();
1820 connection_fake_init( &conn, &opbuf, thrctx );
1828 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1829 op->ors_scope = LDAP_SCOPE_BASE;
1830 op->ors_deref = LDAP_DEREF_NEVER;
1831 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1832 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1833 f.f_choice = LDAP_FILTER_PRESENT;
1834 f.f_desc = slap_schema.si_ad_objectClass;
1837 op->ors_filterstr.bv_len = snprintf( filter_str,
1838 sizeof( filter_str ), "(%s=%s)",
1839 ad_queryId->ad_cname.bv_val, queryid->bv_val );
1840 f.f_choice = LDAP_FILTER_EQUALITY;
1842 f.f_av_desc = ad_queryId;
1843 f.f_av_value = *queryid;
1845 op->ors_filter = &f;
1847 op->ors_tlimit = SLAP_NO_LIMIT;
1848 attrs[ 0 ].an_desc = ad_queryId;
1849 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1850 op->ors_attrs = attrs;
1851 op->ors_attrsonly = 0;
1853 op->o_req_dn = *ndn;
1854 op->o_req_ndn = *ndn;
1856 op->o_tag = LDAP_REQ_SEARCH;
1857 op->o_protocol = LDAP_VERSION3;
1858 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1860 op->o_dn = op->o_bd->be_rootdn;
1861 op->o_ndn = op->o_bd->be_rootndn;
1862 sc.sc_response = fetch_queryId_cb;
1863 op->o_callback = ≻
1865 rc = op->o_bd->be_search( op, &rs );
1866 if ( rc != LDAP_SUCCESS ) {
1870 vals = (BerVarray)op->o_callback->sc_private;
1871 if ( vals != NULL ) {
1874 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1875 struct berval val = vals[ i ];
1877 remove_query_and_data( op, &rs, cm, &val );
1879 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1880 ch_free( val.bv_val );
1884 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1887 return LDAP_SUCCESS;
1894 struct berval *query_uuid )
1896 struct search_info *si = op->o_callback->sc_private;
1897 slap_overinst *on = si->on;
1898 cache_manager *cm = on->on_bi.bi_private;
1901 struct berval crp_uuid;
1902 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1903 Operation op_tmp = *op;
1905 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1906 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1908 op_tmp.o_bd = &cm->db;
1909 op_tmp.o_dn = cm->db.be_rootdn;
1910 op_tmp.o_ndn = cm->db.be_rootndn;
1912 Debug( pcache_debug, "UUID for query being added = %s\n",
1915 for ( e=si->head; e; e=si->head ) {
1916 si->head = e->e_private;
1917 e->e_private = NULL;
1918 while ( cm->cur_entries > (cm->max_entries) ) {
1919 BER_BVZERO( &crp_uuid );
1920 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1923 return_val = merge_entry(&op_tmp, e, query_uuid);
1924 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1925 cm->cur_entries += return_val;
1926 Debug( pcache_debug,
1927 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1928 cm->cur_entries, 0, 0 );
1930 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1937 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1938 slap_callback *cb = op->o_callback;
1939 struct search_info *si = cb->sc_private;
1940 slap_overinst *on = si->on;
1941 cache_manager *cm = on->on_bi.bi_private;
1942 query_manager* qm = cm->qm;
1944 if ( rs->sr_type == REP_SEARCH ) {
1947 /* don't return more entries than requested by the client */
1948 if ( si->slimit && rs->sr_nentries >= si->slimit ) {
1949 si->slimit_exceeded = 1;
1952 /* If we haven't exceeded the limit for this query,
1953 * build a chain of answers to store. If we hit the
1954 * limit, empty the chain and ignore the rest.
1957 if ( si->count < si->max ) {
1959 e = entry_dup( rs->sr_entry );
1960 if ( !si->head ) si->head = e;
1961 if ( si->tail ) si->tail->e_private = e;
1967 for (;si->head; si->head=e) {
1968 e = si->head->e_private;
1969 si->head->e_private = NULL;
1970 entry_free(si->head);
1978 if ( rs->sr_type == REP_RESULT ||
1979 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
1981 if ( si->save_attrs != NULL ) {
1982 rs->sr_attrs = si->save_attrs;
1983 op->ors_attrs = si->save_attrs;
1985 if ( op->o_abandon || rs->sr_err == SLAPD_ABANDON ) {
1986 filter_free( si->query.filter );
1988 /* duplicate query, free it */
1990 for (;si->head; si->head=e) {
1991 e = si->head->e_private;
1992 si->head->e_private = NULL;
1993 entry_free(si->head);
1996 op->o_callback = op->o_callback->sc_next;
1997 op->o_tmpfree( cb, op->o_tmpmemctx );
1998 } else if ( si->caching_reason != PC_IGNORE ) {
1999 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2000 si->qtemp, si->caching_reason, 1 );
2003 switch ( si->caching_reason ) {
2005 cache_entries( op, rs, &qc->q_uuid );
2009 qc->q_sizelimit = rs->sr_nentries;
2012 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2013 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2014 cm->num_cached_queries++;
2015 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2016 cm->num_cached_queries, 0, 0 );
2017 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2019 /* If the consistency checker suspended itself,
2022 if ( cm->cc_paused ) {
2023 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2024 if ( cm->cc_paused ) {
2026 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2028 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2031 } else if ( si->count ) {
2032 /* duplicate query, free it */
2034 for (;si->head; si->head=e) {
2035 e = si->head->e_private;
2036 si->head->e_private = NULL;
2037 entry_free(si->head);
2042 filter_free( si->query.filter );
2046 return SLAP_CB_CONTINUE;
2054 struct search_info *si = op->o_callback->sc_private;
2056 if ( si->save_attrs != NULL ) {
2057 rs->sr_attrs = si->save_attrs;
2058 op->ors_attrs = si->save_attrs;
2061 if ( rs->sr_type == REP_SEARCH ) {
2062 /* don't return more entries than requested by the client */
2063 if ( si->slimit_exceeded ) {
2067 } else if ( rs->sr_type == REP_RESULT ) {
2070 if ( rs->sr_err == LDAP_SUCCESS ) {
2071 si->caching_reason = PC_POSITIVE;
2073 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2074 && si->qtemp->limitttl )
2076 si->caching_reason = PC_SIZELIMIT;
2079 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2080 rs->sr_err == LDAP_SUCCESS )
2082 si->caching_reason = PC_NEGATIVE;
2086 if ( si->slimit_exceeded ) {
2087 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2091 return SLAP_CB_CONTINUE;
2097 AttributeName** new_attrs,
2098 struct attr_set *attrs,
2099 AttributeName* filter_attrs,
2109 /* duplicate attrs */
2110 count = attrs->count + fattr_cnt;
2111 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2116 *new_attrs = (AttributeName*)ch_calloc( count + 1,
2117 sizeof(AttributeName) );
2118 for (i=0; i<attrs->count; i++) {
2119 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2120 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2122 BER_BVZERO( &(*new_attrs)[i].an_name );
2123 alluser = an_find(*new_attrs, &AllUser);
2124 allop = an_find(*new_attrs, &AllOper);
2127 for ( i=0; i<fattr_cnt; i++ ) {
2128 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2131 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2135 } else if ( alluser ) {
2138 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2139 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2140 (*new_attrs)[j].an_oc = NULL;
2141 (*new_attrs)[j].an_oc_exclude = 0;
2145 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2146 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2147 (*new_attrs)[j].an_oc = NULL;
2148 (*new_attrs)[j].an_oc_exclude = 0;
2151 BER_BVZERO( &(*new_attrs)[j].an_name );
2156 /* NOTE: this is a quick workaround to let pcache minimally interact
2157 * with pagedResults. A more articulated solutions would be to
2158 * perform the remote query without control and cache all results,
2159 * performing the pagedResults search only within the client
2160 * and the proxy. This requires pcache to understand pagedResults. */
2162 pcache_chk_controls(
2166 const char *non = "";
2167 const char *stripped = "";
2169 switch( op->o_pagedresults ) {
2170 case SLAP_CONTROL_NONCRITICAL:
2172 stripped = "; stripped";
2175 case SLAP_CONTROL_CRITICAL:
2176 Debug( pcache_debug, "%s: "
2177 "%scritical pagedResults control "
2178 "disabled with proxy cache%s.\n",
2179 op->o_log_prefix, non, stripped );
2181 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2185 rs->sr_err = SLAP_CB_CONTINUE;
2192 #ifdef PCACHE_CONTROL_PRIVDB
2198 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2199 cache_manager *cm = on->on_bi.bi_private;
2200 slap_callback *save_cb;
2203 /* skip if control is unset */
2204 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2205 return SLAP_CB_CONTINUE;
2208 /* FIXME: might be a little bit exaggerated... */
2209 if ( !be_isroot( op ) ) {
2210 save_cb = op->o_callback;
2211 op->o_callback = NULL;
2212 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2213 "pcachePrivDB: operation not allowed" );
2214 op->o_callback = save_cb;
2219 /* map tag to operation */
2220 type = slap_req2op( op->o_tag );
2221 if ( type != SLAP_OP_LAST ) {
2225 /* execute, if possible */
2226 func = &cm->db.be_bind;
2227 if ( func[ type ] != NULL ) {
2228 Operation op2 = *op;
2232 rc = func[ type ]( &op2, rs );
2233 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2234 op->o_conn->c_authz_cookie = cm->db.be_private;
2239 /* otherwise fall back to error */
2240 save_cb = op->o_callback;
2241 op->o_callback = NULL;
2242 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2243 "operation not supported with pcachePrivDB control" );
2244 op->o_callback = save_cb;
2248 #endif /* PCACHE_CONTROL_PRIVDB */
2255 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2256 cache_manager *cm = on->on_bi.bi_private;
2257 query_manager* qm = cm->qm;
2261 AttributeName *filter_attrs = NULL;
2264 QueryTemplate *qtemp = NULL;
2267 CachedQuery *answerable = NULL;
2270 int fattr_got_oc = 0;
2272 struct berval tempstr;
2274 #ifdef PCACHE_CONTROL_PRIVDB
2275 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2276 return pcache_op_privdb( op, rs );
2278 #endif /* PCACHE_CONTROL_PRIVDB */
2280 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2282 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2283 &fattr_cnt, &fattr_got_oc )) {
2284 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2285 return SLAP_CB_CONTINUE;
2288 Debug( pcache_debug, "query template of incoming query = %s\n",
2289 tempstr.bv_val, 0, 0 );
2291 /* FIXME: cannot cache/answer requests with pagedResults control */
2294 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2296 query.filter = op->ors_filter;
2297 query.base = op->o_req_ndn;
2298 query.scope = op->ors_scope;
2300 /* check for query containment */
2301 if (attr_set > -1) {
2302 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2303 for (; qt; qt = qt->qtnext ) {
2304 /* find if template i can potentially answer tempstr */
2305 if (qt->querystr.bv_len != tempstr.bv_len ||
2306 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2310 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2311 op->ors_filterstr.bv_val, 0, 0 );
2312 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2318 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2321 /* Need to clear the callbacks of the original operation,
2322 * in case there are other overlays */
2323 BackendDB *save_bd = op->o_bd;
2324 slap_callback *save_cb = op->o_callback;
2326 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2327 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2328 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
2329 if ( BER_BVISNULL( &answerable->q_uuid )) {
2330 /* No entries cached, just an empty result set */
2332 send_ldap_result( op, rs );
2335 op->o_callback = NULL;
2336 i = cm->db.bd_info->bi_op_search( op, rs );
2338 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
2339 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2341 op->o_callback = save_cb;
2345 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2347 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2348 if (cm->num_cached_queries >= cm->max_queries) {
2351 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2353 if (op->ors_attrsonly)
2358 struct search_info *si;
2360 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2361 query.filter = filter_dup(op->ors_filter, NULL);
2362 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2363 if ( !qtemp->t_attrs.count ) {
2364 qtemp->t_attrs.count = add_filter_attrs(op,
2365 &qtemp->t_attrs.attrs,
2366 &qm->attr_sets[attr_set],
2367 filter_attrs, fattr_cnt, fattr_got_oc);
2369 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2371 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2372 cb->sc_response = pcache_response;
2373 cb->sc_cleanup = pcache_op_cleanup;
2374 cb->sc_private = (cb+1);
2375 si = cb->sc_private;
2379 si->max = cm->num_entries_limit ;
2383 si->slimit_exceeded = 0;
2384 si->caching_reason = PC_IGNORE;
2385 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2386 si->slimit = op->ors_slimit;
2387 op->ors_slimit = cm->num_entries_limit;
2391 si->save_attrs = op->ors_attrs;
2393 op->ors_attrs = qtemp->t_attrs.attrs;
2395 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2396 cb->sc_next = op->o_callback;
2397 op->o_callback = cb;
2400 slap_callback **pcb;
2402 /* need to move the callback at the end, in case other
2403 * overlays are present, so that the final entry is
2404 * actually cached */
2406 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2411 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2415 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2417 return SLAP_CB_CONTINUE;
2422 AttributeName* attrs,
2430 for ( ; attrs[count].an_name.bv_val; count++ );
2433 /* recognize a single "*" or a "1.1" */
2436 attrs = slap_anlist_all_user_attributes;
2438 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2443 for ( i = 0; i < num; i++ ) {
2447 if ( count > qm->attr_sets[i].count ) {
2452 if ( !qm->attr_sets[i].count ) {
2458 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2459 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2482 struct re_s *rtask = arg;
2483 slap_overinst *on = rtask->arg;
2484 cache_manager *cm = on->on_bi.bi_private;
2485 query_manager *qm = cm->qm;
2486 Connection conn = {0};
2487 OperationBuffer opbuf;
2490 SlapReply rs = {REP_RESULT};
2492 int return_val, pause = 1;
2493 QueryTemplate* templ;
2495 connection_fake_init( &conn, &opbuf, ctx );
2499 op->o_dn = cm->db.be_rootdn;
2500 op->o_ndn = cm->db.be_rootndn;
2504 for (templ = qm->templates; templ; templ=templ->qmnext) {
2505 query = templ->query_last;
2506 if ( query ) pause = 0;
2507 op->o_time = slap_get_time();
2508 while (query && (query->expiry_time < op->o_time)) {
2510 Debug( pcache_debug, "Lock CR index = %p\n",
2511 (void *) templ, 0, 0 );
2512 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2513 if ( query == templ->query_last ) {
2515 remove_from_template(query, templ);
2516 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2517 (void *) templ, templ->no_of_queries, 0 );
2518 Debug( pcache_debug, "Unlock CR index = %p\n",
2519 (void *) templ, 0, 0 );
2521 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2523 query = templ->query_last;
2526 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2527 remove_query(qm, query);
2528 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2529 if ( BER_BVISNULL( &query->q_uuid ))
2532 return_val = remove_query_data(op, &rs, &query->q_uuid);
2533 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2535 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2536 cm->cur_entries -= return_val;
2537 cm->num_cached_queries--;
2538 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2539 cm->num_cached_queries, 0, 0 );
2540 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2541 Debug( pcache_debug,
2542 "STALE QUERY REMOVED, CACHE ="
2544 cm->cur_entries, 0, 0 );
2546 query = templ->query_last;
2549 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2550 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2551 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2553 /* If there were no queries, defer processing for a while */
2554 cm->cc_paused = pause;
2555 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2557 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2562 #define MAX_ATTR_SETS 500
2572 static ConfigDriver pc_cf_gen;
2573 static ConfigLDAPadd pc_ldadd;
2574 static ConfigCfAdd pc_cfadd;
2576 static ConfigTable pccfg[] = {
2577 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2579 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2580 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2581 "DESC 'ProxyCache basic parameters' "
2582 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2583 { "proxyattrset", "index> <attributes...",
2584 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2585 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2586 "DESC 'A set of attributes to cache' "
2587 "SYNTAX OMsDirectoryString )", NULL, NULL },
2588 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2589 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2590 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2591 "DESC 'Filter template, attrset, cache TTL, "
2592 "optional negative TTL, optional sizelimit TTL' "
2593 "SYNTAX OMsDirectoryString )", NULL, NULL },
2594 { "response-callback", "head|tail(default)",
2595 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2596 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2597 "DESC 'Response callback position in overlay stack' "
2598 "SYNTAX OMsDirectoryString )", NULL, NULL },
2599 { "proxyCacheQueries", "queries",
2600 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2601 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2602 "DESC 'Maximum number of queries to cache' "
2603 "SYNTAX OMsInteger )", NULL, NULL },
2604 { "proxySaveQueries", "TRUE|FALSE",
2605 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2606 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2607 "DESC 'Save cached queries for hot restart' "
2608 "SYNTAX OMsBoolean )", NULL, NULL },
2610 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2613 static ConfigOCs pcocs[] = {
2614 { "( OLcfgOvOc:2.1 "
2615 "NAME 'olcPcacheConfig' "
2616 "DESC 'ProxyCache configuration' "
2617 "SUP olcOverlayConfig "
2618 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2619 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2620 Cft_Overlay, pccfg, NULL, pc_cfadd },
2621 { "( OLcfgOvOc:2.2 "
2622 "NAME 'olcPcacheDatabase' "
2623 "DESC 'Cache database configuration' "
2624 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2629 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2634 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2635 p->ce_bi->bi_cf_ocs != pcocs )
2636 return LDAP_CONSTRAINT_VIOLATION;
2638 on = (slap_overinst *)p->ce_bi;
2639 cm = on->on_bi.bi_private;
2641 return LDAP_SUCCESS;
2645 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2647 CfEntryInfo *pe = p->e_private;
2648 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2649 cache_manager *cm = on->on_bi.bi_private;
2652 /* FIXME: should not hardcode "olcDatabase" here */
2653 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
2654 "olcDatabase=%s", cm->db.bd_info->bi_type );
2655 if ( bv.bv_len < 0 || bv.bv_len >= sizeof( ca->cr_msg ) ) {
2658 bv.bv_val = ca->cr_msg;
2661 /* We can only create this entry if the database is table-driven
2663 if ( cm->db.bd_info->bi_cf_ocs )
2664 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2671 pc_cf_gen( ConfigArgs *c )
2673 slap_overinst *on = (slap_overinst *)c->bi;
2674 cache_manager* cm = on->on_bi.bi_private;
2675 query_manager* qm = cm->qm;
2676 QueryTemplate* temp;
2677 AttributeName* attr_name;
2678 AttributeName* attrarray;
2679 const char* text=NULL;
2684 if ( c->op == SLAP_CONFIG_EMIT ) {
2688 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2689 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2690 cm->num_entries_limit, cm->cc_period );
2691 bv.bv_val = c->cr_msg;
2692 value_add_one( &c->rvalue_vals, &bv );
2695 for (i=0; i<cm->numattrsets; i++) {
2696 if ( !qm->attr_sets[i].count ) continue;
2698 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2700 /* count the attr length */
2701 for ( attr_name = qm->attr_sets[i].attrs;
2702 attr_name->an_name.bv_val; attr_name++ )
2703 bv.bv_len += attr_name->an_name.bv_len + 1;
2705 bv.bv_val = ch_malloc( bv.bv_len+1 );
2706 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2707 for ( attr_name = qm->attr_sets[i].attrs;
2708 attr_name->an_name.bv_val; attr_name++ ) {
2710 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2712 ber_bvarray_add( &c->rvalue_vals, &bv );
2714 if ( !c->rvalue_vals )
2718 for (temp=qm->templates; temp; temp=temp->qmnext) {
2719 /* HEADS-UP: always print all;
2720 * if optional == 0, ignore */
2721 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2723 temp->attr_set_index,
2727 bv.bv_len += temp->querystr.bv_len + 2;
2728 bv.bv_val = ch_malloc( bv.bv_len+1 );
2731 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2733 strcpy( ptr, c->cr_msg );
2734 ber_bvarray_add( &c->rvalue_vals, &bv );
2736 if ( !c->rvalue_vals )
2740 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2741 BER_BVSTR( &bv, "head" );
2743 BER_BVSTR( &bv, "tail" );
2745 value_add_one( &c->rvalue_vals, &bv );
2748 c->value_int = cm->max_queries;
2752 } else if ( c->op == LDAP_MOD_DELETE ) {
2753 return 1; /* FIXME */
2765 if ( cm->numattrsets > 0 ) {
2766 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2767 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2771 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2772 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2774 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2777 if ( cm->numattrsets <= 0 ) {
2778 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2779 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2782 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2783 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2784 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2788 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2789 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2790 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2794 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2795 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2797 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2800 if ( cm->max_entries <= 0 ) {
2801 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2802 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2806 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2807 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2809 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2812 if ( cm->num_entries_limit <= 0 ) {
2813 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2814 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2817 if ( cm->num_entries_limit > cm->max_entries ) {
2818 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2819 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2823 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2824 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2826 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2829 cm->cc_period = (time_t)t;
2830 Debug( pcache_debug,
2831 "Total # of attribute sets to be cached = %d.\n",
2832 cm->numattrsets, 0, 0 );
2833 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2834 sizeof( struct attr_set ) );
2837 if ( cm->numattrsets == 0 ) {
2838 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2839 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2842 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2843 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2845 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2849 if ( num < 0 || num >= cm->numattrsets ) {
2850 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2851 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2852 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2855 qm->attr_sets[num].flags |= PC_CONFIGURED;
2856 if ( c->argc == 2 ) {
2858 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2859 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2860 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2863 } else if ( c->argc == 3 ) {
2864 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2865 qm->attr_sets[num].count = 1;
2866 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2867 sizeof( AttributeName ) );
2868 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2871 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2872 qm->attr_sets[num].count = 1;
2873 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2874 sizeof( AttributeName ) );
2875 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2878 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2881 /* else: fallthru */
2883 } else if ( c->argc == 4 ) {
2884 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2885 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2887 qm->attr_sets[num].count = 2;
2888 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2889 sizeof( AttributeName ) );
2890 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2891 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2894 /* else: fallthru */
2897 if ( c->argc > 2 ) {
2898 int all_user = 0, all_op = 0;
2900 qm->attr_sets[num].count = c->argc - 2;
2901 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2902 sizeof( AttributeName ) );
2903 attr_name = qm->attr_sets[num].attrs;
2904 for ( i = 2; i < c->argc; i++ ) {
2905 attr_name->an_desc = NULL;
2906 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2907 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2908 "invalid attr #%d \"%s\" in attrlist",
2909 i - 2, c->argv[i] );
2910 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2911 ch_free( qm->attr_sets[num].attrs );
2912 qm->attr_sets[num].attrs = NULL;
2913 qm->attr_sets[num].count = 0;
2916 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2918 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2919 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2921 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2923 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2924 strcpy( c->cr_msg, text );
2925 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2926 ch_free( qm->attr_sets[num].attrs );
2927 qm->attr_sets[num].attrs = NULL;
2928 qm->attr_sets[num].count = 0;
2931 attr_name->an_name = attr_name->an_desc->ad_cname;
2933 attr_name->an_oc = NULL;
2934 attr_name->an_oc_exclude = 0;
2935 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2936 qm->attr_sets[num].flags |= PC_GOT_OC;
2938 BER_BVZERO( &attr_name->an_name );
2941 /* warn if list contains both "*" and "+" */
2942 if ( i > 4 && all_user && all_op ) {
2943 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2944 "warning: attribute list contains \"*\" and \"+\"" );
2945 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2950 if ( cm->numattrsets == 0 ) {
2951 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2952 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2955 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2956 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2958 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2962 if ( i < 0 || i >= cm->numattrsets ||
2963 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2964 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2965 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2966 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2969 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2970 temp->qmnext = qm->templates;
2971 qm->templates = temp;
2972 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2973 temp->query = temp->query_last = NULL;
2974 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2975 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2976 "unable to parse template ttl=\"%s\"",
2978 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2981 temp->ttl = (time_t)t;
2982 temp->negttl = (time_t)0;
2983 temp->limitttl = (time_t)0;
2984 switch ( c->argc ) {
2986 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2987 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2988 "unable to parse template sizelimit ttl=\"%s\"",
2990 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2993 temp->limitttl = (time_t)t;
2997 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2998 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2999 "unable to parse template negative ttl=\"%s\"",
3001 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3004 temp->negttl = (time_t)t;
3008 temp->no_of_queries = 0;
3010 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3011 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3012 Debug( pcache_debug, " query template: %s\n",
3013 temp->querystr.bv_val, 0, 0 );
3014 temp->attr_set_index = i;
3015 qm->attr_sets[i].flags |= PC_REFERENCED;
3016 temp->qtnext = qm->attr_sets[i].templates;
3017 qm->attr_sets[i].templates = temp;
3018 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
3019 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3020 for ( i=0; attrarray[i].an_name.bv_val; i++ )
3021 Debug( pcache_debug, "\t%s\n",
3022 attrarray[i].an_name.bv_val, 0, 0 );
3026 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3027 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3029 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3030 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3033 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3034 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3039 if ( c->value_int <= 0 ) {
3040 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3041 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3044 cm->max_queries = c->value_int;
3059 slap_overinst *on = (slap_overinst *)be->bd_info;
3060 cache_manager* cm = on->on_bi.bi_private;
3062 /* Something for the cache database? */
3063 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3064 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3066 return SLAP_CONF_UNKNOWN;
3074 slap_overinst *on = (slap_overinst *)be->bd_info;
3078 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3079 on->on_bi.bi_private = cm;
3081 qm = (query_manager*)ch_malloc(sizeof(query_manager));
3084 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3085 cm->db.be_private = NULL;
3086 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
3088 cm->numattrsets = 0;
3089 cm->num_entries_limit = 5;
3090 cm->num_cached_queries = 0;
3091 cm->max_entries = 0;
3092 cm->cur_entries = 0;
3093 cm->max_queries = 10000;
3094 cm->save_queries = 0;
3095 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3096 cm->cc_period = 1000;
3099 qm->attr_sets = NULL;
3100 qm->templates = NULL;
3102 qm->lru_bottom = NULL;
3104 qm->qcfunc = query_containment;
3105 qm->crfunc = cache_replacement;
3106 qm->addfunc = add_query;
3107 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3109 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3114 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3116 assert( op->o_tag == LDAP_REQ_SEARCH );
3118 if ( rs->sr_type == REP_SEARCH ) {
3121 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3125 assert( a->a_nvals != NULL );
3127 valsp = op->o_callback->sc_private;
3128 assert( *valsp == NULL );
3130 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3138 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3140 assert( op->o_tag == LDAP_REQ_SEARCH );
3142 if ( rs->sr_type == REP_SEARCH ) {
3143 int *countp = (int *)op->o_callback->sc_private;
3156 slap_overinst *on = (slap_overinst *)be->bd_info;
3157 cache_manager *cm = on->on_bi.bi_private;
3158 query_manager* qm = cm->qm;
3159 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3161 /* check attr sets */
3162 for ( i = 0; i < cm->numattrsets; i++) {
3163 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3164 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3165 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3169 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3173 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3174 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3179 if ( ncf || rf || nrf ) {
3180 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3181 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3182 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3189 /* need to inherit something from the original database... */
3190 cm->db.be_def_limit = be->be_def_limit;
3191 cm->db.be_limits = be->be_limits;
3192 cm->db.be_acl = be->be_acl;
3193 cm->db.be_dfltaccess = be->be_dfltaccess;
3195 if ( SLAP_DBMONITORING( be ) ) {
3196 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3199 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3202 rc = backend_startup_one( &cm->db, NULL );
3204 /* There is no runqueue in TOOL mode */
3205 if ( slapMode & SLAP_SERVER_MODE ) {
3206 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3207 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3208 consistency_check, on,
3209 "pcache_consistency", be->be_suffix[0].bv_val );
3210 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3212 /* Cached database must have the rootdn */
3213 if ( BER_BVISNULL( &cm->db.be_rootndn )
3214 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3216 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3217 "underlying database of type \"%s\"\n"
3218 " serving naming context \"%s\"\n"
3219 " has no \"rootdn\", required by \"proxycache\".\n",
3220 on->on_info->oi_orig->bi_type,
3221 cm->db.be_suffix[0].bv_val, 0 );
3225 if ( cm->save_queries ) {
3226 void *thrctx = ldap_pvt_thread_pool_context();
3227 Connection conn = { 0 };
3228 OperationBuffer opbuf;
3230 slap_callback cb = { 0 };
3231 SlapReply rs = { 0 };
3232 BerVarray vals = NULL;
3233 Filter f = { 0 }, f2 = { 0 };
3234 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3235 AttributeName attrs[ 2 ] = { 0 };
3237 connection_fake_init( &conn, &opbuf, thrctx );
3242 op->o_tag = LDAP_REQ_SEARCH;
3243 op->o_protocol = LDAP_VERSION3;
3244 cb.sc_response = pcache_cachedquery_open_cb;
3245 cb.sc_private = &vals;
3246 op->o_callback = &cb;
3247 op->o_time = slap_get_time();
3248 op->o_do_not_cache = 1;
3249 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3251 op->o_dn = cm->db.be_rootdn;
3252 op->o_ndn = cm->db.be_rootndn;
3253 op->o_req_dn = cm->db.be_suffix[ 0 ];
3254 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3256 op->ors_scope = LDAP_SCOPE_BASE;
3257 op->ors_deref = LDAP_DEREF_NEVER;
3259 op->ors_tlimit = SLAP_NO_LIMIT;
3260 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3261 f.f_choice = LDAP_FILTER_PRESENT;
3262 f.f_desc = ad_cachedQueryURL;
3263 op->ors_filter = &f;
3264 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3265 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3266 op->ors_attrs = attrs;
3267 op->ors_attrsonly = 0;
3269 rc = op->o_bd->be_search( op, &rs );
3270 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3273 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3274 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3275 cm->num_cached_queries++;
3279 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3282 /* count cached entries */
3283 f.f_choice = LDAP_FILTER_NOT;
3285 f2.f_choice = LDAP_FILTER_EQUALITY;
3287 f2.f_av_desc = slap_schema.si_ad_objectClass;
3288 BER_BVSTR( &f2.f_av_value, "glue" );
3289 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3291 op->ors_slimit = SLAP_NO_LIMIT;
3292 op->ors_scope = LDAP_SCOPE_SUBTREE;
3293 op->ors_attrs = slap_anlist_no_attrs;
3295 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3297 op->o_callback->sc_private = &rs.sr_nentries;
3299 rc = op->o_bd->be_search( op, &rs );
3301 cm->cur_entries = rs.sr_nentries;
3312 pcache_free_qbase( void *v )
3318 tavl_free( qb->scopes[i], NULL );
3328 slap_overinst *on = (slap_overinst *)be->bd_info;
3329 cache_manager *cm = on->on_bi.bi_private;
3330 query_manager *qm = cm->qm;
3334 if ( cm->save_queries ) {
3336 BerVarray vals = NULL;
3339 Connection conn = { 0 };
3340 OperationBuffer opbuf;
3342 slap_callback cb = { 0 };
3344 SlapReply rs = { REP_RESULT };
3345 Modifications mod = { 0 };
3347 thrctx = ldap_pvt_thread_pool_context();
3349 connection_fake_init( &conn, &opbuf, thrctx );
3352 if ( qm->templates != NULL ) {
3353 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3354 for ( qc = tm->query; qc; qc = qc->next ) {
3357 if ( query2url( op, qc, &bv ) == 0 ) {
3358 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3365 op->o_dn = cm->db.be_rootdn;
3366 op->o_ndn = cm->db.be_rootndn;
3368 op->o_tag = LDAP_REQ_MODIFY;
3369 op->o_protocol = LDAP_VERSION3;
3370 cb.sc_response = slap_null_cb;
3371 op->o_callback = &cb;
3372 op->o_time = slap_get_time();
3373 op->o_do_not_cache = 1;
3374 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3376 op->o_req_dn = op->o_bd->be_suffix[0];
3377 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3379 mod.sml_op = LDAP_MOD_REPLACE;
3381 mod.sml_desc = ad_cachedQueryURL;
3382 mod.sml_type = ad_cachedQueryURL->ad_cname;
3383 mod.sml_values = vals;
3384 mod.sml_nvalues = NULL;
3385 mod.sml_numvals = 1;
3386 mod.sml_next = NULL;
3387 Debug( pcache_debug,
3388 "%sSETTING CACHED QUERY URLS\n",
3389 vals == NULL ? "RE" : "", 0, 0 );
3391 op->orm_modlist = &mod;
3393 op->o_bd->be_modify( op, &rs );
3395 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3398 /* cleanup stuff inherited from the original database... */
3399 cm->db.be_limits = NULL;
3400 cm->db.be_acl = NULL;
3402 /* stop the thread ... */
3404 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3405 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3406 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3408 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3409 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3412 if ( cm->db.bd_info->bi_db_close ) {
3413 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3415 while ( (tm = qm->templates) != NULL ) {
3416 CachedQuery *qc, *qn;
3417 qm->templates = tm->qmnext;
3418 for ( qc = tm->query; qc; qc = qn ) {
3422 avl_free( tm->qbase, pcache_free_qbase );
3423 free( tm->querystr.bv_val );
3424 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3425 free( tm->t_attrs.attrs );
3429 for ( i=0; i<cm->numattrsets; i++ ) {
3430 free( qm->attr_sets[i].attrs );
3432 free( qm->attr_sets );
3433 qm->attr_sets = NULL;
3444 slap_overinst *on = (slap_overinst *)be->bd_info;
3445 cache_manager *cm = on->on_bi.bi_private;
3446 query_manager *qm = cm->qm;
3448 if ( cm->db.be_private != NULL ) {
3449 backend_stopdown_one( &cm->db );
3452 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3453 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3460 #ifdef PCACHE_CONTROL_PRIVDB
3462 Control ::= SEQUENCE {
3463 controlType LDAPOID,
3464 criticality BOOLEAN DEFAULT FALSE,
3465 controlValue OCTET STRING OPTIONAL }
3467 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3469 * criticality must be TRUE; controlValue must be absent.
3477 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3478 rs->sr_text = "privateDB control specified multiple times";
3479 return LDAP_PROTOCOL_ERROR;
3482 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3483 rs->sr_text = "privateDB control value not absent";
3484 return LDAP_PROTOCOL_ERROR;
3487 if ( !ctrl->ldctl_iscritical ) {
3488 rs->sr_text = "privateDB control criticality required";
3489 return LDAP_PROTOCOL_ERROR;
3492 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3494 return LDAP_SUCCESS;
3497 static char *extops[] = {
3498 LDAP_EXOP_MODIFY_PASSWD,
3501 #endif /* PCACHE_CONTROL_PRIVDB */
3503 #ifdef PCACHE_EXOP_QUERY_DELETE
3504 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3506 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3507 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3508 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3511 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3512 requestName [0] LDAPOID,
3513 requestValue [1] OCTET STRING OPTIONAL }
3515 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3517 requestValue ::= SEQUENCE { CHOICE {
3519 entryDN [1] LDAPDN },
3520 queryID [2] OCTET STRING (SIZE(16))
3521 -- constrained to UUID }
3523 * Either baseDN or entryDN must be present, to allow database selection.
3525 * 1. if baseDN and queryID are present, then the query corresponding
3526 * to queryID is deleted;
3527 * 2. if baseDN is present and queryID is absent, then all queries
3529 * 3. if entryDN is present and queryID is absent, then all queries
3530 * corresponding to the queryID values present in entryDN are deleted;
3531 * 4. if entryDN and queryID are present, then all queries
3532 * corresponding to the queryID values present in entryDN are deleted,
3533 * but only if the value of queryID is contained in the entry;
3535 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3536 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3537 * or by removing the database files.
3539 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3540 COMPONENTS OF LDAPResult,
3541 responseName [10] LDAPOID OPTIONAL,
3542 responseValue [11] OCTET STRING OPTIONAL }
3544 * responseName and responseValue must be absent.
3548 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3549 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3550 * - if ndn != NULL, it is set to the normalized DN in the request
3551 * corresponding to either the baseDN or the entryDN, according
3552 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3553 * be freed by the caller.
3554 * - if uuid != NULL, it is set to point to the normalized UUID;
3555 * memory is malloc'ed on the Operation's slab, and must
3556 * be freed by the caller.
3559 pcache_parse_query_delete(
3563 struct berval *uuid,
3567 int rc = LDAP_SUCCESS;
3570 BerElementBuffer berbuf;
3571 BerElement *ber = (BerElement *)&berbuf;
3572 struct berval reqdata = BER_BVNULL;
3584 if ( in == NULL || in->bv_len == 0 ) {
3585 *text = "empty request data field in queryDelete exop";
3586 return LDAP_PROTOCOL_ERROR;
3589 ber_dupbv_x( &reqdata, in, ctx );
3591 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3592 ber_init2( ber, &reqdata, 0 );
3594 tag = ber_scanf( ber, "{" /*}*/ );
3596 if ( tag == LBER_ERROR ) {
3597 Debug( LDAP_DEBUG_TRACE,
3598 "pcache_parse_query_delete: decoding error.\n",
3600 goto decoding_error;
3603 tag = ber_peek_tag( ber, &len );
3604 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3605 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3609 if ( ndn != NULL ) {
3612 tag = ber_scanf( ber, "m", &dn );
3613 if ( tag == LBER_ERROR ) {
3614 Debug( LDAP_DEBUG_TRACE,
3615 "pcache_parse_query_delete: DN parse failed.\n",
3617 goto decoding_error;
3620 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3621 if ( rc != LDAP_SUCCESS ) {
3622 *text = "invalid DN in queryDelete exop request data";
3627 tag = ber_scanf( ber, "x" /* "m" */ );
3628 if ( tag == LBER_DEFAULT ) {
3629 goto decoding_error;
3633 tag = ber_peek_tag( ber, &len );
3636 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3637 if ( uuid != NULL ) {
3639 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3641 tag = ber_scanf( ber, "m", &bv );
3642 if ( tag == LBER_ERROR ) {
3643 Debug( LDAP_DEBUG_TRACE,
3644 "pcache_parse_query_delete: UUID parse failed.\n",
3646 goto decoding_error;
3649 if ( bv.bv_len != 16 ) {
3650 Debug( LDAP_DEBUG_TRACE,
3651 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3652 (unsigned long)bv.bv_len, 0, 0 );
3653 goto decoding_error;
3656 rc = lutil_uuidstr_from_normalized(
3657 bv.bv_val, bv.bv_len,
3658 uuidbuf, sizeof( uuidbuf ) );
3660 goto decoding_error;
3662 ber_str2bv( uuidbuf, rc, 1, uuid );
3666 tag = ber_skip_tag( ber, &len );
3667 if ( tag == LBER_DEFAULT ) {
3668 goto decoding_error;
3672 Debug( LDAP_DEBUG_TRACE,
3673 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3674 (unsigned long)len, 0, 0 );
3675 goto decoding_error;
3679 tag = ber_peek_tag( ber, &len );
3682 if ( tag != LBER_DEFAULT || len != 0 ) {
3684 Debug( LDAP_DEBUG_TRACE,
3685 "pcache_parse_query_delete: decoding error\n",
3687 rc = LDAP_PROTOCOL_ERROR;
3688 *text = "queryDelete data decoding error";
3691 if ( ndn && !BER_BVISNULL( ndn ) ) {
3692 slap_sl_free( ndn->bv_val, ctx );
3696 if ( uuid && !BER_BVISNULL( uuid ) ) {
3697 slap_sl_free( uuid->bv_val, ctx );
3702 if ( !BER_BVISNULL( &reqdata ) ) {
3703 ber_memfree_x( reqdata.bv_val, ctx );
3710 pcache_exop_query_delete(
3714 BackendDB *bd = op->o_bd;
3716 struct berval uuid = BER_BVNULL,
3718 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3720 ber_tag_t tag = LBER_DEFAULT;
3722 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3726 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3727 &tag, &op->o_req_ndn, uuidp,
3728 &rs->sr_text, op->o_tmpmemctx );
3729 if ( rs->sr_err != LDAP_SUCCESS ) {
3733 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3734 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3735 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3737 if ( !BER_BVISNULL( &uuid ) ) {
3738 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3741 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3742 op->o_log_prefix, buf, 0 );
3744 op->o_req_dn = op->o_req_ndn;
3746 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3747 rs->sr_err = backend_check_restrictions( op, rs,
3748 (struct berval *)&pcache_exop_QUERY_DELETE );
3749 if ( rs->sr_err != LDAP_SUCCESS ) {
3753 if ( op->o_bd->be_extended == NULL ) {
3754 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3755 "backend does not support extended operations" );
3759 op->o_bd->be_extended( op, rs );
3762 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3763 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3764 BER_BVZERO( &op->o_req_ndn );
3765 BER_BVZERO( &op->o_req_dn );
3768 if ( !BER_BVISNULL( &uuid ) ) {
3769 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3778 pcache_op_extended( Operation *op, SlapReply *rs )
3780 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3781 cache_manager *cm = on->on_bi.bi_private;
3783 #ifdef PCACHE_CONTROL_PRIVDB
3784 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3785 return pcache_op_privdb( op, rs );
3787 #endif /* PCACHE_CONTROL_PRIVDB */
3789 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3790 struct berval uuid = BER_BVNULL;
3791 ber_tag_t tag = LBER_DEFAULT;
3793 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3794 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3795 assert( rs->sr_err == LDAP_SUCCESS );
3797 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3798 /* remove all queries related to the selected entry */
3799 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3800 cm, &op->o_req_ndn, &uuid );
3802 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3803 if ( !BER_BVISNULL( &uuid ) ) {
3804 /* remove the selected query */
3805 rs->sr_err = pcache_remove_query_from_cache( op,
3809 /* TODO: remove all queries */
3810 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3811 rs->sr_text = "deletion of all queries not implemented";
3815 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3820 #endif /* PCACHE_EXOP_QUERY_DELETE */
3822 static slap_overinst pcache;
3824 static char *obsolete_names[] = {
3829 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3831 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3836 struct berval debugbv = BER_BVC("pcache");
3838 code = slap_loglevel_get( &debugbv, &pcache_debug );
3843 #ifdef PCACHE_CONTROL_PRIVDB
3844 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3845 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3846 parse_privdb_ctrl, &privDB_cid );
3847 if ( code != LDAP_SUCCESS ) {
3848 Debug( LDAP_DEBUG_ANY,
3849 "pcache_initialize: failed to register control %s (%d)\n",
3850 PCACHE_CONTROL_PRIVDB, code, 0 );
3853 #endif /* PCACHE_CONTROL_PRIVDB */
3855 #ifdef PCACHE_EXOP_QUERY_DELETE
3856 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3857 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3859 if ( code != LDAP_SUCCESS ) {
3860 Debug( LDAP_DEBUG_ANY,
3861 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3865 #endif /* PCACHE_EXOP_QUERY_DELETE */
3867 for ( i = 0; as[i].desc != NULL; i++ ) {
3868 code = register_at( as[i].desc, as[i].adp, 0 );
3870 Debug( LDAP_DEBUG_ANY,
3871 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3874 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3877 pcache.on_bi.bi_type = "pcache";
3878 pcache.on_bi.bi_obsolete_names = obsolete_names;
3879 pcache.on_bi.bi_db_init = pcache_db_init;
3880 pcache.on_bi.bi_db_config = pcache_db_config;
3881 pcache.on_bi.bi_db_open = pcache_db_open;
3882 pcache.on_bi.bi_db_close = pcache_db_close;
3883 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3885 pcache.on_bi.bi_op_search = pcache_op_search;
3886 #ifdef PCACHE_CONTROL_PRIVDB
3887 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3888 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3889 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3890 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3891 pcache.on_bi.bi_op_add = pcache_op_privdb;
3892 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3893 #endif /* PCACHE_CONTROL_PRIVDB */
3894 #ifdef PCACHE_EXOP_QUERY_DELETE
3895 pcache.on_bi.bi_extended = pcache_op_extended;
3896 #elif defined( PCACHE_CONTROL_PRIVDB )
3897 pcache.on_bi.bi_extended = pcache_op_privdb;
3900 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3902 pcache.on_bi.bi_cf_ocs = pcocs;
3904 code = config_register_schema( pccfg, pcocs );
3905 if ( code ) return code;
3907 return overlay_register( &pcache );
3910 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3911 int init_module(int argc, char *argv[]) {
3912 return pcache_initialize();
3916 #endif /* defined(SLAPD_OVER_PROXYCACHE) */