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 */
75 struct query_template_s *qtemp; /* template of the query */
76 time_t expiry_time; /* time till the query is considered valid */
77 struct cached_query_s *next; /* next query in the template */
78 struct cached_query_s *prev; /* previous query in the template */
79 struct cached_query_s *lru_up; /* previous query in the LRU list */
80 struct cached_query_s *lru_down; /* next query in the LRU list */
86 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
88 * <base> ::= CachedQuery.qbase->base
89 * <scope> ::= CachedQuery.scope
90 * <filter> ::= filter2bv(CachedQuery.filter)
91 * <uuid> ::= CachedQuery.q_uuid
92 * <template> ::= CachedQuery.qtemp->querystr [FIXME: better give it an ID?]
93 * <attrset> ::= CachedQuery.qtemp->attr_set_index [FIXME: better give it an ID?]
94 * <expiry> ::= CachedQuery.expiry_time
96 * quick hack: parse URI, call add_query() and then fix
97 * CachedQuery.expiry_time and CachedQuery.q_uuid
101 * Represents a set of projected attributes.
105 struct query_template_s *templates;
106 AttributeName* attrs; /* specifies the set */
108 #define PC_CONFIGURED (0x1)
109 #define PC_REFERENCED (0x2)
110 #define PC_GOT_OC (0x4)
111 int count; /* number of attributes */
114 /* struct representing a query template
115 * e.g. template string = &(cn=)(mail=)
117 typedef struct query_template_s {
118 struct query_template_s *qtnext;
119 struct query_template_s *qmnext;
122 CachedQuery* query; /* most recent query cached for the template */
123 CachedQuery* query_last; /* oldest query cached for the template */
124 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
125 struct berval querystr; /* Filter string corresponding to the QT */
127 int attr_set_index; /* determines the projected attributes */
128 int no_of_queries; /* Total number of queries in the template */
129 time_t ttl; /* TTL for the queries of this template */
130 time_t negttl; /* TTL for negative results */
131 struct attr_set t_attrs; /* filter attrs + attr_set */
134 struct query_manager_s;
136 /* prototypes for functions for 1) query containment
137 * 2) query addition, 3) cache replacement
139 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
140 typedef CachedQuery * (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
141 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
143 /* LDAP query cache */
144 typedef struct query_manager_s {
145 struct attr_set* attr_sets; /* possible sets of projected attributes */
146 QueryTemplate* templates; /* cacheable templates */
148 CachedQuery* lru_top; /* top and bottom of LRU list */
149 CachedQuery* lru_bottom;
151 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
153 /* Query cache methods */
154 QCfunc *qcfunc; /* Query containment*/
155 CRfunc *crfunc; /* cache replacement */
156 AddQueryfunc *addfunc; /* add query */
159 /* LDAP query cache manager */
160 typedef struct cache_manager_s {
161 BackendDB db; /* underlying database */
162 unsigned long num_cached_queries; /* total number of cached queries */
163 unsigned long max_queries; /* upper bound on # of cached queries */
164 int save_queries; /* save cached queries across restarts */
165 int numattrsets; /* number of attribute sets */
166 int cur_entries; /* current number of entries cached */
167 int max_entries; /* max number of entries cached */
168 int num_entries_limit; /* max # of entries in a cacheable query */
170 char response_cb; /* install the response callback
171 * at the tail of the callback list */
172 #define PCACHE_RESPONSE_CB_HEAD 0
173 #define PCACHE_RESPONSE_CB_TAIL 1
175 time_t cc_period; /* interval between successive consistency checks (sec) */
179 ldap_pvt_thread_mutex_t cache_mutex;
181 query_manager* qm; /* query cache managed by the cache manager */
184 static int pcache_debug;
186 #ifdef PCACHE_CONTROL_PRIVDB
187 static int privDB_cid;
188 #endif /* PCACHE_CONTROL_PRIVDB */
190 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
193 AttributeDescription **adp;
195 { "( 1.3.6.1.4.1.4203.666.11.9.1.1 NAME 'queryId' "
196 "DESC 'List of queries the entry belongs to' "
197 "EQUALITY octetStringMatch "
198 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
199 "NO-USER-MODIFICATION USAGE directoryOperation )",
201 { "( 1.3.6.1.4.1.4203.666.11.9.1.2 NAME 'cachedQueryURL' "
202 "DESC 'URI describing a cached query' "
203 "EQUALITY caseExactMatch "
204 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
205 "NO-USER-MODIFICATION USAGE directoryOperation )",
206 &ad_cachedQueryURL },
215 AttributeName** filter_attrs,
217 int* filter_got_oc );
224 QueryTemplate *templ,
231 struct berval *query_uuid );
234 * Turn a cached query into its URL representation
237 query2url( Operation *op, CachedQuery *q, struct berval *urlbv )
239 struct berval bv_scope,
241 char attrset_buf[ 32 ],
244 ber_len_t attrset_len,
247 ldap_pvt_scope2bv( q->scope, &bv_scope );
248 filter2bv_x( op, q->filter, &bv_filter );
249 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
250 "%lu", (unsigned long)q->qtemp->attr_set_index );
251 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
252 "%lu", (unsigned long)q->expiry_time );
254 urlbv->bv_len = STRLENOF( "ldap:///" )
255 + q->qbase->base.bv_len
260 + STRLENOF( "?x-uuid=" )
262 + STRLENOF( ",x-attrset=" )
264 + STRLENOF( ",x-expiry=" )
266 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
267 ptr = lutil_strcopy( ptr, "ldap:///" );
268 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
269 ptr = lutil_strcopy( ptr, "??" );
270 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
271 ptr = lutil_strcopy( ptr, "?" );
272 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
273 ptr = lutil_strcopy( ptr, "?x-uuid=" );
274 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
275 ptr = lutil_strcopy( ptr, ",x-attrset=" );
276 ptr = lutil_strcopy( ptr, attrset_buf );
277 ptr = lutil_strcopy( ptr, ",x-expiry=" );
278 ptr = lutil_strcopy( ptr, expiry_buf );
280 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
286 * Turn an URL representing a formerly cached query into a cached query,
287 * and try to cache it
298 LDAPURLDesc *lud = NULL;
300 tempstr = BER_BVNULL,
310 rc = ldap_url_parse( url, &lud );
311 if ( rc != LDAP_URL_SUCCESS ) {
315 /* non-allowed fields */
316 if ( lud->lud_host != NULL ) {
321 if ( lud->lud_attrs != NULL ) {
327 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
332 /* required fields */
333 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
338 switch ( lud->lud_scope ) {
339 case LDAP_SCOPE_BASE:
340 case LDAP_SCOPE_ONELEVEL:
341 case LDAP_SCOPE_SUBTREE:
342 case LDAP_SCOPE_SUBORDINATE:
350 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
355 if ( lud->lud_exts == NULL ) {
360 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
361 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
362 struct berval tmpUUID;
363 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
365 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
366 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
367 if ( rc != LDAP_SUCCESS ) {
372 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
373 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
379 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
382 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
386 expiry_time = (time_t)l;
400 if ( !got_attrset ) {
410 /* ignore expired queries */
411 if ( expiry_time <= slap_get_time()) {
413 SlapReply rs2 = { 0 };
415 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
417 (void)remove_query_data( &op2, &rs2, &uuid );
422 ber_str2bv( lud->lud_dn, 0, 0, &base );
423 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
424 if ( rc != LDAP_SUCCESS ) {
427 query.scope = lud->lud_scope;
428 query.filter = str2filter( lud->lud_filter );
430 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
432 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
433 ch_free( tempstr.bv_val );
438 /* check for query containment */
439 qt = qm->attr_sets[attrset].templates;
440 for ( ; qt; qt = qt->qtnext ) {
441 /* find if template i can potentially answer tempstr */
442 if ( bvmatch( &qt->querystr, &tempstr ) ) {
452 cq = add_query( op, qm, &query, qt, 1 );
454 cq->expiry_time = expiry_time;
457 /* it's now into cq->filter */
467 if ( query.filter != NULL ) filter_free( query.filter );
468 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
469 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
470 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
471 if ( lud != NULL ) ldap_free_urldesc( lud );
476 /* Return 1 for an added entry, else 0 */
481 struct berval* query_uuid )
484 Modifications* modlist = NULL;
485 const char* text = NULL;
487 char textbuf[SLAP_TEXT_BUFLEN];
488 size_t textlen = sizeof(textbuf);
490 SlapReply sreply = {REP_RESULT};
492 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
497 /* add queryId attribute */
498 attr_merge_one( e, ad_queryId, query_uuid, NULL );
500 /* append the attribute list from the fetched entry */
501 e->e_attrs->a_next = attr;
503 op->o_tag = LDAP_REQ_ADD;
504 op->o_protocol = LDAP_VERSION3;
505 op->o_callback = &cb;
506 op->o_time = slap_get_time();
507 op->o_do_not_cache = 1;
510 op->o_req_dn = e->e_name;
511 op->o_req_ndn = e->e_nname;
512 rc = op->o_bd->be_add( op, &sreply );
514 if ( rc != LDAP_SUCCESS ) {
515 if ( rc == LDAP_ALREADY_EXISTS ) {
516 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
517 modlist->sml_op = LDAP_MOD_ADD;
518 op->o_tag = LDAP_REQ_MODIFY;
519 op->orm_modlist = modlist;
520 op->o_bd->be_modify( op, &sreply );
521 slap_mods_free( modlist, 1 );
522 } else if ( rc == LDAP_REFERRAL ||
523 rc == LDAP_NO_SUCH_OBJECT ) {
524 syncrepl_add_glue( op, e );
533 if ( op->ora_e == e )
534 be_entry_release_w( op, e );
541 /* Length-ordered sort on normalized DNs */
542 static int pcache_dn_cmp( const void *v1, const void *v2 )
544 const Qbase *q1 = v1, *q2 = v2;
546 int rc = q1->base.bv_len - q2->base.bv_len;
548 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
552 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
555 dif = bv1->bv_len - bv2->bv_len;
557 if ( dif > 0 ) len -= dif;
558 len = memcmp( bv1->bv_val, bv2->bv_val, len );
564 /* compare the first value in each filter */
565 static int pcache_filter_cmp( const void *v1, const void *v2 )
567 const CachedQuery *q1 = v1, *q2 =v2;
568 int rc, weight1, weight2;
570 switch( q1->first->f_choice ) {
571 case LDAP_FILTER_PRESENT:
574 case LDAP_FILTER_EQUALITY:
582 switch( q2->first->f_choice ) {
583 case LDAP_FILTER_PRESENT:
586 case LDAP_FILTER_EQUALITY:
594 rc = weight1 - weight2;
599 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
602 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
604 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
605 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
606 rc = lex_bvcmp( &q1->first->f_sub_initial,
607 &q2->first->f_sub_initial );
611 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
615 if ( q1->first->f_sub_any ) {
616 if ( q2->first->f_sub_any ) {
617 rc = lex_bvcmp( q1->first->f_sub_any,
618 q2->first->f_sub_any );
622 } else if ( q2->first->f_sub_any ) {
626 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
627 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
628 rc = lex_bvcmp( &q1->first->f_sub_final,
629 &q2->first->f_sub_final );
633 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
637 rc = lex_bvcmp( &q1->first->f_mr_value,
638 &q2->first->f_mr_value );
647 /* add query on top of LRU list */
649 add_query_on_top (query_manager* qm, CachedQuery* qc)
651 CachedQuery* top = qm->lru_top;
662 Debug( pcache_debug, "Base of added query = %s\n",
663 qc->qbase->base.bv_val, 0, 0 );
666 /* remove_query from LRU list */
669 remove_query (query_manager* qm, CachedQuery* qc)
692 qc->lru_up = qc->lru_down = NULL;
695 /* find and remove string2 from string1
696 * from start if position = 1,
697 * from end if position = 3,
698 * from anywhere if position = 2
699 * string1 is overwritten if position = 2.
703 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
714 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
715 ber2->bv_val, ber2->bv_len )) {
717 ber1->bv_val += ber2->bv_len;
718 ber1->bv_len -= ber2->bv_len;
723 ber1->bv_val[ber1->bv_len] = '\0';
724 temp = strstr( ber1->bv_val, ber2->bv_val );
726 strcpy( temp, temp+ber2->bv_len );
727 ber1->bv_len -= ber2->bv_len;
733 if ( ber1->bv_len >= ber2->bv_len &&
734 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
737 ber1->bv_len -= ber2->bv_len;
745 static struct berval*
746 merge_init_final(Operation *op, struct berval* init, struct berval* any,
747 struct berval* final)
749 struct berval* merged, *temp;
750 int i, any_count, count;
752 for (any_count=0; any && any[any_count].bv_val; any_count++)
762 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
767 ber_dupbv_x( temp, init, op->o_tmpmemctx );
771 for (i=0; i<any_count; i++) {
772 ber_dupbv_x( temp, any, op->o_tmpmemctx );
777 ber_dupbv_x( temp, final, op->o_tmpmemctx );
784 /* Each element in stored must be found in incoming. Incoming is overwritten.
787 strings_containment(struct berval* stored, struct berval* incoming)
789 struct berval* element;
793 for ( element=stored; element->bv_val != NULL; element++ ) {
794 for (j = k; incoming[j].bv_val != NULL; j++) {
795 if (find_and_remove(&(incoming[j]), element, 2)) {
812 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
816 struct berval init_incoming;
817 struct berval final_incoming;
818 struct berval *remaining_incoming = NULL;
820 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
821 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
824 init_incoming = incoming->f_sub_initial;
825 final_incoming = incoming->f_sub_final;
827 if (find_and_remove(&init_incoming,
828 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
829 &(stored->f_sub_final), 3))
831 if (stored->f_sub_any == NULL) {
835 remaining_incoming = merge_init_final(op, &init_incoming,
836 incoming->f_sub_any, &final_incoming);
837 rc = strings_containment(stored->f_sub_any, remaining_incoming);
838 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
845 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
847 struct berval incoming_val[2];
850 incoming_val[1] = incoming->f_av_value;
852 if (find_and_remove(incoming_val+1,
853 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
854 &(stored->f_sub_final), 3)) {
855 if (stored->f_sub_any == NULL){
859 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
860 BER_BVZERO( incoming_val+1 );
861 rc = strings_containment(stored->f_sub_any, incoming_val);
862 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
869 filter_first( Filter *f )
871 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
878 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
882 MatchingRule* mrule = NULL;
883 int res=0, eqpass= 0;
891 /* substring matches sort to the end, and we just have to
892 * walk the entire list.
894 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
895 ptr = tavl_end( root, 1 );
898 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
899 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
908 /* an incoming substr query can only be satisfied by a cached
911 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
912 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
915 /* an incoming eq query can be satisfied by a cached eq or substr
918 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
920 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
921 nextpass: eqpass = 1;
922 ptr = tavl_end( root, 1 );
927 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
933 switch (fs->f_choice) {
934 case LDAP_FILTER_EQUALITY:
935 if (fi->f_choice == LDAP_FILTER_EQUALITY)
936 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
942 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
949 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
950 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
951 &(fi->f_ava->aa_value),
952 &(fs->f_ava->aa_value), &text);
953 if (rc != LDAP_SUCCESS) {
956 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
959 switch (fs->f_choice) {
961 case LDAP_FILTER_AND:
966 case LDAP_FILTER_SUBSTRINGS:
967 /* check if the equality query can be
968 * answered with cached substring query */
969 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
970 && substr_containment_equality( op,
973 /* check if the substring query can be
974 * answered with cached substring query */
975 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
976 ) && substr_containment_substr( op,
982 case LDAP_FILTER_PRESENT:
987 case LDAP_FILTER_EQUALITY:
994 if (mrule && ret >= 0)
1000 if (mrule && ret <= 0)
1005 case LDAP_FILTER_NOT:
1011 } while((res) && (fi != NULL) && (fs != NULL));
1015 ptr = tavl_next( ptr, dir );
1020 /* check whether query is contained in any of
1021 * the cached queries in template
1023 static CachedQuery *
1024 query_containment(Operation *op, query_manager *qm,
1026 QueryTemplate *templa)
1029 int depth = 0, tscope;
1030 Qbase qbase, *qbptr = NULL;
1033 if (query->filter != NULL) {
1036 Debug( pcache_debug, "Lock QC index = %p\n",
1037 (void *) templa, 0, 0 );
1038 qbase.base = query->base;
1040 first = filter_first( query->filter );
1042 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1045 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1047 tscope = query->scope;
1048 /* Find a matching scope:
1049 * match at depth 0 OK
1052 * subord at depth > 0 OK
1053 * subtree at any depth OK
1055 * subtree or subord at any depth OK
1057 * subtree or subord at any depth OK
1059 * subord at depth > 0 OK
1060 * subtree at any depth OK
1062 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1063 switch ( query->scope ) {
1064 case LDAP_SCOPE_BASE:
1065 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1066 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1067 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1069 case LDAP_SCOPE_ONE:
1070 if ( tscope == LDAP_SCOPE_BASE )
1071 tscope = LDAP_SCOPE_ONE;
1072 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1073 if ( !depth ) break;
1074 if ( tscope < LDAP_SCOPE_SUBTREE )
1075 tscope = LDAP_SCOPE_SUBTREE;
1077 case LDAP_SCOPE_SUBTREE:
1078 if ( tscope < LDAP_SCOPE_SUBTREE )
1079 tscope = LDAP_SCOPE_SUBTREE;
1080 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1082 case LDAP_SCOPE_CHILDREN:
1083 if ( tscope < LDAP_SCOPE_SUBTREE )
1084 tscope = LDAP_SCOPE_SUBTREE;
1087 if ( !qbptr->scopes[tscope] ) continue;
1090 qc = find_filter( op, qbptr->scopes[tscope],
1091 query->filter, first );
1093 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1094 if (qm->lru_top != qc) {
1095 remove_query(qm, qc);
1096 add_query_on_top(qm, qc);
1098 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1103 if ( be_issuffix( op->o_bd, &qbase.base ))
1106 dnParent( &qbase.base, &pdn );
1111 Debug( pcache_debug,
1112 "Not answerable: Unlock QC index=%p\n",
1113 (void *) templa, 0, 0 );
1114 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1120 free_query (CachedQuery* qc)
1122 free(qc->q_uuid.bv_val);
1123 filter_free(qc->filter);
1128 /* Add query to query cache */
1129 static CachedQuery *
1134 QueryTemplate *templ,
1137 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1142 new_cached_query->qtemp = templ;
1143 BER_BVZERO( &new_cached_query->q_uuid );
1145 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1147 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1149 new_cached_query->lru_up = NULL;
1150 new_cached_query->lru_down = NULL;
1151 Debug( pcache_debug, "Added query expires at %ld\n",
1152 (long) new_cached_query->expiry_time, 0, 0 );
1154 new_cached_query->scope = query->scope;
1155 new_cached_query->filter = query->filter;
1156 new_cached_query->first = first = filter_first( query->filter );
1158 qb.base = query->base;
1160 /* Adding a query */
1161 Debug( pcache_debug, "Lock AQ index = %p\n",
1162 (void *) templ, 0, 0 );
1163 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1164 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1166 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1167 qbase->base.bv_len = qb.base.bv_len;
1168 qbase->base.bv_val = (char *)(qbase+1);
1169 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1170 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1171 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1173 new_cached_query->next = templ->query;
1174 new_cached_query->prev = NULL;
1175 new_cached_query->qbase = qbase;
1176 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1177 pcache_filter_cmp, avl_dup_error );
1180 if (templ->query == NULL)
1181 templ->query_last = new_cached_query;
1183 templ->query->prev = new_cached_query;
1184 templ->query = new_cached_query;
1185 templ->no_of_queries++;
1187 ch_free( new_cached_query );
1188 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1189 query->filter, first );
1190 filter_free( query->filter );
1192 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1193 (void *) templ, templ->no_of_queries, 0 );
1195 Debug( pcache_debug, "Unlock AQ index = %p \n",
1196 (void *) templ, 0, 0 );
1197 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1199 /* Adding on top of LRU list */
1201 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1202 add_query_on_top(qm, new_cached_query);
1203 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1205 return rc == 0 ? new_cached_query : NULL;
1209 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1211 if (!qc->prev && !qc->next) {
1212 template->query_last = template->query = NULL;
1213 } else if (qc->prev == NULL) {
1214 qc->next->prev = NULL;
1215 template->query = qc->next;
1216 } else if (qc->next == NULL) {
1217 qc->prev->next = NULL;
1218 template->query_last = qc->prev;
1220 qc->next->prev = qc->prev;
1221 qc->prev->next = qc->next;
1223 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1224 qc->qbase->queries--;
1225 if ( qc->qbase->queries == 0 ) {
1226 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1227 ch_free( qc->qbase );
1231 template->no_of_queries--;
1234 /* remove bottom query of LRU list from the query cache */
1236 * NOTE: slight change in functionality.
1238 * - if result->bv_val is NULL, the query at the bottom of the LRU
1240 * - otherwise, the query whose UUID is *result is removed
1241 * - if not found, result->bv_val is zeroed
1244 cache_replacement(query_manager* qm, struct berval *result)
1246 CachedQuery* bottom;
1247 QueryTemplate *temp;
1249 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1250 if ( BER_BVISNULL( result ) ) {
1251 bottom = qm->lru_bottom;
1254 Debug ( pcache_debug,
1255 "Cache replacement invoked without "
1256 "any query in LRU list\n", 0, 0, 0 );
1257 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1262 for ( bottom = qm->lru_bottom;
1264 bottom = bottom->lru_up )
1266 if ( bvmatch( result, &bottom->q_uuid ) ) {
1272 Debug ( pcache_debug,
1273 "Could not find query with uuid=\"%s\""
1274 "in LRU list\n", result->bv_val, 0, 0 );
1275 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1276 BER_BVZERO( result );
1281 temp = bottom->qtemp;
1282 remove_query(qm, bottom);
1283 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1285 *result = bottom->q_uuid;
1286 bottom->q_uuid.bv_val = NULL;
1288 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1289 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1290 remove_from_template(bottom, temp);
1291 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1292 (void *) temp, temp->no_of_queries, 0 );
1293 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1294 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1299 struct query_info *next;
1311 struct query_info *qi;
1314 if ( rs->sr_type != REP_SEARCH ) return 0;
1316 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1317 if ( attr == NULL ) return 0;
1319 for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1321 assert( count > 0 );
1322 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1323 qi->next = op->o_callback->sc_private;
1324 op->o_callback->sc_private = qi;
1325 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1326 qi->del = ( count == 1 );
1335 struct berval *query_uuid )
1337 struct query_info *qi, *qnext;
1338 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1339 #ifdef LDAP_COMP_MATCH
1340 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1342 AttributeAssertion ava = { NULL, BER_BVNULL };
1344 Filter filter = {LDAP_FILTER_EQUALITY};
1345 SlapReply sreply = {REP_RESULT};
1346 slap_callback cb = { NULL, remove_func, NULL, NULL };
1349 sreply.sr_entry = NULL;
1350 sreply.sr_nentries = 0;
1351 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1352 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1353 filter.f_ava = &ava;
1354 filter.f_av_desc = ad_queryId;
1355 filter.f_av_value = *query_uuid;
1357 op->o_tag = LDAP_REQ_SEARCH;
1358 op->o_protocol = LDAP_VERSION3;
1359 op->o_callback = &cb;
1360 op->o_time = slap_get_time();
1361 op->o_do_not_cache = 1;
1363 op->o_req_dn = op->o_bd->be_suffix[0];
1364 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1365 op->ors_scope = LDAP_SCOPE_SUBTREE;
1366 op->ors_deref = LDAP_DEREF_NEVER;
1367 op->ors_slimit = SLAP_NO_LIMIT;
1368 op->ors_tlimit = SLAP_NO_LIMIT;
1369 op->ors_filter = &filter;
1370 op->ors_filterstr.bv_val = filter_str;
1371 op->ors_filterstr.bv_len = strlen(filter_str);
1372 op->ors_attrs = NULL;
1373 op->ors_attrsonly = 0;
1375 op->o_bd->be_search( op, &sreply );
1377 for ( qi=cb.sc_private; qi; qi=qnext ) {
1380 op->o_req_dn = qi->xdn;
1381 op->o_req_ndn = qi->xdn;
1384 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1385 query_uuid->bv_val, 0, 0 );
1387 op->o_tag = LDAP_REQ_DELETE;
1389 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1395 struct berval vals[2];
1397 vals[0] = *query_uuid;
1398 vals[1].bv_val = NULL;
1400 mod.sml_op = LDAP_MOD_DELETE;
1402 mod.sml_desc = ad_queryId;
1403 mod.sml_type = ad_queryId->ad_cname;
1404 mod.sml_values = vals;
1405 mod.sml_nvalues = NULL;
1406 mod.sml_next = NULL;
1407 Debug( pcache_debug,
1408 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1409 query_uuid->bv_val, 0, 0 );
1411 op->orm_modlist = &mod;
1413 op->o_bd->be_modify( op, &sreply );
1415 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1416 op->o_tmpfree( qi, op->o_tmpmemctx );
1423 AttributeName* attrs,
1432 struct berval *fstr,
1433 AttributeName** filter_attrs,
1435 int* filter_got_oc )
1437 AttributeDescription *ad;
1439 switch ( f->f_choice ) {
1440 case LDAP_FILTER_EQUALITY:
1442 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1443 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1446 case LDAP_FILTER_GE:
1448 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1449 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1452 case LDAP_FILTER_LE:
1454 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1455 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1458 case LDAP_FILTER_APPROX:
1460 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1461 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1464 case LDAP_FILTER_SUBSTRINGS:
1466 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1467 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1470 case LDAP_FILTER_PRESENT:
1472 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1473 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1476 case LDAP_FILTER_AND:
1477 case LDAP_FILTER_OR:
1478 case LDAP_FILTER_NOT: {
1480 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1481 f->f_choice == LDAP_FILTER_AND ? '&' :
1482 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1483 fstr->bv_len += sizeof("(%") - 1;
1485 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1486 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1490 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1491 fstr->bv_len += sizeof(")") - 1;
1497 strcpy( fstr->bv_val, "(?=?)" );
1498 fstr->bv_len += sizeof("(?=?)")-1;
1502 if ( filter_attrs != NULL ) {
1503 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1504 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1506 (*filter_attrs)[*filter_cnt].an_desc = ad;
1507 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1508 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1509 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1510 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1512 if ( ad == slap_schema.si_ad_objectClass )
1519 struct search_info {
1522 QueryTemplate *qtemp;
1523 AttributeName* save_attrs; /* original attributes, saved for response */
1531 remove_query_and_data(
1535 struct berval *uuid )
1537 query_manager* qm = cm->qm;
1539 qm->crfunc( qm, uuid );
1540 if ( !BER_BVISNULL( uuid ) ) {
1543 Debug( pcache_debug,
1544 "Removing query UUID %s\n",
1545 uuid->bv_val, 0, 0 );
1546 return_val = remove_query_data( op, rs, uuid );
1547 Debug( pcache_debug,
1548 "QUERY REMOVED, SIZE=%d\n",
1550 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1551 cm->cur_entries -= return_val;
1552 cm->num_cached_queries--;
1553 Debug( pcache_debug,
1554 "STORED QUERIES = %lu\n",
1555 cm->num_cached_queries, 0, 0 );
1556 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1557 Debug( pcache_debug,
1558 "QUERY REMOVED, CACHE ="
1560 cm->cur_entries, 0, 0 );
1565 * Callback used to fetch queryId values based on entryUUID;
1566 * used by pcache_remove_entries_from_cache()
1569 fetch_queryId_cb( Operation *op, SlapReply *rs )
1573 /* only care about searchEntry responses */
1574 if ( rs->sr_type != REP_SEARCH ) {
1578 /* allow only one response per entryUUID */
1579 if ( op->o_callback->sc_private != NULL ) {
1585 /* copy all queryId values into callback's private data */
1586 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1588 BerVarray vals = NULL;
1590 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1591 op->o_callback->sc_private = (void *)vals;
1595 /* clear entry if required */
1596 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1597 entry_free( rs->sr_entry );
1598 rs->sr_entry = NULL;
1599 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1606 * Call that allows to remove a set of entries from the cache,
1607 * by forcing the removal of all the related queries.
1610 pcache_remove_entries_from_cache(
1615 Connection conn = { 0 };
1616 OperationBuffer opbuf;
1618 slap_callback sc = { 0 };
1619 SlapReply rs = { REP_RESULT };
1621 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1622 #ifdef LDAP_COMP_MATCH
1623 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1625 AttributeAssertion ava = { NULL, BER_BVNULL };
1627 AttributeName attrs[ 2 ] = { 0 };
1631 void *thrctx = ldap_pvt_thread_pool_context();
1633 connection_fake_init( &conn, &opbuf, thrctx );
1641 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1642 op->ors_scope = LDAP_SCOPE_SUBTREE;
1643 op->ors_deref = LDAP_DEREF_NEVER;
1644 f.f_choice = LDAP_FILTER_EQUALITY;
1646 ava.aa_desc = slap_schema.si_ad_entryUUID;
1647 op->ors_filter = &f;
1649 op->ors_tlimit = SLAP_NO_LIMIT;
1650 attrs[ 0 ].an_desc = ad_queryId;
1651 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1652 op->ors_attrs = attrs;
1653 op->ors_attrsonly = 0;
1655 op->o_req_dn = cm->db.be_suffix[ 0 ];
1656 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1658 op->o_tag = LDAP_REQ_SEARCH;
1659 op->o_protocol = LDAP_VERSION3;
1660 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1662 op->o_dn = op->o_bd->be_rootdn;
1663 op->o_ndn = op->o_bd->be_rootndn;
1664 sc.sc_response = fetch_queryId_cb;
1665 op->o_callback = ≻
1667 for ( s = 0; !BER_BVISNULL( &UUIDs[ s ] ); s++ ) {
1668 BerVarray vals = NULL;
1670 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1671 "(entryUUID=%s)", UUIDs[ s ].bv_val );
1672 op->ors_filterstr.bv_val = filtbuf;
1673 ava.aa_value = UUIDs[ s ];
1675 rc = op->o_bd->be_search( op, &rs );
1676 if ( rc != LDAP_SUCCESS ) {
1680 vals = (BerVarray)op->o_callback->sc_private;
1681 if ( vals != NULL ) {
1684 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1685 struct berval val = vals[ i ];
1687 remove_query_and_data( op, &rs, cm, &val );
1689 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1690 ch_free( val.bv_val );
1694 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1695 op->o_callback->sc_private = NULL;
1703 * Call that allows to remove a set of queries from the cache
1706 pcache_remove_entry_queries_from_cache(
1710 struct berval *uuid )
1712 Connection conn = { 0 };
1713 OperationBuffer opbuf;
1715 slap_callback sc = { 0 };
1716 SlapReply rs = { REP_RESULT };
1718 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1719 #ifdef LDAP_COMP_MATCH
1720 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1722 AttributeAssertion ava = { NULL, BER_BVNULL };
1724 AttributeName attrs[ 2 ] = { 0 };
1727 BerVarray vals = NULL;
1730 void *thrctx = ldap_pvt_thread_pool_context();
1732 connection_fake_init( &conn, &opbuf, thrctx );
1740 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1741 op->ors_scope = LDAP_SCOPE_BASE;
1742 op->ors_deref = LDAP_DEREF_NEVER;
1743 if ( uuid == NULL || BER_BVISNULL( uuid ) ) {
1744 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1745 f.f_choice = LDAP_FILTER_PRESENT;
1746 f.f_desc = slap_schema.si_ad_objectClass;
1749 op->ors_filterstr.bv_len = snprintf( filter_str,
1750 sizeof( filter_str ), "(%s=%s)",
1751 ad_queryId->ad_cname.bv_val, uuid->bv_val );
1752 f.f_choice = LDAP_FILTER_EQUALITY;
1754 f.f_av_desc = ad_queryId;
1755 f.f_av_value = *uuid;
1757 op->ors_filter = &f;
1759 op->ors_tlimit = SLAP_NO_LIMIT;
1760 attrs[ 0 ].an_desc = ad_queryId;
1761 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1762 op->ors_attrs = attrs;
1763 op->ors_attrsonly = 0;
1765 op->o_req_dn = *ndn;
1766 op->o_req_ndn = *ndn;
1768 op->o_tag = LDAP_REQ_SEARCH;
1769 op->o_protocol = LDAP_VERSION3;
1770 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1772 op->o_dn = op->o_bd->be_rootdn;
1773 op->o_ndn = op->o_bd->be_rootndn;
1774 sc.sc_response = fetch_queryId_cb;
1775 op->o_callback = ≻
1777 rc = op->o_bd->be_search( op, &rs );
1778 if ( rc != LDAP_SUCCESS ) {
1782 vals = (BerVarray)op->o_callback->sc_private;
1783 if ( vals != NULL ) {
1786 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1787 struct berval val = vals[ i ];
1789 remove_query_and_data( op, &rs, cm, &val );
1791 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1792 ch_free( val.bv_val );
1796 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1799 return LDAP_SUCCESS;
1806 struct berval *query_uuid )
1808 struct search_info *si = op->o_callback->sc_private;
1809 slap_overinst *on = si->on;
1810 cache_manager *cm = on->on_bi.bi_private;
1813 struct berval crp_uuid;
1814 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1815 Operation op_tmp = *op;
1817 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1818 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1820 op_tmp.o_bd = &cm->db;
1821 op_tmp.o_dn = cm->db.be_rootdn;
1822 op_tmp.o_ndn = cm->db.be_rootndn;
1824 Debug( pcache_debug, "UUID for query being added = %s\n",
1827 for ( e=si->head; e; e=si->head ) {
1828 si->head = e->e_private;
1829 e->e_private = NULL;
1830 while ( cm->cur_entries > (cm->max_entries) ) {
1831 BER_BVZERO( &crp_uuid );
1832 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1835 return_val = merge_entry(&op_tmp, e, query_uuid);
1836 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1837 cm->cur_entries += return_val;
1838 Debug( pcache_debug,
1839 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1840 cm->cur_entries, 0, 0 );
1842 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1849 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1850 slap_callback *cb = op->o_callback;
1851 struct search_info *si = cb->sc_private;
1852 if ( si->save_attrs != NULL ) {
1853 rs->sr_attrs = si->save_attrs;
1854 op->ors_attrs = si->save_attrs;
1856 op->o_callback = op->o_callback->sc_next;
1857 op->o_tmpfree( cb, op->o_tmpmemctx );
1858 return SLAP_CB_CONTINUE;
1866 struct search_info *si = op->o_callback->sc_private;
1867 slap_overinst *on = si->on;
1868 cache_manager *cm = on->on_bi.bi_private;
1869 query_manager* qm = cm->qm;
1871 if ( si->save_attrs != NULL ) {
1872 rs->sr_attrs = si->save_attrs;
1873 op->ors_attrs = si->save_attrs;
1876 if ( rs->sr_type == REP_SEARCH ) {
1878 /* If we haven't exceeded the limit for this query,
1879 * build a chain of answers to store. If we hit the
1880 * limit, empty the chain and ignore the rest.
1883 if ( si->count < si->max ) {
1885 e = entry_dup( rs->sr_entry );
1886 if ( !si->head ) si->head = e;
1887 if ( si->tail ) si->tail->e_private = e;
1892 for (;si->head; si->head=e) {
1893 e = si->head->e_private;
1894 si->head->e_private = NULL;
1895 entry_free(si->head);
1901 } else if ( rs->sr_type == REP_RESULT ) {
1903 ( si->qtemp->negttl && !si->count && !si->over &&
1904 rs->sr_err == LDAP_SUCCESS )) {
1905 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1910 cache_entries( op, rs, &qc->q_uuid );
1911 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1912 cm->num_cached_queries++;
1913 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1914 cm->num_cached_queries, 0, 0 );
1915 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1917 /* If the consistency checker suspended itself,
1920 if ( cm->cc_paused ) {
1921 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1922 if ( cm->cc_paused ) {
1924 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1926 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1928 } else if ( si->count ) {
1929 /* duplicate query, free it */
1931 for (;si->head; si->head=e) {
1932 e = si->head->e_private;
1933 si->head->e_private = NULL;
1934 entry_free(si->head);
1938 filter_free( si->query.filter );
1941 op->o_callback->sc_cleanup = pcache_op_cleanup;
1943 return SLAP_CB_CONTINUE;
1949 AttributeName** new_attrs,
1950 struct attr_set *attrs,
1951 AttributeName* filter_attrs,
1961 /* duplicate attrs */
1962 count = attrs->count + fattr_cnt;
1963 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1968 *new_attrs = (AttributeName*)ch_calloc( count + 1,
1969 sizeof(AttributeName) );
1970 for (i=0; i<attrs->count; i++) {
1971 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1972 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1974 BER_BVZERO( &(*new_attrs)[i].an_name );
1975 alluser = an_find(*new_attrs, &AllUser);
1976 allop = an_find(*new_attrs, &AllOper);
1979 for ( i=0; i<fattr_cnt; i++ ) {
1980 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
1983 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1987 } else if ( alluser ) {
1990 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1991 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1992 (*new_attrs)[j].an_oc = NULL;
1993 (*new_attrs)[j].an_oc_exclude = 0;
1997 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1998 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1999 (*new_attrs)[j].an_oc = NULL;
2000 (*new_attrs)[j].an_oc_exclude = 0;
2003 BER_BVZERO( &(*new_attrs)[j].an_name );
2008 /* NOTE: this is a quick workaround to let pcache minimally interact
2009 * with pagedResults. A more articulated solutions would be to
2010 * perform the remote query without control and cache all results,
2011 * performing the pagedResults search only within the client
2012 * and the proxy. This requires pcache to understand pagedResults. */
2014 pcache_chk_controls(
2018 const char *non = "";
2019 const char *stripped = "";
2021 switch( op->o_pagedresults ) {
2022 case SLAP_CONTROL_NONCRITICAL:
2024 stripped = "; stripped";
2027 case SLAP_CONTROL_CRITICAL:
2028 Debug( pcache_debug, "%s: "
2029 "%scritical pagedResults control "
2030 "disabled with proxy cache%s.\n",
2031 op->o_log_prefix, non, stripped );
2033 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2037 rs->sr_err = SLAP_CB_CONTINUE;
2044 #ifdef PCACHE_CONTROL_PRIVDB
2050 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2051 cache_manager *cm = on->on_bi.bi_private;
2052 slap_callback *save_cb;
2055 /* skip if control is unset */
2056 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2057 return SLAP_CB_CONTINUE;
2060 /* FIXME: might be a little bit exaggerated... */
2061 if ( !be_isroot( op ) ) {
2062 save_cb = op->o_callback;
2063 op->o_callback = NULL;
2064 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2065 "pcachePrivDB: operation not allowed" );
2066 op->o_callback = save_cb;
2071 /* map tag to operation */
2072 type = slap_req2op( op->o_tag );
2073 if ( type != SLAP_OP_LAST ) {
2076 /* execute, if possible */
2077 func = &cm->db.be_bind;
2078 if ( func[ type ] != NULL ) {
2079 Operation op2 = *op;
2083 return func[ type ]( &op2, rs );
2087 /* otherwise fall back to error */
2088 save_cb = op->o_callback;
2089 op->o_callback = NULL;
2090 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2091 "operation not supported with pcachePrivDB control" );
2092 op->o_callback = save_cb;
2096 #endif /* PCACHE_CONTROL_PRIVDB */
2103 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2104 cache_manager *cm = on->on_bi.bi_private;
2105 query_manager* qm = cm->qm;
2109 AttributeName *filter_attrs = NULL;
2112 QueryTemplate *qtemp = NULL;
2115 CachedQuery *answerable = NULL;
2118 int fattr_got_oc = 0;
2120 struct berval tempstr;
2122 #ifdef PCACHE_CONTROL_PRIVDB
2123 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2124 return pcache_op_privdb( op, rs );
2126 #endif /* PCACHE_CONTROL_PRIVDB */
2128 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2130 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2131 &fattr_cnt, &fattr_got_oc )) {
2132 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2133 return SLAP_CB_CONTINUE;
2136 Debug( pcache_debug, "query template of incoming query = %s\n",
2137 tempstr.bv_val, 0, 0 );
2139 /* FIXME: cannot cache/answer requests with pagedResults control */
2142 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2144 query.filter = op->ors_filter;
2145 query.base = op->o_req_ndn;
2146 query.scope = op->ors_scope;
2148 /* check for query containment */
2149 if (attr_set > -1) {
2150 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2151 for (; qt; qt = qt->qtnext ) {
2152 /* find if template i can potentially answer tempstr */
2153 if (qt->querystr.bv_len != tempstr.bv_len ||
2154 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2158 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2159 op->ors_filterstr.bv_val, 0, 0 );
2160 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2166 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2169 /* Need to clear the callbacks of the original operation,
2170 * in case there are other overlays */
2171 BackendDB *save_bd = op->o_bd;
2172 slap_callback *save_cb = op->o_callback;
2174 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2175 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2176 if ( BER_BVISNULL( &answerable->q_uuid )) {
2177 /* No entries cached, just an empty result set */
2179 send_ldap_result( op, rs );
2182 op->o_callback = NULL;
2183 i = cm->db.bd_info->bi_op_search( op, rs );
2185 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2187 op->o_callback = save_cb;
2191 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2193 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2194 if (cm->num_cached_queries >= cm->max_queries) {
2197 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2199 if (op->ors_attrsonly)
2204 struct search_info *si;
2206 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2207 query.filter = filter_dup(op->ors_filter, NULL);
2208 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2209 if ( !qtemp->t_attrs.count ) {
2210 qtemp->t_attrs.count = add_filter_attrs(op,
2211 &qtemp->t_attrs.attrs,
2212 &qm->attr_sets[attr_set],
2213 filter_attrs, fattr_cnt, fattr_got_oc);
2215 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2217 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2218 cb->sc_response = pcache_response;
2219 cb->sc_cleanup = NULL;
2220 cb->sc_private = (cb+1);
2221 si = cb->sc_private;
2225 si->max = cm->num_entries_limit ;
2230 si->save_attrs = op->ors_attrs;
2232 op->ors_attrs = qtemp->t_attrs.attrs;
2234 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2235 cb->sc_next = op->o_callback;
2236 op->o_callback = cb;
2239 slap_callback **pcb;
2241 /* need to move the callback at the end, in case other
2242 * overlays are present, so that the final entry is
2243 * actually cached */
2245 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2250 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2254 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2256 return SLAP_CB_CONTINUE;
2261 AttributeName* attrs,
2269 for ( ; attrs[count].an_name.bv_val; count++ );
2272 /* recognize a single "*" or a "1.1" */
2275 attrs = slap_anlist_all_user_attributes;
2277 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2282 for ( i = 0; i < num; i++ ) {
2286 if ( count > qm->attr_sets[i].count ) {
2291 if ( !qm->attr_sets[i].count ) {
2297 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2298 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2321 struct re_s *rtask = arg;
2322 slap_overinst *on = rtask->arg;
2323 cache_manager *cm = on->on_bi.bi_private;
2324 query_manager *qm = cm->qm;
2325 Connection conn = {0};
2326 OperationBuffer opbuf;
2329 SlapReply rs = {REP_RESULT};
2331 int return_val, pause = 1;
2332 QueryTemplate* templ;
2334 connection_fake_init( &conn, &opbuf, ctx );
2338 op->o_dn = cm->db.be_rootdn;
2339 op->o_ndn = cm->db.be_rootndn;
2343 for (templ = qm->templates; templ; templ=templ->qmnext) {
2344 query = templ->query_last;
2345 if ( query ) pause = 0;
2346 op->o_time = slap_get_time();
2347 while (query && (query->expiry_time < op->o_time)) {
2349 Debug( pcache_debug, "Lock CR index = %p\n",
2350 (void *) templ, 0, 0 );
2351 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2352 if ( query == templ->query_last ) {
2354 remove_from_template(query, templ);
2355 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2356 (void *) templ, templ->no_of_queries, 0 );
2357 Debug( pcache_debug, "Unlock CR index = %p\n",
2358 (void *) templ, 0, 0 );
2360 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2362 query = templ->query_last;
2365 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2366 remove_query(qm, query);
2367 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2368 if ( BER_BVISNULL( &query->q_uuid ))
2371 return_val = remove_query_data(op, &rs, &query->q_uuid);
2372 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2374 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2375 cm->cur_entries -= return_val;
2376 cm->num_cached_queries--;
2377 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2378 cm->num_cached_queries, 0, 0 );
2379 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2380 Debug( pcache_debug,
2381 "STALE QUERY REMOVED, CACHE ="
2383 cm->cur_entries, 0, 0 );
2385 query = templ->query_last;
2388 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2389 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2390 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2392 /* If there were no queries, defer processing for a while */
2393 cm->cc_paused = pause;
2394 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2396 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2401 #define MAX_ATTR_SETS 500
2411 static ConfigDriver pc_cf_gen;
2412 static ConfigLDAPadd pc_ldadd;
2413 static ConfigCfAdd pc_cfadd;
2415 static ConfigTable pccfg[] = {
2416 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2418 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2419 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2420 "DESC 'ProxyCache basic parameters' "
2421 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2422 { "proxyattrset", "index> <attributes...",
2423 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2424 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2425 "DESC 'A set of attributes to cache' "
2426 "SYNTAX OMsDirectoryString )", NULL, NULL },
2427 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2428 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2429 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2430 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2431 "SYNTAX OMsDirectoryString )", NULL, NULL },
2432 { "response-callback", "head|tail(default)",
2433 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2434 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2435 "DESC 'Response callback position in overlay stack' "
2436 "SYNTAX OMsDirectoryString )", NULL, NULL },
2437 { "proxyCacheQueries", "queries",
2438 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2439 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2440 "DESC 'Maximum number of queries to cache' "
2441 "SYNTAX OMsInteger )", NULL, NULL },
2442 { "proxySaveQueries", "TRUE|FALSE",
2443 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2444 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2445 "DESC 'Save cached queries for hot restart' "
2446 "SYNTAX OMsBoolean )", NULL, NULL },
2448 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2451 static ConfigOCs pcocs[] = {
2452 { "( OLcfgOvOc:2.1 "
2453 "NAME 'olcPcacheConfig' "
2454 "DESC 'ProxyCache configuration' "
2455 "SUP olcOverlayConfig "
2456 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2457 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2458 Cft_Overlay, pccfg, NULL, pc_cfadd },
2459 { "( OLcfgOvOc:2.2 "
2460 "NAME 'olcPcacheDatabase' "
2461 "DESC 'Cache database configuration' "
2462 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2467 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2472 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2473 p->ce_bi->bi_cf_ocs != pcocs )
2474 return LDAP_CONSTRAINT_VIOLATION;
2476 on = (slap_overinst *)p->ce_bi;
2477 cm = on->on_bi.bi_private;
2479 return LDAP_SUCCESS;
2483 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2485 CfEntryInfo *pe = p->e_private;
2486 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2487 cache_manager *cm = on->on_bi.bi_private;
2490 /* FIXME: should not hardcode "olcDatabase" here */
2491 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2492 bv.bv_val = ca->cr_msg;
2495 /* We can only create this entry if the database is table-driven
2497 if ( cm->db.bd_info->bi_cf_ocs )
2498 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2505 pc_cf_gen( ConfigArgs *c )
2507 slap_overinst *on = (slap_overinst *)c->bi;
2508 cache_manager* cm = on->on_bi.bi_private;
2509 query_manager* qm = cm->qm;
2510 QueryTemplate* temp;
2511 AttributeName* attr_name;
2512 AttributeName* attrarray;
2513 const char* text=NULL;
2518 if ( c->op == SLAP_CONFIG_EMIT ) {
2522 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2523 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2524 cm->num_entries_limit, cm->cc_period );
2525 bv.bv_val = c->cr_msg;
2526 value_add_one( &c->rvalue_vals, &bv );
2529 for (i=0; i<cm->numattrsets; i++) {
2530 if ( !qm->attr_sets[i].count ) continue;
2532 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2534 /* count the attr length */
2535 for ( attr_name = qm->attr_sets[i].attrs;
2536 attr_name->an_name.bv_val; attr_name++ )
2537 bv.bv_len += attr_name->an_name.bv_len + 1;
2539 bv.bv_val = ch_malloc( bv.bv_len+1 );
2540 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2541 for ( attr_name = qm->attr_sets[i].attrs;
2542 attr_name->an_name.bv_val; attr_name++ ) {
2544 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2546 ber_bvarray_add( &c->rvalue_vals, &bv );
2548 if ( !c->rvalue_vals )
2552 for (temp=qm->templates; temp; temp=temp->qmnext) {
2553 if ( temp->negttl ) {
2554 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2556 temp->attr_set_index,
2560 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2561 temp->attr_set_index,
2564 bv.bv_len += temp->querystr.bv_len + 2;
2565 bv.bv_val = ch_malloc( bv.bv_len+1 );
2568 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2570 strcpy( ptr, c->cr_msg );
2571 ber_bvarray_add( &c->rvalue_vals, &bv );
2573 if ( !c->rvalue_vals )
2577 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2578 BER_BVSTR( &bv, "head" );
2580 BER_BVSTR( &bv, "tail" );
2582 value_add_one( &c->rvalue_vals, &bv );
2585 c->value_int = cm->max_queries;
2589 } else if ( c->op == LDAP_MOD_DELETE ) {
2590 return 1; /* FIXME */
2602 if ( cm->numattrsets > 0 ) {
2603 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2604 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2608 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2609 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2611 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2614 if ( cm->numattrsets <= 0 ) {
2615 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2616 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2619 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2620 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2621 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2625 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2626 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2627 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2631 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2632 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2634 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2637 if ( cm->max_entries <= 0 ) {
2638 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2639 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2643 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2644 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2646 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2649 if ( cm->num_entries_limit <= 0 ) {
2650 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2651 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2654 if ( cm->num_entries_limit > cm->max_entries ) {
2655 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2656 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2660 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2661 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2663 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2666 cm->cc_period = (time_t)t;
2667 Debug( pcache_debug,
2668 "Total # of attribute sets to be cached = %d.\n",
2669 cm->numattrsets, 0, 0 );
2670 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2671 sizeof( struct attr_set ) );
2674 if ( cm->numattrsets == 0 ) {
2675 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2676 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2679 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2680 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2682 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2686 if ( num < 0 || num >= cm->numattrsets ) {
2687 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2688 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2689 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2692 qm->attr_sets[num].flags |= PC_CONFIGURED;
2693 if ( c->argc == 2 ) {
2695 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2696 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2697 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2700 } else if ( c->argc == 3 ) {
2701 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2702 qm->attr_sets[num].count = 1;
2703 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2704 sizeof( AttributeName ) );
2705 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2708 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2709 qm->attr_sets[num].count = 1;
2710 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2711 sizeof( AttributeName ) );
2712 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2715 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2718 /* else: fallthru */
2720 } else if ( c->argc == 4 ) {
2721 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2722 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2724 qm->attr_sets[num].count = 2;
2725 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2726 sizeof( AttributeName ) );
2727 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2728 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2731 /* else: fallthru */
2734 if ( c->argc > 2 ) {
2735 int all_user = 0, all_op = 0;
2737 qm->attr_sets[num].count = c->argc - 2;
2738 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2739 sizeof( AttributeName ) );
2740 attr_name = qm->attr_sets[num].attrs;
2741 for ( i = 2; i < c->argc; i++ ) {
2742 attr_name->an_desc = NULL;
2743 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2744 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2745 "invalid attr #%d \"%s\" in attrlist",
2746 i - 2, c->argv[i] );
2747 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2748 ch_free( qm->attr_sets[num].attrs );
2749 qm->attr_sets[num].attrs = NULL;
2750 qm->attr_sets[num].count = 0;
2753 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2755 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2756 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2758 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2760 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2761 strcpy( c->cr_msg, text );
2762 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2763 ch_free( qm->attr_sets[num].attrs );
2764 qm->attr_sets[num].attrs = NULL;
2765 qm->attr_sets[num].count = 0;
2768 attr_name->an_name = attr_name->an_desc->ad_cname;
2770 attr_name->an_oc = NULL;
2771 attr_name->an_oc_exclude = 0;
2772 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2773 qm->attr_sets[num].flags |= PC_GOT_OC;
2775 BER_BVZERO( &attr_name->an_name );
2778 /* warn if list contains both "*" and "+" */
2779 if ( i > 4 && all_user && all_op ) {
2780 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2781 "warning: attribute list contains \"*\" and \"+\"" );
2782 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2787 if ( cm->numattrsets == 0 ) {
2788 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2789 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2792 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2793 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2795 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2799 if ( i < 0 || i >= cm->numattrsets ||
2800 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2801 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2802 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2803 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2806 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2807 temp->qmnext = qm->templates;
2808 qm->templates = temp;
2809 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2810 temp->query = temp->query_last = NULL;
2811 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2812 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2814 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2817 temp->ttl = (time_t)t;
2818 if ( c->argc == 5 ) {
2819 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2820 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2821 "unable to parse template negttl=\"%s\"",
2823 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2826 temp->negttl = (time_t)t;
2831 temp->no_of_queries = 0;
2833 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2834 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2835 Debug( pcache_debug, " query template: %s\n",
2836 temp->querystr.bv_val, 0, 0 );
2837 temp->attr_set_index = i;
2838 qm->attr_sets[i].flags |= PC_REFERENCED;
2839 temp->qtnext = qm->attr_sets[i].templates;
2840 qm->attr_sets[i].templates = temp;
2841 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2842 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2843 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2844 Debug( pcache_debug, "\t%s\n",
2845 attrarray[i].an_name.bv_val, 0, 0 );
2849 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2850 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2852 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2853 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2856 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2857 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2862 if ( c->value_int <= 0 ) {
2863 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2864 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2867 cm->max_queries = c->value_int;
2882 slap_overinst *on = (slap_overinst *)be->bd_info;
2883 cache_manager* cm = on->on_bi.bi_private;
2885 /* Something for the cache database? */
2886 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2887 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2889 return SLAP_CONF_UNKNOWN;
2897 slap_overinst *on = (slap_overinst *)be->bd_info;
2901 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2902 on->on_bi.bi_private = cm;
2904 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2907 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2908 cm->db.be_private = NULL;
2909 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2911 cm->numattrsets = 0;
2912 cm->num_entries_limit = 5;
2913 cm->num_cached_queries = 0;
2914 cm->max_entries = 0;
2915 cm->cur_entries = 0;
2916 cm->max_queries = 10000;
2917 cm->save_queries = 0;
2918 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2919 cm->cc_period = 1000;
2922 qm->attr_sets = NULL;
2923 qm->templates = NULL;
2925 qm->lru_bottom = NULL;
2927 qm->qcfunc = query_containment;
2928 qm->crfunc = cache_replacement;
2929 qm->addfunc = add_query;
2930 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2932 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2937 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2939 assert( op->o_tag == LDAP_REQ_SEARCH );
2941 if ( rs->sr_type == REP_SEARCH ) {
2944 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2948 assert( a->a_nvals != NULL );
2950 valsp = op->o_callback->sc_private;
2951 assert( *valsp == NULL );
2953 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2965 slap_overinst *on = (slap_overinst *)be->bd_info;
2966 cache_manager *cm = on->on_bi.bi_private;
2967 query_manager* qm = cm->qm;
2968 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2970 /* check attr sets */
2971 for ( i = 0; i < cm->numattrsets; i++) {
2972 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2973 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2974 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2978 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2982 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2983 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2988 if ( ncf || rf || nrf ) {
2989 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2990 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2991 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2998 /* need to inherit something from the original database... */
2999 cm->db.be_def_limit = be->be_def_limit;
3000 cm->db.be_limits = be->be_limits;
3001 cm->db.be_acl = be->be_acl;
3002 cm->db.be_dfltaccess = be->be_dfltaccess;
3004 if ( SLAP_DBMONITORING( be ) ) {
3005 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3008 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3011 rc = backend_startup_one( &cm->db, NULL );
3013 /* There is no runqueue in TOOL mode */
3014 if ( slapMode & SLAP_SERVER_MODE ) {
3015 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3016 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3017 consistency_check, on,
3018 "pcache_consistency", be->be_suffix[0].bv_val );
3019 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3021 /* Cached database must have the rootdn */
3022 if ( BER_BVISNULL( &cm->db.be_rootndn )
3023 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3025 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3026 "underlying database of type \"%s\"\n"
3027 " serving naming context \"%s\"\n"
3028 " has no \"rootdn\", required by \"proxycache\".\n",
3029 on->on_info->oi_orig->bi_type,
3030 cm->db.be_suffix[0].bv_val, 0 );
3034 if ( cm->save_queries ) {
3035 void *thrctx = ldap_pvt_thread_pool_context();
3036 Connection conn = { 0 };
3037 OperationBuffer opbuf;
3039 slap_callback cb = { 0 };
3040 SlapReply rs = { 0 };
3041 BerVarray vals = NULL;
3043 AttributeName attrs[ 2 ] = { 0 };
3045 connection_fake_init( &conn, &opbuf, thrctx );
3050 op->o_tag = LDAP_REQ_SEARCH;
3051 op->o_protocol = LDAP_VERSION3;
3052 cb.sc_response = pcache_cachedquery_open_cb;
3053 cb.sc_private = &vals;
3054 op->o_callback = &cb;
3055 op->o_time = slap_get_time();
3056 op->o_do_not_cache = 1;
3057 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3059 op->o_dn = cm->db.be_rootdn;
3060 op->o_ndn = cm->db.be_rootndn;
3061 op->o_req_dn = cm->db.be_suffix[ 0 ];
3062 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3064 op->ors_scope = LDAP_SCOPE_BASE;
3065 op->ors_deref = LDAP_DEREF_NEVER;
3067 op->ors_tlimit = SLAP_NO_LIMIT;
3068 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3069 f.f_choice = LDAP_FILTER_PRESENT;
3070 f.f_desc = ad_cachedQueryURL;
3071 op->ors_filter = &f;
3072 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3073 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3074 op->ors_attrs = attrs;
3075 op->ors_attrsonly = 0;
3077 rc = op->o_bd->be_search( op, &rs );
3078 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3081 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3082 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3083 cm->num_cached_queries++;
3087 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3099 pcache_free_qbase( void *v )
3105 tavl_free( qb->scopes[i], NULL );
3115 slap_overinst *on = (slap_overinst *)be->bd_info;
3116 cache_manager *cm = on->on_bi.bi_private;
3117 query_manager *qm = cm->qm;
3121 if ( cm->save_queries ) {
3123 BerVarray vals = NULL;
3126 Connection conn = { 0 };
3127 OperationBuffer opbuf;
3129 slap_callback cb = { 0 };
3131 SlapReply rs = { REP_RESULT };
3132 Modifications mod = { 0 };
3134 thrctx = ldap_pvt_thread_pool_context();
3136 connection_fake_init( &conn, &opbuf, thrctx );
3139 if ( qm->templates != NULL ) {
3140 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3141 for ( qc = tm->query; qc; qc = qc->next ) {
3144 if ( query2url( op, qc, &bv ) == 0 ) {
3145 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3152 op->o_dn = cm->db.be_rootdn;
3153 op->o_ndn = cm->db.be_rootndn;
3155 op->o_tag = LDAP_REQ_MODIFY;
3156 op->o_protocol = LDAP_VERSION3;
3157 cb.sc_response = slap_null_cb;
3158 op->o_callback = &cb;
3159 op->o_time = slap_get_time();
3160 op->o_do_not_cache = 1;
3161 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3163 op->o_req_dn = op->o_bd->be_suffix[0];
3164 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3166 mod.sml_op = LDAP_MOD_REPLACE;
3168 mod.sml_desc = ad_cachedQueryURL;
3169 mod.sml_type = ad_cachedQueryURL->ad_cname;
3170 mod.sml_values = vals;
3171 mod.sml_nvalues = NULL;
3172 mod.sml_next = NULL;
3173 Debug( pcache_debug,
3174 "%sSETTING CACHED QUERY URLS\n",
3175 vals == NULL ? "RE" : "", 0, 0 );
3177 op->orm_modlist = &mod;
3179 op->o_bd->be_modify( op, &rs );
3181 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3184 /* cleanup stuff inherited from the original database... */
3185 cm->db.be_limits = NULL;
3186 cm->db.be_acl = NULL;
3188 /* stop the thread ... */
3190 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3191 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3192 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3194 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3195 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3198 if ( cm->db.bd_info->bi_db_close ) {
3199 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3201 while ( (tm = qm->templates) != NULL ) {
3202 CachedQuery *qc, *qn;
3203 qm->templates = tm->qmnext;
3204 for ( qc = tm->query; qc; qc = qn ) {
3208 avl_free( tm->qbase, pcache_free_qbase );
3209 free( tm->querystr.bv_val );
3210 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3211 free( tm->t_attrs.attrs );
3215 for ( i=0; i<cm->numattrsets; i++ ) {
3216 free( qm->attr_sets[i].attrs );
3218 free( qm->attr_sets );
3219 qm->attr_sets = NULL;
3230 slap_overinst *on = (slap_overinst *)be->bd_info;
3231 cache_manager *cm = on->on_bi.bi_private;
3232 query_manager *qm = cm->qm;
3234 if ( cm->db.be_private != NULL ) {
3235 backend_stopdown_one( &cm->db );
3238 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3239 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3246 #ifdef PCACHE_CONTROL_PRIVDB
3248 Control ::= SEQUENCE {
3249 controlType LDAPOID,
3250 criticality BOOLEAN DEFAULT FALSE,
3251 controlValue OCTET STRING OPTIONAL }
3253 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3255 * criticality must be TRUE; controlValue must be absent.
3263 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3264 rs->sr_text = "privateDB control specified multiple times";
3265 return LDAP_PROTOCOL_ERROR;
3268 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3269 rs->sr_text = "privateDB control value not absent";
3270 return LDAP_PROTOCOL_ERROR;
3273 if ( !ctrl->ldctl_iscritical ) {
3274 rs->sr_text = "privateDB control criticality required";
3275 return LDAP_PROTOCOL_ERROR;
3278 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3280 return LDAP_SUCCESS;
3283 static char *extops[] = {
3284 LDAP_EXOP_MODIFY_PASSWD,
3287 #endif /* PCACHE_CONTROL_PRIVDB */
3289 #ifdef PCACHE_EXOP_QUERY_DELETE
3290 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3292 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3293 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3294 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3297 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3298 requestName [0] LDAPOID,
3299 requestValue [1] OCTET STRING OPTIONAL }
3301 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3303 requestValue ::= SEQUENCE { CHOICE {
3305 entryDN [1] LDAPDN },
3306 queryID [2] OCTET STRING (SIZE(16))
3307 -- constrained to UUID }
3309 * Either baseDN or entryDN must be present, to allow database selection.
3311 * 1. if baseDN and queryID are present, then the query corresponding
3312 * to queryID is deleted;
3313 * 2. if baseDN is present and queryID is absent, then all queries
3315 * 3. if entryDN is present and queryID is absent, then all queries
3316 * corresponding to the queryID values present in entryDN are deleted;
3317 * 4. if entryDN and queryID are present, then all queries
3318 * corresponding to the queryID values present in entryDN are deleted,
3319 * but only if the value of queryID is contained in the entry;
3321 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3322 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3323 * or by removing the database files.
3325 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3326 COMPONENTS OF LDAPResult,
3327 responseName [10] LDAPOID OPTIONAL,
3328 responseValue [11] OCTET STRING OPTIONAL }
3330 * responseName and responseValue must be absent.
3334 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3335 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3336 * - if ndn != NULL, it is set to the normalized DN in the request
3337 * corresponding to either the baseDN or the entryDN, according
3338 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3339 * be freed by the caller.
3340 * - if uuid != NULL, it is set to point to the normalized UUID;
3341 * memory is malloc'ed on the Operation's slab, and must
3342 * be freed by the caller.
3345 pcache_parse_query_delete(
3349 struct berval *uuid,
3353 int rc = LDAP_SUCCESS;
3356 BerElementBuffer berbuf;
3357 BerElement *ber = (BerElement *)&berbuf;
3358 struct berval reqdata = BER_BVNULL;
3370 if ( in == NULL || in->bv_len == 0 ) {
3371 *text = "empty request data field in queryDelete exop";
3372 return LDAP_PROTOCOL_ERROR;
3375 ber_dupbv_x( &reqdata, in, ctx );
3377 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3378 ber_init2( ber, &reqdata, 0 );
3380 tag = ber_scanf( ber, "{" /*}*/ );
3382 if ( tag == LBER_ERROR ) {
3383 Debug( LDAP_DEBUG_TRACE,
3384 "pcache_parse_query_delete: decoding error.\n",
3386 goto decoding_error;
3389 tag = ber_peek_tag( ber, &len );
3390 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3391 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3395 if ( ndn != NULL ) {
3398 tag = ber_scanf( ber, "m", &dn );
3399 if ( tag == LBER_ERROR ) {
3400 Debug( LDAP_DEBUG_TRACE,
3401 "pcache_parse_query_delete: DN parse failed.\n",
3403 goto decoding_error;
3406 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3407 if ( rc != LDAP_SUCCESS ) {
3408 *text = "invalid DN in queryDelete exop request data";
3413 tag = ber_scanf( ber, "x" /* "m" */ );
3414 if ( tag == LBER_DEFAULT ) {
3415 goto decoding_error;
3419 tag = ber_peek_tag( ber, &len );
3422 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3423 if ( uuid != NULL ) {
3425 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
3427 tag = ber_scanf( ber, "m", &bv );
3428 if ( tag == LBER_ERROR ) {
3429 Debug( LDAP_DEBUG_TRACE,
3430 "pcache_parse_query_delete: UUID parse failed.\n",
3432 goto decoding_error;
3435 if ( bv.bv_len != 16 ) {
3436 Debug( LDAP_DEBUG_TRACE,
3437 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3438 (unsigned long)bv.bv_len, 0, 0 );
3439 goto decoding_error;
3442 ber_dupbv_x( uuid, &bv, ctx );
3445 tag = ber_skip_tag( ber, &len );
3446 if ( tag == LBER_DEFAULT ) {
3447 goto decoding_error;
3451 Debug( LDAP_DEBUG_TRACE,
3452 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3453 (unsigned long)len, 0, 0 );
3454 goto decoding_error;
3458 tag = ber_peek_tag( ber, &len );
3461 if ( tag != LBER_DEFAULT || len != 0 ) {
3463 Debug( LDAP_DEBUG_TRACE,
3464 "pcache_parse_query_delete: decoding error\n",
3466 rc = LDAP_PROTOCOL_ERROR;
3467 *text = "queryDelete data decoding error";
3470 if ( ndn && !BER_BVISNULL( ndn ) ) {
3471 slap_sl_free( ndn->bv_val, ctx );
3475 if ( uuid && !BER_BVISNULL( uuid ) ) {
3476 slap_sl_free( uuid->bv_val, ctx );
3481 if ( !BER_BVISNULL( &reqdata ) ) {
3482 ber_memfree_x( reqdata.bv_val, ctx );
3489 pcache_exop_query_delete(
3493 BackendDB *bd = op->o_bd;
3495 struct berval uuid = BER_BVNULL;
3496 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3498 ber_tag_t tag = LBER_DEFAULT;
3500 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3501 &tag, &op->o_req_ndn, &uuid,
3502 &rs->sr_text, op->o_tmpmemctx );
3503 if ( rs->sr_err != LDAP_SUCCESS ) {
3507 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3508 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3509 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3512 if ( !BER_BVISNULL( &uuid ) ) {
3513 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3515 lutil_uuidstr_from_normalized(
3516 uuid.bv_val, uuid.bv_len,
3517 uuidbuf, sizeof( uuidbuf ) );
3519 snprintf( &buf[ len ], sizeof( buf ) - len, " UUID=\"%s\"", uuidbuf );
3522 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3523 op->o_log_prefix, buf, 0 );
3524 op->o_req_dn = op->o_req_ndn;
3527 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3528 rs->sr_err = backend_check_restrictions( op, rs,
3529 (struct berval *)&pcache_exop_QUERY_DELETE );
3530 if ( rs->sr_err != LDAP_SUCCESS ) {
3534 if ( op->o_bd->be_extended == NULL ) {
3535 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3536 "backend does not support extended operations" );
3540 op->o_bd->be_extended( op, rs );
3543 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3544 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3545 BER_BVZERO( &op->o_req_ndn );
3546 BER_BVZERO( &op->o_req_dn );
3549 if ( !BER_BVISNULL( &uuid ) ) {
3550 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3559 pcache_op_extended( Operation *op, SlapReply *rs )
3561 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3562 cache_manager *cm = on->on_bi.bi_private;
3564 #ifdef PCACHE_CONTROL_PRIVDB
3565 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3566 return pcache_op_privdb( op, rs );
3568 #endif /* PCACHE_CONTROL_PRIVDB */
3570 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3571 struct berval uuid = BER_BVNULL;
3572 ber_tag_t tag = LBER_DEFAULT;
3574 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3575 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3576 assert( rs->sr_err == LDAP_SUCCESS );
3578 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3579 /* remove all queries related to the selected entry */
3580 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3581 cm, &op->o_req_ndn, &uuid );
3583 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3584 if ( !BER_BVISNULL( &uuid ) ) {
3585 /* remove the selected query */
3586 remove_query_and_data( op, rs, cm, &uuid );
3587 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3588 rs->sr_err = LDAP_SUCCESS;
3591 /* TODO: remove all queries */
3592 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3593 rs->sr_text = "deletion of all queries not implemented";
3600 #endif /* PCACHE_EXOP_QUERY_DELETE */
3602 static slap_overinst pcache;
3604 static char *obsolete_names[] = {
3609 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3611 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3616 struct berval debugbv = BER_BVC("pcache");
3618 code = slap_loglevel_get( &debugbv, &pcache_debug );
3623 #ifdef PCACHE_CONTROL_PRIVDB
3624 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3625 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3626 parse_privdb_ctrl, &privDB_cid );
3627 if ( code != LDAP_SUCCESS ) {
3628 Debug( LDAP_DEBUG_ANY,
3629 "pcache_initialize: failed to register control %s (%d)\n",
3630 PCACHE_CONTROL_PRIVDB, code, 0 );
3633 #endif /* PCACHE_CONTROL_PRIVDB */
3635 #ifdef PCACHE_EXOP_QUERY_DELETE
3636 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3637 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3639 if ( code != LDAP_SUCCESS ) {
3640 Debug( LDAP_DEBUG_ANY,
3641 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3645 #endif /* PCACHE_EXOP_QUERY_DELETE */
3647 for ( i = 0; as[i].desc != NULL; i++ ) {
3648 code = register_at( as[i].desc, as[i].adp, 0 );
3650 Debug( LDAP_DEBUG_ANY,
3651 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3656 pcache.on_bi.bi_type = "pcache";
3657 pcache.on_bi.bi_obsolete_names = obsolete_names;
3658 pcache.on_bi.bi_db_init = pcache_db_init;
3659 pcache.on_bi.bi_db_config = pcache_db_config;
3660 pcache.on_bi.bi_db_open = pcache_db_open;
3661 pcache.on_bi.bi_db_close = pcache_db_close;
3662 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3664 pcache.on_bi.bi_op_search = pcache_op_search;
3665 #ifdef PCACHE_CONTROL_PRIVDB
3666 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3667 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3668 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3669 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3670 pcache.on_bi.bi_op_add = pcache_op_privdb;
3671 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3672 #endif /* PCACHE_CONTROL_PRIVDB */
3673 #ifdef PCACHE_EXOP_QUERY_DELETE
3674 pcache.on_bi.bi_extended = pcache_op_extended;
3675 #elif defined( PCACHE_CONTROL_PRIVDB )
3676 pcache.on_bi.bi_extended = pcache_op_privdb;
3679 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3681 pcache.on_bi.bi_cf_ocs = pcocs;
3683 code = config_register_schema( pccfg, pcocs );
3684 if ( code ) return code;
3686 return overlay_register( &pcache );
3689 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3690 int init_module(int argc, char *argv[]) {
3691 return pcache_initialize();
3695 #endif /* defined(SLAPD_OVER_PROXYCACHE) */