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 * <attrset> ::= CachedQuery.qtemp->attr_set_index
93 * <expiry> ::= CachedQuery.expiry_time
95 * quick hack: parse URI, call add_query() and then fix
96 * CachedQuery.expiry_time and CachedQuery.q_uuid
100 * Represents a set of projected attributes.
104 struct query_template_s *templates;
105 AttributeName* attrs; /* specifies the set */
107 #define PC_CONFIGURED (0x1)
108 #define PC_REFERENCED (0x2)
109 #define PC_GOT_OC (0x4)
110 int count; /* number of attributes */
113 /* struct representing a query template
114 * e.g. template string = &(cn=)(mail=)
116 typedef struct query_template_s {
117 struct query_template_s *qtnext;
118 struct query_template_s *qmnext;
121 CachedQuery* query; /* most recent query cached for the template */
122 CachedQuery* query_last; /* oldest query cached for the template */
123 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
124 struct berval querystr; /* Filter string corresponding to the QT */
126 int attr_set_index; /* determines the projected attributes */
127 int no_of_queries; /* Total number of queries in the template */
128 time_t ttl; /* TTL for the queries of this template */
129 time_t negttl; /* TTL for negative results */
130 struct attr_set t_attrs; /* filter attrs + attr_set */
133 struct query_manager_s;
135 /* prototypes for functions for 1) query containment
136 * 2) query addition, 3) cache replacement
138 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
139 typedef CachedQuery * (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
140 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
142 /* LDAP query cache */
143 typedef struct query_manager_s {
144 struct attr_set* attr_sets; /* possible sets of projected attributes */
145 QueryTemplate* templates; /* cacheable templates */
147 CachedQuery* lru_top; /* top and bottom of LRU list */
148 CachedQuery* lru_bottom;
150 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
152 /* Query cache methods */
153 QCfunc *qcfunc; /* Query containment*/
154 CRfunc *crfunc; /* cache replacement */
155 AddQueryfunc *addfunc; /* add query */
158 /* LDAP query cache manager */
159 typedef struct cache_manager_s {
160 BackendDB db; /* underlying database */
161 unsigned long num_cached_queries; /* total number of cached queries */
162 unsigned long max_queries; /* upper bound on # of cached queries */
163 int save_queries; /* save cached queries across restarts */
164 int numattrsets; /* number of attribute sets */
165 int cur_entries; /* current number of entries cached */
166 int max_entries; /* max number of entries cached */
167 int num_entries_limit; /* max # of entries in a cacheable query */
169 char response_cb; /* install the response callback
170 * at the tail of the callback list */
171 #define PCACHE_RESPONSE_CB_HEAD 0
172 #define PCACHE_RESPONSE_CB_TAIL 1
174 time_t cc_period; /* interval between successive consistency checks (sec) */
178 ldap_pvt_thread_mutex_t cache_mutex;
180 query_manager* qm; /* query cache managed by the cache manager */
183 static int pcache_debug;
185 #ifdef PCACHE_CONTROL_PRIVDB
186 static int privDB_cid;
187 #endif /* PCACHE_CONTROL_PRIVDB */
189 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
192 AttributeDescription **adp;
194 { "( 1.3.6.1.4.1.4203.666.11.9.1.1 "
196 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
197 "EQUALITY octetStringMatch "
198 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
199 "NO-USER-MODIFICATION "
200 "USAGE directoryOperation )",
202 { "( 1.3.6.1.4.1.4203.666.11.9.1.2 "
203 "NAME 'cachedQueryURL' "
204 "DESC 'URI describing a cached query' "
205 "EQUALITY caseExactMatch "
206 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
207 "NO-USER-MODIFICATION "
208 "USAGE directoryOperation )",
209 &ad_cachedQueryURL },
218 AttributeName** filter_attrs,
220 int* filter_got_oc );
227 QueryTemplate *templ,
234 struct berval *query_uuid );
237 * Turn a cached query into its URL representation
240 query2url( Operation *op, CachedQuery *q, struct berval *urlbv )
242 struct berval bv_scope,
244 char attrset_buf[ 32 ],
247 ber_len_t attrset_len,
250 ldap_pvt_scope2bv( q->scope, &bv_scope );
251 filter2bv_x( op, q->filter, &bv_filter );
252 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
253 "%lu", (unsigned long)q->qtemp->attr_set_index );
254 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
255 "%lu", (unsigned long)q->expiry_time );
257 urlbv->bv_len = STRLENOF( "ldap:///" )
258 + q->qbase->base.bv_len
263 + STRLENOF( "?x-uuid=" )
265 + STRLENOF( ",x-attrset=" )
267 + STRLENOF( ",x-expiry=" )
269 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
270 ptr = lutil_strcopy( ptr, "ldap:///" );
271 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
272 ptr = lutil_strcopy( ptr, "??" );
273 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
274 ptr = lutil_strcopy( ptr, "?" );
275 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
276 ptr = lutil_strcopy( ptr, "?x-uuid=" );
277 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
278 ptr = lutil_strcopy( ptr, ",x-attrset=" );
279 ptr = lutil_strcopy( ptr, attrset_buf );
280 ptr = lutil_strcopy( ptr, ",x-expiry=" );
281 ptr = lutil_strcopy( ptr, expiry_buf );
283 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
289 * Turn an URL representing a formerly cached query into a cached query,
290 * and try to cache it
301 LDAPURLDesc *lud = NULL;
303 tempstr = BER_BVNULL,
313 rc = ldap_url_parse( url, &lud );
314 if ( rc != LDAP_URL_SUCCESS ) {
318 /* non-allowed fields */
319 if ( lud->lud_host != NULL ) {
324 if ( lud->lud_attrs != NULL ) {
330 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
335 /* required fields */
336 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
341 switch ( lud->lud_scope ) {
342 case LDAP_SCOPE_BASE:
343 case LDAP_SCOPE_ONELEVEL:
344 case LDAP_SCOPE_SUBTREE:
345 case LDAP_SCOPE_SUBORDINATE:
353 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
358 if ( lud->lud_exts == NULL ) {
363 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
364 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
365 struct berval tmpUUID;
366 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
368 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
369 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
370 if ( rc != LDAP_SUCCESS ) {
375 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
376 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
382 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
385 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
389 expiry_time = (time_t)l;
403 if ( !got_attrset ) {
413 /* ignore expired queries */
414 if ( expiry_time <= slap_get_time()) {
416 SlapReply rs2 = { 0 };
418 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
420 (void)remove_query_data( &op2, &rs2, &uuid );
425 ber_str2bv( lud->lud_dn, 0, 0, &base );
426 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
427 if ( rc != LDAP_SUCCESS ) {
430 query.scope = lud->lud_scope;
431 query.filter = str2filter( lud->lud_filter );
433 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
435 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
436 ch_free( tempstr.bv_val );
441 /* check for query containment */
442 qt = qm->attr_sets[attrset].templates;
443 for ( ; qt; qt = qt->qtnext ) {
444 /* find if template i can potentially answer tempstr */
445 if ( bvmatch( &qt->querystr, &tempstr ) ) {
455 cq = add_query( op, qm, &query, qt, 1 );
457 cq->expiry_time = expiry_time;
460 /* it's now into cq->filter */
470 if ( query.filter != NULL ) filter_free( query.filter );
471 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
472 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
473 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
474 if ( lud != NULL ) ldap_free_urldesc( lud );
479 /* Return 1 for an added entry, else 0 */
484 struct berval* query_uuid )
487 Modifications* modlist = NULL;
488 const char* text = NULL;
490 char textbuf[SLAP_TEXT_BUFLEN];
491 size_t textlen = sizeof(textbuf);
493 SlapReply sreply = {REP_RESULT};
495 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
500 /* add queryId attribute */
501 attr_merge_one( e, ad_queryId, query_uuid, NULL );
503 /* append the attribute list from the fetched entry */
504 e->e_attrs->a_next = attr;
506 op->o_tag = LDAP_REQ_ADD;
507 op->o_protocol = LDAP_VERSION3;
508 op->o_callback = &cb;
509 op->o_time = slap_get_time();
510 op->o_do_not_cache = 1;
513 op->o_req_dn = e->e_name;
514 op->o_req_ndn = e->e_nname;
515 rc = op->o_bd->be_add( op, &sreply );
517 if ( rc != LDAP_SUCCESS ) {
518 if ( rc == LDAP_ALREADY_EXISTS ) {
519 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
520 modlist->sml_op = LDAP_MOD_ADD;
521 op->o_tag = LDAP_REQ_MODIFY;
522 op->orm_modlist = modlist;
523 op->o_bd->be_modify( op, &sreply );
524 slap_mods_free( modlist, 1 );
525 } else if ( rc == LDAP_REFERRAL ||
526 rc == LDAP_NO_SUCH_OBJECT ) {
527 syncrepl_add_glue( op, e );
536 if ( op->ora_e == e )
537 be_entry_release_w( op, e );
544 /* Length-ordered sort on normalized DNs */
545 static int pcache_dn_cmp( const void *v1, const void *v2 )
547 const Qbase *q1 = v1, *q2 = v2;
549 int rc = q1->base.bv_len - q2->base.bv_len;
551 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
555 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
558 dif = bv1->bv_len - bv2->bv_len;
560 if ( dif > 0 ) len -= dif;
561 len = memcmp( bv1->bv_val, bv2->bv_val, len );
567 /* compare the first value in each filter */
568 static int pcache_filter_cmp( const void *v1, const void *v2 )
570 const CachedQuery *q1 = v1, *q2 =v2;
571 int rc, weight1, weight2;
573 switch( q1->first->f_choice ) {
574 case LDAP_FILTER_PRESENT:
577 case LDAP_FILTER_EQUALITY:
585 switch( q2->first->f_choice ) {
586 case LDAP_FILTER_PRESENT:
589 case LDAP_FILTER_EQUALITY:
597 rc = weight1 - weight2;
602 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
605 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
607 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
608 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
609 rc = lex_bvcmp( &q1->first->f_sub_initial,
610 &q2->first->f_sub_initial );
614 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
618 if ( q1->first->f_sub_any ) {
619 if ( q2->first->f_sub_any ) {
620 rc = lex_bvcmp( q1->first->f_sub_any,
621 q2->first->f_sub_any );
625 } else if ( q2->first->f_sub_any ) {
629 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
630 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
631 rc = lex_bvcmp( &q1->first->f_sub_final,
632 &q2->first->f_sub_final );
636 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
640 rc = lex_bvcmp( &q1->first->f_mr_value,
641 &q2->first->f_mr_value );
650 /* add query on top of LRU list */
652 add_query_on_top (query_manager* qm, CachedQuery* qc)
654 CachedQuery* top = qm->lru_top;
665 Debug( pcache_debug, "Base of added query = %s\n",
666 qc->qbase->base.bv_val, 0, 0 );
669 /* remove_query from LRU list */
672 remove_query (query_manager* qm, CachedQuery* qc)
695 qc->lru_up = qc->lru_down = NULL;
698 /* find and remove string2 from string1
699 * from start if position = 1,
700 * from end if position = 3,
701 * from anywhere if position = 2
702 * string1 is overwritten if position = 2.
706 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
717 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
718 ber2->bv_val, ber2->bv_len )) {
720 ber1->bv_val += ber2->bv_len;
721 ber1->bv_len -= ber2->bv_len;
726 ber1->bv_val[ber1->bv_len] = '\0';
727 temp = strstr( ber1->bv_val, ber2->bv_val );
729 strcpy( temp, temp+ber2->bv_len );
730 ber1->bv_len -= ber2->bv_len;
736 if ( ber1->bv_len >= ber2->bv_len &&
737 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
740 ber1->bv_len -= ber2->bv_len;
748 static struct berval*
749 merge_init_final(Operation *op, struct berval* init, struct berval* any,
750 struct berval* final)
752 struct berval* merged, *temp;
753 int i, any_count, count;
755 for (any_count=0; any && any[any_count].bv_val; any_count++)
765 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
770 ber_dupbv_x( temp, init, op->o_tmpmemctx );
774 for (i=0; i<any_count; i++) {
775 ber_dupbv_x( temp, any, op->o_tmpmemctx );
780 ber_dupbv_x( temp, final, op->o_tmpmemctx );
787 /* Each element in stored must be found in incoming. Incoming is overwritten.
790 strings_containment(struct berval* stored, struct berval* incoming)
792 struct berval* element;
796 for ( element=stored; element->bv_val != NULL; element++ ) {
797 for (j = k; incoming[j].bv_val != NULL; j++) {
798 if (find_and_remove(&(incoming[j]), element, 2)) {
815 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
819 struct berval init_incoming;
820 struct berval final_incoming;
821 struct berval *remaining_incoming = NULL;
823 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
824 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
827 init_incoming = incoming->f_sub_initial;
828 final_incoming = incoming->f_sub_final;
830 if (find_and_remove(&init_incoming,
831 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
832 &(stored->f_sub_final), 3))
834 if (stored->f_sub_any == NULL) {
838 remaining_incoming = merge_init_final(op, &init_incoming,
839 incoming->f_sub_any, &final_incoming);
840 rc = strings_containment(stored->f_sub_any, remaining_incoming);
841 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
848 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
850 struct berval incoming_val[2];
853 incoming_val[1] = incoming->f_av_value;
855 if (find_and_remove(incoming_val+1,
856 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
857 &(stored->f_sub_final), 3)) {
858 if (stored->f_sub_any == NULL){
862 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
863 BER_BVZERO( incoming_val+1 );
864 rc = strings_containment(stored->f_sub_any, incoming_val);
865 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
872 filter_first( Filter *f )
874 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
881 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
885 MatchingRule* mrule = NULL;
886 int res=0, eqpass= 0;
894 /* substring matches sort to the end, and we just have to
895 * walk the entire list.
897 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
898 ptr = tavl_end( root, 1 );
901 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
902 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
911 /* an incoming substr query can only be satisfied by a cached
914 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
915 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
918 /* an incoming eq query can be satisfied by a cached eq or substr
921 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
923 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
924 nextpass: eqpass = 1;
925 ptr = tavl_end( root, 1 );
930 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
936 switch (fs->f_choice) {
937 case LDAP_FILTER_EQUALITY:
938 if (fi->f_choice == LDAP_FILTER_EQUALITY)
939 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
945 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
952 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
953 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
954 &(fi->f_ava->aa_value),
955 &(fs->f_ava->aa_value), &text);
956 if (rc != LDAP_SUCCESS) {
959 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
962 switch (fs->f_choice) {
964 case LDAP_FILTER_AND:
969 case LDAP_FILTER_SUBSTRINGS:
970 /* check if the equality query can be
971 * answered with cached substring query */
972 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
973 && substr_containment_equality( op,
976 /* check if the substring query can be
977 * answered with cached substring query */
978 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
979 ) && substr_containment_substr( op,
985 case LDAP_FILTER_PRESENT:
990 case LDAP_FILTER_EQUALITY:
997 if (mrule && ret >= 0)
1002 case LDAP_FILTER_LE:
1003 if (mrule && ret <= 0)
1008 case LDAP_FILTER_NOT:
1014 } while((res) && (fi != NULL) && (fs != NULL));
1018 ptr = tavl_next( ptr, dir );
1023 /* check whether query is contained in any of
1024 * the cached queries in template
1026 static CachedQuery *
1027 query_containment(Operation *op, query_manager *qm,
1029 QueryTemplate *templa)
1032 int depth = 0, tscope;
1033 Qbase qbase, *qbptr = NULL;
1036 if (query->filter != NULL) {
1039 Debug( pcache_debug, "Lock QC index = %p\n",
1040 (void *) templa, 0, 0 );
1041 qbase.base = query->base;
1043 first = filter_first( query->filter );
1045 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1048 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1050 tscope = query->scope;
1051 /* Find a matching scope:
1052 * match at depth 0 OK
1055 * subord at depth > 0 OK
1056 * subtree at any depth OK
1058 * subtree or subord at any depth OK
1060 * subtree or subord at any depth OK
1062 * subord at depth > 0 OK
1063 * subtree at any depth OK
1065 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1066 switch ( query->scope ) {
1067 case LDAP_SCOPE_BASE:
1068 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1069 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1070 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1072 case LDAP_SCOPE_ONE:
1073 if ( tscope == LDAP_SCOPE_BASE )
1074 tscope = LDAP_SCOPE_ONE;
1075 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1076 if ( !depth ) break;
1077 if ( tscope < LDAP_SCOPE_SUBTREE )
1078 tscope = LDAP_SCOPE_SUBTREE;
1080 case LDAP_SCOPE_SUBTREE:
1081 if ( tscope < LDAP_SCOPE_SUBTREE )
1082 tscope = LDAP_SCOPE_SUBTREE;
1083 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1085 case LDAP_SCOPE_CHILDREN:
1086 if ( tscope < LDAP_SCOPE_SUBTREE )
1087 tscope = LDAP_SCOPE_SUBTREE;
1090 if ( !qbptr->scopes[tscope] ) continue;
1093 qc = find_filter( op, qbptr->scopes[tscope],
1094 query->filter, first );
1096 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1097 if (qm->lru_top != qc) {
1098 remove_query(qm, qc);
1099 add_query_on_top(qm, qc);
1101 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1106 if ( be_issuffix( op->o_bd, &qbase.base ))
1109 dnParent( &qbase.base, &pdn );
1114 Debug( pcache_debug,
1115 "Not answerable: Unlock QC index=%p\n",
1116 (void *) templa, 0, 0 );
1117 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1123 free_query (CachedQuery* qc)
1125 free(qc->q_uuid.bv_val);
1126 filter_free(qc->filter);
1131 /* Add query to query cache */
1132 static CachedQuery *
1137 QueryTemplate *templ,
1140 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1145 new_cached_query->qtemp = templ;
1146 BER_BVZERO( &new_cached_query->q_uuid );
1148 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1150 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1152 new_cached_query->lru_up = NULL;
1153 new_cached_query->lru_down = NULL;
1154 Debug( pcache_debug, "Added query expires at %ld\n",
1155 (long) new_cached_query->expiry_time, 0, 0 );
1157 new_cached_query->scope = query->scope;
1158 new_cached_query->filter = query->filter;
1159 new_cached_query->first = first = filter_first( query->filter );
1161 qb.base = query->base;
1163 /* Adding a query */
1164 Debug( pcache_debug, "Lock AQ index = %p\n",
1165 (void *) templ, 0, 0 );
1166 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1167 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1169 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1170 qbase->base.bv_len = qb.base.bv_len;
1171 qbase->base.bv_val = (char *)(qbase+1);
1172 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1173 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1174 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1176 new_cached_query->next = templ->query;
1177 new_cached_query->prev = NULL;
1178 new_cached_query->qbase = qbase;
1179 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1180 pcache_filter_cmp, avl_dup_error );
1183 if (templ->query == NULL)
1184 templ->query_last = new_cached_query;
1186 templ->query->prev = new_cached_query;
1187 templ->query = new_cached_query;
1188 templ->no_of_queries++;
1190 ch_free( new_cached_query );
1191 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1192 query->filter, first );
1193 filter_free( query->filter );
1195 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1196 (void *) templ, templ->no_of_queries, 0 );
1198 Debug( pcache_debug, "Unlock AQ index = %p \n",
1199 (void *) templ, 0, 0 );
1200 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1202 /* Adding on top of LRU list */
1204 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1205 add_query_on_top(qm, new_cached_query);
1206 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1208 return rc == 0 ? new_cached_query : NULL;
1212 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1214 if (!qc->prev && !qc->next) {
1215 template->query_last = template->query = NULL;
1216 } else if (qc->prev == NULL) {
1217 qc->next->prev = NULL;
1218 template->query = qc->next;
1219 } else if (qc->next == NULL) {
1220 qc->prev->next = NULL;
1221 template->query_last = qc->prev;
1223 qc->next->prev = qc->prev;
1224 qc->prev->next = qc->next;
1226 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1227 qc->qbase->queries--;
1228 if ( qc->qbase->queries == 0 ) {
1229 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1230 ch_free( qc->qbase );
1234 template->no_of_queries--;
1237 /* remove bottom query of LRU list from the query cache */
1239 * NOTE: slight change in functionality.
1241 * - if result->bv_val is NULL, the query at the bottom of the LRU
1243 * - otherwise, the query whose UUID is *result is removed
1244 * - if not found, result->bv_val is zeroed
1247 cache_replacement(query_manager* qm, struct berval *result)
1249 CachedQuery* bottom;
1250 QueryTemplate *temp;
1252 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1253 if ( BER_BVISNULL( result ) ) {
1254 bottom = qm->lru_bottom;
1257 Debug ( pcache_debug,
1258 "Cache replacement invoked without "
1259 "any query in LRU list\n", 0, 0, 0 );
1260 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1265 for ( bottom = qm->lru_bottom;
1267 bottom = bottom->lru_up )
1269 if ( bvmatch( result, &bottom->q_uuid ) ) {
1275 Debug ( pcache_debug,
1276 "Could not find query with uuid=\"%s\""
1277 "in LRU list\n", result->bv_val, 0, 0 );
1278 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1279 BER_BVZERO( result );
1284 temp = bottom->qtemp;
1285 remove_query(qm, bottom);
1286 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1288 *result = bottom->q_uuid;
1289 bottom->q_uuid.bv_val = NULL;
1291 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1292 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1293 remove_from_template(bottom, temp);
1294 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1295 (void *) temp, temp->no_of_queries, 0 );
1296 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1297 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1302 struct query_info *next;
1314 struct query_info *qi;
1317 if ( rs->sr_type != REP_SEARCH ) return 0;
1319 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1320 if ( attr == NULL ) return 0;
1322 for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1324 assert( count > 0 );
1325 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1326 qi->next = op->o_callback->sc_private;
1327 op->o_callback->sc_private = qi;
1328 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1329 qi->del = ( count == 1 );
1338 struct berval *query_uuid )
1340 struct query_info *qi, *qnext;
1341 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1342 #ifdef LDAP_COMP_MATCH
1343 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1345 AttributeAssertion ava = { NULL, BER_BVNULL };
1347 Filter filter = {LDAP_FILTER_EQUALITY};
1348 SlapReply sreply = {REP_RESULT};
1349 slap_callback cb = { NULL, remove_func, NULL, NULL };
1352 sreply.sr_entry = NULL;
1353 sreply.sr_nentries = 0;
1354 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1355 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1356 filter.f_ava = &ava;
1357 filter.f_av_desc = ad_queryId;
1358 filter.f_av_value = *query_uuid;
1360 op->o_tag = LDAP_REQ_SEARCH;
1361 op->o_protocol = LDAP_VERSION3;
1362 op->o_callback = &cb;
1363 op->o_time = slap_get_time();
1364 op->o_do_not_cache = 1;
1366 op->o_req_dn = op->o_bd->be_suffix[0];
1367 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1368 op->ors_scope = LDAP_SCOPE_SUBTREE;
1369 op->ors_deref = LDAP_DEREF_NEVER;
1370 op->ors_slimit = SLAP_NO_LIMIT;
1371 op->ors_tlimit = SLAP_NO_LIMIT;
1372 op->ors_filter = &filter;
1373 op->ors_filterstr.bv_val = filter_str;
1374 op->ors_filterstr.bv_len = strlen(filter_str);
1375 op->ors_attrs = NULL;
1376 op->ors_attrsonly = 0;
1378 op->o_bd->be_search( op, &sreply );
1380 for ( qi=cb.sc_private; qi; qi=qnext ) {
1383 op->o_req_dn = qi->xdn;
1384 op->o_req_ndn = qi->xdn;
1387 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1388 query_uuid->bv_val, 0, 0 );
1390 op->o_tag = LDAP_REQ_DELETE;
1392 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1398 struct berval vals[2];
1400 vals[0] = *query_uuid;
1401 vals[1].bv_val = NULL;
1403 mod.sml_op = LDAP_MOD_DELETE;
1405 mod.sml_desc = ad_queryId;
1406 mod.sml_type = ad_queryId->ad_cname;
1407 mod.sml_values = vals;
1408 mod.sml_nvalues = NULL;
1409 mod.sml_next = NULL;
1410 Debug( pcache_debug,
1411 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1412 query_uuid->bv_val, 0, 0 );
1414 op->orm_modlist = &mod;
1416 op->o_bd->be_modify( op, &sreply );
1418 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1419 op->o_tmpfree( qi, op->o_tmpmemctx );
1426 AttributeName* attrs,
1435 struct berval *fstr,
1436 AttributeName** filter_attrs,
1438 int* filter_got_oc )
1440 AttributeDescription *ad;
1442 switch ( f->f_choice ) {
1443 case LDAP_FILTER_EQUALITY:
1445 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1446 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1449 case LDAP_FILTER_GE:
1451 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1452 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1455 case LDAP_FILTER_LE:
1457 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1458 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1461 case LDAP_FILTER_APPROX:
1463 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1464 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1467 case LDAP_FILTER_SUBSTRINGS:
1469 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1470 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1473 case LDAP_FILTER_PRESENT:
1475 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1476 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1479 case LDAP_FILTER_AND:
1480 case LDAP_FILTER_OR:
1481 case LDAP_FILTER_NOT: {
1483 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1484 f->f_choice == LDAP_FILTER_AND ? '&' :
1485 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1486 fstr->bv_len += sizeof("(%") - 1;
1488 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1489 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1493 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1494 fstr->bv_len += sizeof(")") - 1;
1500 strcpy( fstr->bv_val, "(?=?)" );
1501 fstr->bv_len += sizeof("(?=?)")-1;
1505 if ( filter_attrs != NULL ) {
1506 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1507 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1509 (*filter_attrs)[*filter_cnt].an_desc = ad;
1510 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1511 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1512 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1513 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1515 if ( ad == slap_schema.si_ad_objectClass )
1522 struct search_info {
1525 QueryTemplate *qtemp;
1526 AttributeName* save_attrs; /* original attributes, saved for response */
1534 remove_query_and_data(
1538 struct berval *uuid )
1540 query_manager* qm = cm->qm;
1542 qm->crfunc( qm, uuid );
1543 if ( !BER_BVISNULL( uuid ) ) {
1546 Debug( pcache_debug,
1547 "Removing query UUID %s\n",
1548 uuid->bv_val, 0, 0 );
1549 return_val = remove_query_data( op, rs, uuid );
1550 Debug( pcache_debug,
1551 "QUERY REMOVED, SIZE=%d\n",
1553 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1554 cm->cur_entries -= return_val;
1555 cm->num_cached_queries--;
1556 Debug( pcache_debug,
1557 "STORED QUERIES = %lu\n",
1558 cm->num_cached_queries, 0, 0 );
1559 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1560 Debug( pcache_debug,
1561 "QUERY REMOVED, CACHE ="
1563 cm->cur_entries, 0, 0 );
1568 * Callback used to fetch queryId values based on entryUUID;
1569 * used by pcache_remove_entries_from_cache()
1572 fetch_queryId_cb( Operation *op, SlapReply *rs )
1576 /* only care about searchEntry responses */
1577 if ( rs->sr_type != REP_SEARCH ) {
1581 /* allow only one response per entryUUID */
1582 if ( op->o_callback->sc_private != NULL ) {
1588 /* copy all queryId values into callback's private data */
1589 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1591 BerVarray vals = NULL;
1593 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1594 op->o_callback->sc_private = (void *)vals;
1598 /* clear entry if required */
1599 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1600 entry_free( rs->sr_entry );
1601 rs->sr_entry = NULL;
1602 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1609 * Call that allows to remove a set of entries from the cache,
1610 * by forcing the removal of all the related queries.
1613 pcache_remove_entries_from_cache(
1618 Connection conn = { 0 };
1619 OperationBuffer opbuf;
1621 slap_callback sc = { 0 };
1622 SlapReply rs = { REP_RESULT };
1624 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1625 #ifdef LDAP_COMP_MATCH
1626 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1628 AttributeAssertion ava = { NULL, BER_BVNULL };
1630 AttributeName attrs[ 2 ] = { 0 };
1634 void *thrctx = ldap_pvt_thread_pool_context();
1636 connection_fake_init( &conn, &opbuf, thrctx );
1644 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1645 op->ors_scope = LDAP_SCOPE_SUBTREE;
1646 op->ors_deref = LDAP_DEREF_NEVER;
1647 f.f_choice = LDAP_FILTER_EQUALITY;
1649 ava.aa_desc = slap_schema.si_ad_entryUUID;
1650 op->ors_filter = &f;
1652 op->ors_tlimit = SLAP_NO_LIMIT;
1653 attrs[ 0 ].an_desc = ad_queryId;
1654 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1655 op->ors_attrs = attrs;
1656 op->ors_attrsonly = 0;
1658 op->o_req_dn = cm->db.be_suffix[ 0 ];
1659 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1661 op->o_tag = LDAP_REQ_SEARCH;
1662 op->o_protocol = LDAP_VERSION3;
1663 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1665 op->o_dn = op->o_bd->be_rootdn;
1666 op->o_ndn = op->o_bd->be_rootndn;
1667 sc.sc_response = fetch_queryId_cb;
1668 op->o_callback = ≻
1670 for ( s = 0; !BER_BVISNULL( &UUIDs[ s ] ); s++ ) {
1671 BerVarray vals = NULL;
1673 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1674 "(entryUUID=%s)", UUIDs[ s ].bv_val );
1675 op->ors_filterstr.bv_val = filtbuf;
1676 ava.aa_value = UUIDs[ s ];
1678 rc = op->o_bd->be_search( op, &rs );
1679 if ( rc != LDAP_SUCCESS ) {
1683 vals = (BerVarray)op->o_callback->sc_private;
1684 if ( vals != NULL ) {
1687 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1688 struct berval val = vals[ i ];
1690 remove_query_and_data( op, &rs, cm, &val );
1692 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1693 ch_free( val.bv_val );
1697 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1698 op->o_callback->sc_private = NULL;
1706 * Call that allows to remove a set of queries from the cache
1709 pcache_remove_entry_queries_from_cache(
1713 struct berval *uuid )
1715 Connection conn = { 0 };
1716 OperationBuffer opbuf;
1718 slap_callback sc = { 0 };
1719 SlapReply rs = { REP_RESULT };
1721 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1722 #ifdef LDAP_COMP_MATCH
1723 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1725 AttributeAssertion ava = { NULL, BER_BVNULL };
1727 AttributeName attrs[ 2 ] = { 0 };
1730 BerVarray vals = NULL;
1733 void *thrctx = ldap_pvt_thread_pool_context();
1735 connection_fake_init( &conn, &opbuf, thrctx );
1743 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1744 op->ors_scope = LDAP_SCOPE_BASE;
1745 op->ors_deref = LDAP_DEREF_NEVER;
1746 if ( uuid == NULL || BER_BVISNULL( uuid ) ) {
1747 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1748 f.f_choice = LDAP_FILTER_PRESENT;
1749 f.f_desc = slap_schema.si_ad_objectClass;
1752 op->ors_filterstr.bv_len = snprintf( filter_str,
1753 sizeof( filter_str ), "(%s=%s)",
1754 ad_queryId->ad_cname.bv_val, uuid->bv_val );
1755 f.f_choice = LDAP_FILTER_EQUALITY;
1757 f.f_av_desc = ad_queryId;
1758 f.f_av_value = *uuid;
1760 op->ors_filter = &f;
1762 op->ors_tlimit = SLAP_NO_LIMIT;
1763 attrs[ 0 ].an_desc = ad_queryId;
1764 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1765 op->ors_attrs = attrs;
1766 op->ors_attrsonly = 0;
1768 op->o_req_dn = *ndn;
1769 op->o_req_ndn = *ndn;
1771 op->o_tag = LDAP_REQ_SEARCH;
1772 op->o_protocol = LDAP_VERSION3;
1773 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1775 op->o_dn = op->o_bd->be_rootdn;
1776 op->o_ndn = op->o_bd->be_rootndn;
1777 sc.sc_response = fetch_queryId_cb;
1778 op->o_callback = ≻
1780 rc = op->o_bd->be_search( op, &rs );
1781 if ( rc != LDAP_SUCCESS ) {
1785 vals = (BerVarray)op->o_callback->sc_private;
1786 if ( vals != NULL ) {
1789 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1790 struct berval val = vals[ i ];
1792 remove_query_and_data( op, &rs, cm, &val );
1794 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1795 ch_free( val.bv_val );
1799 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1802 return LDAP_SUCCESS;
1809 struct berval *query_uuid )
1811 struct search_info *si = op->o_callback->sc_private;
1812 slap_overinst *on = si->on;
1813 cache_manager *cm = on->on_bi.bi_private;
1816 struct berval crp_uuid;
1817 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1818 Operation op_tmp = *op;
1820 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1821 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1823 op_tmp.o_bd = &cm->db;
1824 op_tmp.o_dn = cm->db.be_rootdn;
1825 op_tmp.o_ndn = cm->db.be_rootndn;
1827 Debug( pcache_debug, "UUID for query being added = %s\n",
1830 for ( e=si->head; e; e=si->head ) {
1831 si->head = e->e_private;
1832 e->e_private = NULL;
1833 while ( cm->cur_entries > (cm->max_entries) ) {
1834 BER_BVZERO( &crp_uuid );
1835 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1838 return_val = merge_entry(&op_tmp, e, query_uuid);
1839 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1840 cm->cur_entries += return_val;
1841 Debug( pcache_debug,
1842 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1843 cm->cur_entries, 0, 0 );
1845 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1852 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1853 slap_callback *cb = op->o_callback;
1854 struct search_info *si = cb->sc_private;
1855 if ( si->save_attrs != NULL ) {
1856 rs->sr_attrs = si->save_attrs;
1857 op->ors_attrs = si->save_attrs;
1859 op->o_callback = op->o_callback->sc_next;
1860 op->o_tmpfree( cb, op->o_tmpmemctx );
1861 return SLAP_CB_CONTINUE;
1869 struct search_info *si = op->o_callback->sc_private;
1870 slap_overinst *on = si->on;
1871 cache_manager *cm = on->on_bi.bi_private;
1872 query_manager* qm = cm->qm;
1874 if ( si->save_attrs != NULL ) {
1875 rs->sr_attrs = si->save_attrs;
1876 op->ors_attrs = si->save_attrs;
1879 if ( rs->sr_type == REP_SEARCH ) {
1881 /* If we haven't exceeded the limit for this query,
1882 * build a chain of answers to store. If we hit the
1883 * limit, empty the chain and ignore the rest.
1886 if ( si->count < si->max ) {
1888 e = entry_dup( rs->sr_entry );
1889 if ( !si->head ) si->head = e;
1890 if ( si->tail ) si->tail->e_private = e;
1895 for (;si->head; si->head=e) {
1896 e = si->head->e_private;
1897 si->head->e_private = NULL;
1898 entry_free(si->head);
1904 } else if ( rs->sr_type == REP_RESULT ) {
1906 ( si->qtemp->negttl && !si->count && !si->over &&
1907 rs->sr_err == LDAP_SUCCESS )) {
1908 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1913 cache_entries( op, rs, &qc->q_uuid );
1914 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1915 cm->num_cached_queries++;
1916 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1917 cm->num_cached_queries, 0, 0 );
1918 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1920 /* If the consistency checker suspended itself,
1923 if ( cm->cc_paused ) {
1924 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1925 if ( cm->cc_paused ) {
1927 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1929 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1931 } else if ( si->count ) {
1932 /* duplicate query, free it */
1934 for (;si->head; si->head=e) {
1935 e = si->head->e_private;
1936 si->head->e_private = NULL;
1937 entry_free(si->head);
1941 filter_free( si->query.filter );
1944 op->o_callback->sc_cleanup = pcache_op_cleanup;
1946 return SLAP_CB_CONTINUE;
1952 AttributeName** new_attrs,
1953 struct attr_set *attrs,
1954 AttributeName* filter_attrs,
1964 /* duplicate attrs */
1965 count = attrs->count + fattr_cnt;
1966 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1971 *new_attrs = (AttributeName*)ch_calloc( count + 1,
1972 sizeof(AttributeName) );
1973 for (i=0; i<attrs->count; i++) {
1974 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1975 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1977 BER_BVZERO( &(*new_attrs)[i].an_name );
1978 alluser = an_find(*new_attrs, &AllUser);
1979 allop = an_find(*new_attrs, &AllOper);
1982 for ( i=0; i<fattr_cnt; i++ ) {
1983 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
1986 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1990 } else if ( alluser ) {
1993 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1994 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1995 (*new_attrs)[j].an_oc = NULL;
1996 (*new_attrs)[j].an_oc_exclude = 0;
2000 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2001 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2002 (*new_attrs)[j].an_oc = NULL;
2003 (*new_attrs)[j].an_oc_exclude = 0;
2006 BER_BVZERO( &(*new_attrs)[j].an_name );
2011 /* NOTE: this is a quick workaround to let pcache minimally interact
2012 * with pagedResults. A more articulated solutions would be to
2013 * perform the remote query without control and cache all results,
2014 * performing the pagedResults search only within the client
2015 * and the proxy. This requires pcache to understand pagedResults. */
2017 pcache_chk_controls(
2021 const char *non = "";
2022 const char *stripped = "";
2024 switch( op->o_pagedresults ) {
2025 case SLAP_CONTROL_NONCRITICAL:
2027 stripped = "; stripped";
2030 case SLAP_CONTROL_CRITICAL:
2031 Debug( pcache_debug, "%s: "
2032 "%scritical pagedResults control "
2033 "disabled with proxy cache%s.\n",
2034 op->o_log_prefix, non, stripped );
2036 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2040 rs->sr_err = SLAP_CB_CONTINUE;
2047 #ifdef PCACHE_CONTROL_PRIVDB
2053 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2054 cache_manager *cm = on->on_bi.bi_private;
2055 slap_callback *save_cb;
2058 /* skip if control is unset */
2059 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2060 return SLAP_CB_CONTINUE;
2063 /* FIXME: might be a little bit exaggerated... */
2064 if ( !be_isroot( op ) ) {
2065 save_cb = op->o_callback;
2066 op->o_callback = NULL;
2067 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2068 "pcachePrivDB: operation not allowed" );
2069 op->o_callback = save_cb;
2074 /* map tag to operation */
2075 type = slap_req2op( op->o_tag );
2076 if ( type != SLAP_OP_LAST ) {
2079 /* execute, if possible */
2080 func = &cm->db.be_bind;
2081 if ( func[ type ] != NULL ) {
2082 Operation op2 = *op;
2086 return func[ type ]( &op2, rs );
2090 /* otherwise fall back to error */
2091 save_cb = op->o_callback;
2092 op->o_callback = NULL;
2093 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2094 "operation not supported with pcachePrivDB control" );
2095 op->o_callback = save_cb;
2099 #endif /* PCACHE_CONTROL_PRIVDB */
2106 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2107 cache_manager *cm = on->on_bi.bi_private;
2108 query_manager* qm = cm->qm;
2112 AttributeName *filter_attrs = NULL;
2115 QueryTemplate *qtemp = NULL;
2118 CachedQuery *answerable = NULL;
2121 int fattr_got_oc = 0;
2123 struct berval tempstr;
2125 #ifdef PCACHE_CONTROL_PRIVDB
2126 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2127 return pcache_op_privdb( op, rs );
2129 #endif /* PCACHE_CONTROL_PRIVDB */
2131 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2133 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2134 &fattr_cnt, &fattr_got_oc )) {
2135 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2136 return SLAP_CB_CONTINUE;
2139 Debug( pcache_debug, "query template of incoming query = %s\n",
2140 tempstr.bv_val, 0, 0 );
2142 /* FIXME: cannot cache/answer requests with pagedResults control */
2145 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2147 query.filter = op->ors_filter;
2148 query.base = op->o_req_ndn;
2149 query.scope = op->ors_scope;
2151 /* check for query containment */
2152 if (attr_set > -1) {
2153 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2154 for (; qt; qt = qt->qtnext ) {
2155 /* find if template i can potentially answer tempstr */
2156 if (qt->querystr.bv_len != tempstr.bv_len ||
2157 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2161 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2162 op->ors_filterstr.bv_val, 0, 0 );
2163 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2169 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2172 /* Need to clear the callbacks of the original operation,
2173 * in case there are other overlays */
2174 BackendDB *save_bd = op->o_bd;
2175 slap_callback *save_cb = op->o_callback;
2177 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2178 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2179 if ( BER_BVISNULL( &answerable->q_uuid )) {
2180 /* No entries cached, just an empty result set */
2182 send_ldap_result( op, rs );
2185 op->o_callback = NULL;
2186 i = cm->db.bd_info->bi_op_search( op, rs );
2188 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2190 op->o_callback = save_cb;
2194 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2196 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2197 if (cm->num_cached_queries >= cm->max_queries) {
2200 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2202 if (op->ors_attrsonly)
2207 struct search_info *si;
2209 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2210 query.filter = filter_dup(op->ors_filter, NULL);
2211 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2212 if ( !qtemp->t_attrs.count ) {
2213 qtemp->t_attrs.count = add_filter_attrs(op,
2214 &qtemp->t_attrs.attrs,
2215 &qm->attr_sets[attr_set],
2216 filter_attrs, fattr_cnt, fattr_got_oc);
2218 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2220 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2221 cb->sc_response = pcache_response;
2222 cb->sc_cleanup = NULL;
2223 cb->sc_private = (cb+1);
2224 si = cb->sc_private;
2228 si->max = cm->num_entries_limit ;
2233 si->save_attrs = op->ors_attrs;
2235 op->ors_attrs = qtemp->t_attrs.attrs;
2237 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2238 cb->sc_next = op->o_callback;
2239 op->o_callback = cb;
2242 slap_callback **pcb;
2244 /* need to move the callback at the end, in case other
2245 * overlays are present, so that the final entry is
2246 * actually cached */
2248 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2253 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2257 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2259 return SLAP_CB_CONTINUE;
2264 AttributeName* attrs,
2272 for ( ; attrs[count].an_name.bv_val; count++ );
2275 /* recognize a single "*" or a "1.1" */
2278 attrs = slap_anlist_all_user_attributes;
2280 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2285 for ( i = 0; i < num; i++ ) {
2289 if ( count > qm->attr_sets[i].count ) {
2294 if ( !qm->attr_sets[i].count ) {
2300 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2301 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2324 struct re_s *rtask = arg;
2325 slap_overinst *on = rtask->arg;
2326 cache_manager *cm = on->on_bi.bi_private;
2327 query_manager *qm = cm->qm;
2328 Connection conn = {0};
2329 OperationBuffer opbuf;
2332 SlapReply rs = {REP_RESULT};
2334 int return_val, pause = 1;
2335 QueryTemplate* templ;
2337 connection_fake_init( &conn, &opbuf, ctx );
2341 op->o_dn = cm->db.be_rootdn;
2342 op->o_ndn = cm->db.be_rootndn;
2346 for (templ = qm->templates; templ; templ=templ->qmnext) {
2347 query = templ->query_last;
2348 if ( query ) pause = 0;
2349 op->o_time = slap_get_time();
2350 while (query && (query->expiry_time < op->o_time)) {
2352 Debug( pcache_debug, "Lock CR index = %p\n",
2353 (void *) templ, 0, 0 );
2354 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2355 if ( query == templ->query_last ) {
2357 remove_from_template(query, templ);
2358 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2359 (void *) templ, templ->no_of_queries, 0 );
2360 Debug( pcache_debug, "Unlock CR index = %p\n",
2361 (void *) templ, 0, 0 );
2363 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2365 query = templ->query_last;
2368 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2369 remove_query(qm, query);
2370 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2371 if ( BER_BVISNULL( &query->q_uuid ))
2374 return_val = remove_query_data(op, &rs, &query->q_uuid);
2375 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2377 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2378 cm->cur_entries -= return_val;
2379 cm->num_cached_queries--;
2380 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2381 cm->num_cached_queries, 0, 0 );
2382 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2383 Debug( pcache_debug,
2384 "STALE QUERY REMOVED, CACHE ="
2386 cm->cur_entries, 0, 0 );
2388 query = templ->query_last;
2391 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2392 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2393 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2395 /* If there were no queries, defer processing for a while */
2396 cm->cc_paused = pause;
2397 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2399 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2404 #define MAX_ATTR_SETS 500
2414 static ConfigDriver pc_cf_gen;
2415 static ConfigLDAPadd pc_ldadd;
2416 static ConfigCfAdd pc_cfadd;
2418 static ConfigTable pccfg[] = {
2419 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2421 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2422 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2423 "DESC 'ProxyCache basic parameters' "
2424 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2425 { "proxyattrset", "index> <attributes...",
2426 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2427 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2428 "DESC 'A set of attributes to cache' "
2429 "SYNTAX OMsDirectoryString )", NULL, NULL },
2430 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2431 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2432 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2433 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2434 "SYNTAX OMsDirectoryString )", NULL, NULL },
2435 { "response-callback", "head|tail(default)",
2436 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2437 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2438 "DESC 'Response callback position in overlay stack' "
2439 "SYNTAX OMsDirectoryString )", NULL, NULL },
2440 { "proxyCacheQueries", "queries",
2441 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2442 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2443 "DESC 'Maximum number of queries to cache' "
2444 "SYNTAX OMsInteger )", NULL, NULL },
2445 { "proxySaveQueries", "TRUE|FALSE",
2446 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2447 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2448 "DESC 'Save cached queries for hot restart' "
2449 "SYNTAX OMsBoolean )", NULL, NULL },
2451 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2454 static ConfigOCs pcocs[] = {
2455 { "( OLcfgOvOc:2.1 "
2456 "NAME 'olcPcacheConfig' "
2457 "DESC 'ProxyCache configuration' "
2458 "SUP olcOverlayConfig "
2459 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2460 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2461 Cft_Overlay, pccfg, NULL, pc_cfadd },
2462 { "( OLcfgOvOc:2.2 "
2463 "NAME 'olcPcacheDatabase' "
2464 "DESC 'Cache database configuration' "
2465 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2470 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2475 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2476 p->ce_bi->bi_cf_ocs != pcocs )
2477 return LDAP_CONSTRAINT_VIOLATION;
2479 on = (slap_overinst *)p->ce_bi;
2480 cm = on->on_bi.bi_private;
2482 return LDAP_SUCCESS;
2486 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2488 CfEntryInfo *pe = p->e_private;
2489 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2490 cache_manager *cm = on->on_bi.bi_private;
2493 /* FIXME: should not hardcode "olcDatabase" here */
2494 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2495 bv.bv_val = ca->cr_msg;
2498 /* We can only create this entry if the database is table-driven
2500 if ( cm->db.bd_info->bi_cf_ocs )
2501 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2508 pc_cf_gen( ConfigArgs *c )
2510 slap_overinst *on = (slap_overinst *)c->bi;
2511 cache_manager* cm = on->on_bi.bi_private;
2512 query_manager* qm = cm->qm;
2513 QueryTemplate* temp;
2514 AttributeName* attr_name;
2515 AttributeName* attrarray;
2516 const char* text=NULL;
2521 if ( c->op == SLAP_CONFIG_EMIT ) {
2525 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2526 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2527 cm->num_entries_limit, cm->cc_period );
2528 bv.bv_val = c->cr_msg;
2529 value_add_one( &c->rvalue_vals, &bv );
2532 for (i=0; i<cm->numattrsets; i++) {
2533 if ( !qm->attr_sets[i].count ) continue;
2535 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2537 /* count the attr length */
2538 for ( attr_name = qm->attr_sets[i].attrs;
2539 attr_name->an_name.bv_val; attr_name++ )
2540 bv.bv_len += attr_name->an_name.bv_len + 1;
2542 bv.bv_val = ch_malloc( bv.bv_len+1 );
2543 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2544 for ( attr_name = qm->attr_sets[i].attrs;
2545 attr_name->an_name.bv_val; attr_name++ ) {
2547 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2549 ber_bvarray_add( &c->rvalue_vals, &bv );
2551 if ( !c->rvalue_vals )
2555 for (temp=qm->templates; temp; temp=temp->qmnext) {
2556 if ( temp->negttl ) {
2557 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2559 temp->attr_set_index,
2563 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2564 temp->attr_set_index,
2567 bv.bv_len += temp->querystr.bv_len + 2;
2568 bv.bv_val = ch_malloc( bv.bv_len+1 );
2571 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2573 strcpy( ptr, c->cr_msg );
2574 ber_bvarray_add( &c->rvalue_vals, &bv );
2576 if ( !c->rvalue_vals )
2580 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2581 BER_BVSTR( &bv, "head" );
2583 BER_BVSTR( &bv, "tail" );
2585 value_add_one( &c->rvalue_vals, &bv );
2588 c->value_int = cm->max_queries;
2592 } else if ( c->op == LDAP_MOD_DELETE ) {
2593 return 1; /* FIXME */
2605 if ( cm->numattrsets > 0 ) {
2606 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2607 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2611 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2612 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2614 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2617 if ( cm->numattrsets <= 0 ) {
2618 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2619 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2622 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2623 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2624 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2628 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2629 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2630 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2634 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2635 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2637 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2640 if ( cm->max_entries <= 0 ) {
2641 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2642 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2646 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2647 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2649 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2652 if ( cm->num_entries_limit <= 0 ) {
2653 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2654 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2657 if ( cm->num_entries_limit > cm->max_entries ) {
2658 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2659 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2663 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2664 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2666 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2669 cm->cc_period = (time_t)t;
2670 Debug( pcache_debug,
2671 "Total # of attribute sets to be cached = %d.\n",
2672 cm->numattrsets, 0, 0 );
2673 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2674 sizeof( struct attr_set ) );
2677 if ( cm->numattrsets == 0 ) {
2678 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2679 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2682 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2683 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2685 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2689 if ( num < 0 || num >= cm->numattrsets ) {
2690 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2691 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2692 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2695 qm->attr_sets[num].flags |= PC_CONFIGURED;
2696 if ( c->argc == 2 ) {
2698 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2699 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2700 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2703 } else if ( c->argc == 3 ) {
2704 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2705 qm->attr_sets[num].count = 1;
2706 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2707 sizeof( AttributeName ) );
2708 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2711 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2712 qm->attr_sets[num].count = 1;
2713 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2714 sizeof( AttributeName ) );
2715 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2718 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2721 /* else: fallthru */
2723 } else if ( c->argc == 4 ) {
2724 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2725 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2727 qm->attr_sets[num].count = 2;
2728 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2729 sizeof( AttributeName ) );
2730 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2731 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2734 /* else: fallthru */
2737 if ( c->argc > 2 ) {
2738 int all_user = 0, all_op = 0;
2740 qm->attr_sets[num].count = c->argc - 2;
2741 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2742 sizeof( AttributeName ) );
2743 attr_name = qm->attr_sets[num].attrs;
2744 for ( i = 2; i < c->argc; i++ ) {
2745 attr_name->an_desc = NULL;
2746 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2747 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2748 "invalid attr #%d \"%s\" in attrlist",
2749 i - 2, c->argv[i] );
2750 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2751 ch_free( qm->attr_sets[num].attrs );
2752 qm->attr_sets[num].attrs = NULL;
2753 qm->attr_sets[num].count = 0;
2756 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2758 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2759 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2761 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2763 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2764 strcpy( c->cr_msg, text );
2765 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2766 ch_free( qm->attr_sets[num].attrs );
2767 qm->attr_sets[num].attrs = NULL;
2768 qm->attr_sets[num].count = 0;
2771 attr_name->an_name = attr_name->an_desc->ad_cname;
2773 attr_name->an_oc = NULL;
2774 attr_name->an_oc_exclude = 0;
2775 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2776 qm->attr_sets[num].flags |= PC_GOT_OC;
2778 BER_BVZERO( &attr_name->an_name );
2781 /* warn if list contains both "*" and "+" */
2782 if ( i > 4 && all_user && all_op ) {
2783 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2784 "warning: attribute list contains \"*\" and \"+\"" );
2785 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2790 if ( cm->numattrsets == 0 ) {
2791 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2792 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2795 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2796 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2798 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2802 if ( i < 0 || i >= cm->numattrsets ||
2803 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2804 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2805 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2806 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2809 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2810 temp->qmnext = qm->templates;
2811 qm->templates = temp;
2812 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2813 temp->query = temp->query_last = NULL;
2814 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2815 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2817 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2820 temp->ttl = (time_t)t;
2821 if ( c->argc == 5 ) {
2822 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2823 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2824 "unable to parse template negttl=\"%s\"",
2826 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2829 temp->negttl = (time_t)t;
2834 temp->no_of_queries = 0;
2836 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2837 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2838 Debug( pcache_debug, " query template: %s\n",
2839 temp->querystr.bv_val, 0, 0 );
2840 temp->attr_set_index = i;
2841 qm->attr_sets[i].flags |= PC_REFERENCED;
2842 temp->qtnext = qm->attr_sets[i].templates;
2843 qm->attr_sets[i].templates = temp;
2844 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2845 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2846 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2847 Debug( pcache_debug, "\t%s\n",
2848 attrarray[i].an_name.bv_val, 0, 0 );
2852 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2853 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2855 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2856 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2859 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2860 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2865 if ( c->value_int <= 0 ) {
2866 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2867 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2870 cm->max_queries = c->value_int;
2885 slap_overinst *on = (slap_overinst *)be->bd_info;
2886 cache_manager* cm = on->on_bi.bi_private;
2888 /* Something for the cache database? */
2889 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2890 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2892 return SLAP_CONF_UNKNOWN;
2900 slap_overinst *on = (slap_overinst *)be->bd_info;
2904 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2905 on->on_bi.bi_private = cm;
2907 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2910 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2911 cm->db.be_private = NULL;
2912 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2914 cm->numattrsets = 0;
2915 cm->num_entries_limit = 5;
2916 cm->num_cached_queries = 0;
2917 cm->max_entries = 0;
2918 cm->cur_entries = 0;
2919 cm->max_queries = 10000;
2920 cm->save_queries = 0;
2921 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2922 cm->cc_period = 1000;
2925 qm->attr_sets = NULL;
2926 qm->templates = NULL;
2928 qm->lru_bottom = NULL;
2930 qm->qcfunc = query_containment;
2931 qm->crfunc = cache_replacement;
2932 qm->addfunc = add_query;
2933 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2935 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2940 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2942 assert( op->o_tag == LDAP_REQ_SEARCH );
2944 if ( rs->sr_type == REP_SEARCH ) {
2947 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2951 assert( a->a_nvals != NULL );
2953 valsp = op->o_callback->sc_private;
2954 assert( *valsp == NULL );
2956 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2964 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
2966 assert( op->o_tag == LDAP_REQ_SEARCH );
2968 if ( rs->sr_type == REP_SEARCH ) {
2969 int *countp = (int *)op->o_callback->sc_private;
2982 slap_overinst *on = (slap_overinst *)be->bd_info;
2983 cache_manager *cm = on->on_bi.bi_private;
2984 query_manager* qm = cm->qm;
2985 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2987 /* check attr sets */
2988 for ( i = 0; i < cm->numattrsets; i++) {
2989 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2990 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2991 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2995 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2999 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3000 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3005 if ( ncf || rf || nrf ) {
3006 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3007 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3008 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3015 /* need to inherit something from the original database... */
3016 cm->db.be_def_limit = be->be_def_limit;
3017 cm->db.be_limits = be->be_limits;
3018 cm->db.be_acl = be->be_acl;
3019 cm->db.be_dfltaccess = be->be_dfltaccess;
3021 if ( SLAP_DBMONITORING( be ) ) {
3022 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3025 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3028 rc = backend_startup_one( &cm->db, NULL );
3030 /* There is no runqueue in TOOL mode */
3031 if ( slapMode & SLAP_SERVER_MODE ) {
3032 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3033 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3034 consistency_check, on,
3035 "pcache_consistency", be->be_suffix[0].bv_val );
3036 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3038 /* Cached database must have the rootdn */
3039 if ( BER_BVISNULL( &cm->db.be_rootndn )
3040 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3042 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3043 "underlying database of type \"%s\"\n"
3044 " serving naming context \"%s\"\n"
3045 " has no \"rootdn\", required by \"proxycache\".\n",
3046 on->on_info->oi_orig->bi_type,
3047 cm->db.be_suffix[0].bv_val, 0 );
3051 if ( cm->save_queries ) {
3052 void *thrctx = ldap_pvt_thread_pool_context();
3053 Connection conn = { 0 };
3054 OperationBuffer opbuf;
3056 slap_callback cb = { 0 };
3057 SlapReply rs = { 0 };
3058 BerVarray vals = NULL;
3059 Filter f = { 0 }, f2 = { 0 };
3060 #ifdef LDAP_COMP_MATCH
3061 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
3063 AttributeAssertion ava = { NULL, BER_BVNULL };
3065 AttributeName attrs[ 2 ] = { 0 };
3067 connection_fake_init( &conn, &opbuf, thrctx );
3072 op->o_tag = LDAP_REQ_SEARCH;
3073 op->o_protocol = LDAP_VERSION3;
3074 cb.sc_response = pcache_cachedquery_open_cb;
3075 cb.sc_private = &vals;
3076 op->o_callback = &cb;
3077 op->o_time = slap_get_time();
3078 op->o_do_not_cache = 1;
3079 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3081 op->o_dn = cm->db.be_rootdn;
3082 op->o_ndn = cm->db.be_rootndn;
3083 op->o_req_dn = cm->db.be_suffix[ 0 ];
3084 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3086 op->ors_scope = LDAP_SCOPE_BASE;
3087 op->ors_deref = LDAP_DEREF_NEVER;
3089 op->ors_tlimit = SLAP_NO_LIMIT;
3090 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3091 f.f_choice = LDAP_FILTER_PRESENT;
3092 f.f_desc = ad_cachedQueryURL;
3093 op->ors_filter = &f;
3094 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3095 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3096 op->ors_attrs = attrs;
3097 op->ors_attrsonly = 0;
3099 rc = op->o_bd->be_search( op, &rs );
3100 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3103 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3104 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3105 cm->num_cached_queries++;
3109 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3112 /* count cached entries */
3113 f.f_choice = LDAP_FILTER_NOT;
3115 f2.f_choice = LDAP_FILTER_EQUALITY;
3117 f2.f_av_desc = slap_schema.si_ad_objectClass;
3118 BER_BVSTR( &f2.f_av_value, "glue" );
3119 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3121 op->ors_slimit = SLAP_NO_LIMIT;
3122 op->ors_scope = LDAP_SCOPE_SUBTREE;
3123 op->ors_attrs = slap_anlist_no_attrs;
3125 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3127 op->o_callback->sc_private = &rs.sr_nentries;
3129 rc = op->o_bd->be_search( op, &rs );
3131 cm->cur_entries = rs.sr_nentries;
3142 pcache_free_qbase( void *v )
3148 tavl_free( qb->scopes[i], NULL );
3158 slap_overinst *on = (slap_overinst *)be->bd_info;
3159 cache_manager *cm = on->on_bi.bi_private;
3160 query_manager *qm = cm->qm;
3164 if ( cm->save_queries ) {
3166 BerVarray vals = NULL;
3169 Connection conn = { 0 };
3170 OperationBuffer opbuf;
3172 slap_callback cb = { 0 };
3174 SlapReply rs = { REP_RESULT };
3175 Modifications mod = { 0 };
3177 thrctx = ldap_pvt_thread_pool_context();
3179 connection_fake_init( &conn, &opbuf, thrctx );
3182 if ( qm->templates != NULL ) {
3183 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3184 for ( qc = tm->query; qc; qc = qc->next ) {
3187 if ( query2url( op, qc, &bv ) == 0 ) {
3188 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3195 op->o_dn = cm->db.be_rootdn;
3196 op->o_ndn = cm->db.be_rootndn;
3198 op->o_tag = LDAP_REQ_MODIFY;
3199 op->o_protocol = LDAP_VERSION3;
3200 cb.sc_response = slap_null_cb;
3201 op->o_callback = &cb;
3202 op->o_time = slap_get_time();
3203 op->o_do_not_cache = 1;
3204 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3206 op->o_req_dn = op->o_bd->be_suffix[0];
3207 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3209 mod.sml_op = LDAP_MOD_REPLACE;
3211 mod.sml_desc = ad_cachedQueryURL;
3212 mod.sml_type = ad_cachedQueryURL->ad_cname;
3213 mod.sml_values = vals;
3214 mod.sml_nvalues = NULL;
3215 mod.sml_next = NULL;
3216 Debug( pcache_debug,
3217 "%sSETTING CACHED QUERY URLS\n",
3218 vals == NULL ? "RE" : "", 0, 0 );
3220 op->orm_modlist = &mod;
3222 op->o_bd->be_modify( op, &rs );
3224 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3227 /* cleanup stuff inherited from the original database... */
3228 cm->db.be_limits = NULL;
3229 cm->db.be_acl = NULL;
3231 /* stop the thread ... */
3233 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3234 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3235 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3237 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3238 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3241 if ( cm->db.bd_info->bi_db_close ) {
3242 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3244 while ( (tm = qm->templates) != NULL ) {
3245 CachedQuery *qc, *qn;
3246 qm->templates = tm->qmnext;
3247 for ( qc = tm->query; qc; qc = qn ) {
3251 avl_free( tm->qbase, pcache_free_qbase );
3252 free( tm->querystr.bv_val );
3253 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3254 free( tm->t_attrs.attrs );
3258 for ( i=0; i<cm->numattrsets; i++ ) {
3259 free( qm->attr_sets[i].attrs );
3261 free( qm->attr_sets );
3262 qm->attr_sets = NULL;
3273 slap_overinst *on = (slap_overinst *)be->bd_info;
3274 cache_manager *cm = on->on_bi.bi_private;
3275 query_manager *qm = cm->qm;
3277 if ( cm->db.be_private != NULL ) {
3278 backend_stopdown_one( &cm->db );
3281 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3282 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3289 #ifdef PCACHE_CONTROL_PRIVDB
3291 Control ::= SEQUENCE {
3292 controlType LDAPOID,
3293 criticality BOOLEAN DEFAULT FALSE,
3294 controlValue OCTET STRING OPTIONAL }
3296 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3298 * criticality must be TRUE; controlValue must be absent.
3306 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3307 rs->sr_text = "privateDB control specified multiple times";
3308 return LDAP_PROTOCOL_ERROR;
3311 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3312 rs->sr_text = "privateDB control value not absent";
3313 return LDAP_PROTOCOL_ERROR;
3316 if ( !ctrl->ldctl_iscritical ) {
3317 rs->sr_text = "privateDB control criticality required";
3318 return LDAP_PROTOCOL_ERROR;
3321 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3323 return LDAP_SUCCESS;
3326 static char *extops[] = {
3327 LDAP_EXOP_MODIFY_PASSWD,
3330 #endif /* PCACHE_CONTROL_PRIVDB */
3332 #ifdef PCACHE_EXOP_QUERY_DELETE
3333 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3335 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3336 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3337 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3340 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3341 requestName [0] LDAPOID,
3342 requestValue [1] OCTET STRING OPTIONAL }
3344 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3346 requestValue ::= SEQUENCE { CHOICE {
3348 entryDN [1] LDAPDN },
3349 queryID [2] OCTET STRING (SIZE(16))
3350 -- constrained to UUID }
3352 * Either baseDN or entryDN must be present, to allow database selection.
3354 * 1. if baseDN and queryID are present, then the query corresponding
3355 * to queryID is deleted;
3356 * 2. if baseDN is present and queryID is absent, then all queries
3358 * 3. if entryDN is present and queryID is absent, then all queries
3359 * corresponding to the queryID values present in entryDN are deleted;
3360 * 4. if entryDN and queryID are present, then all queries
3361 * corresponding to the queryID values present in entryDN are deleted,
3362 * but only if the value of queryID is contained in the entry;
3364 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3365 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3366 * or by removing the database files.
3368 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3369 COMPONENTS OF LDAPResult,
3370 responseName [10] LDAPOID OPTIONAL,
3371 responseValue [11] OCTET STRING OPTIONAL }
3373 * responseName and responseValue must be absent.
3377 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3378 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3379 * - if ndn != NULL, it is set to the normalized DN in the request
3380 * corresponding to either the baseDN or the entryDN, according
3381 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3382 * be freed by the caller.
3383 * - if uuid != NULL, it is set to point to the normalized UUID;
3384 * memory is malloc'ed on the Operation's slab, and must
3385 * be freed by the caller.
3388 pcache_parse_query_delete(
3392 struct berval *uuid,
3396 int rc = LDAP_SUCCESS;
3399 BerElementBuffer berbuf;
3400 BerElement *ber = (BerElement *)&berbuf;
3401 struct berval reqdata = BER_BVNULL;
3413 if ( in == NULL || in->bv_len == 0 ) {
3414 *text = "empty request data field in queryDelete exop";
3415 return LDAP_PROTOCOL_ERROR;
3418 ber_dupbv_x( &reqdata, in, ctx );
3420 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3421 ber_init2( ber, &reqdata, 0 );
3423 tag = ber_scanf( ber, "{" /*}*/ );
3425 if ( tag == LBER_ERROR ) {
3426 Debug( LDAP_DEBUG_TRACE,
3427 "pcache_parse_query_delete: decoding error.\n",
3429 goto decoding_error;
3432 tag = ber_peek_tag( ber, &len );
3433 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3434 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3438 if ( ndn != NULL ) {
3441 tag = ber_scanf( ber, "m", &dn );
3442 if ( tag == LBER_ERROR ) {
3443 Debug( LDAP_DEBUG_TRACE,
3444 "pcache_parse_query_delete: DN parse failed.\n",
3446 goto decoding_error;
3449 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3450 if ( rc != LDAP_SUCCESS ) {
3451 *text = "invalid DN in queryDelete exop request data";
3456 tag = ber_scanf( ber, "x" /* "m" */ );
3457 if ( tag == LBER_DEFAULT ) {
3458 goto decoding_error;
3462 tag = ber_peek_tag( ber, &len );
3465 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3466 if ( uuid != NULL ) {
3468 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3470 tag = ber_scanf( ber, "m", &bv );
3471 if ( tag == LBER_ERROR ) {
3472 Debug( LDAP_DEBUG_TRACE,
3473 "pcache_parse_query_delete: UUID parse failed.\n",
3475 goto decoding_error;
3478 if ( bv.bv_len != 16 ) {
3479 Debug( LDAP_DEBUG_TRACE,
3480 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3481 (unsigned long)bv.bv_len, 0, 0 );
3482 goto decoding_error;
3485 rc = lutil_uuidstr_from_normalized(
3486 bv.bv_val, bv.bv_len,
3487 uuidbuf, sizeof( uuidbuf ) );
3489 goto decoding_error;
3491 ber_str2bv( uuidbuf, rc, 1, uuid );
3495 tag = ber_skip_tag( ber, &len );
3496 if ( tag == LBER_DEFAULT ) {
3497 goto decoding_error;
3501 Debug( LDAP_DEBUG_TRACE,
3502 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3503 (unsigned long)len, 0, 0 );
3504 goto decoding_error;
3508 tag = ber_peek_tag( ber, &len );
3511 if ( tag != LBER_DEFAULT || len != 0 ) {
3513 Debug( LDAP_DEBUG_TRACE,
3514 "pcache_parse_query_delete: decoding error\n",
3516 rc = LDAP_PROTOCOL_ERROR;
3517 *text = "queryDelete data decoding error";
3520 if ( ndn && !BER_BVISNULL( ndn ) ) {
3521 slap_sl_free( ndn->bv_val, ctx );
3525 if ( uuid && !BER_BVISNULL( uuid ) ) {
3526 slap_sl_free( uuid->bv_val, ctx );
3531 if ( !BER_BVISNULL( &reqdata ) ) {
3532 ber_memfree_x( reqdata.bv_val, ctx );
3539 pcache_exop_query_delete(
3543 BackendDB *bd = op->o_bd;
3545 struct berval uuid = BER_BVNULL,
3547 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3549 ber_tag_t tag = LBER_DEFAULT;
3551 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3555 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3556 &tag, &op->o_req_ndn, uuidp,
3557 &rs->sr_text, op->o_tmpmemctx );
3558 if ( rs->sr_err != LDAP_SUCCESS ) {
3562 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3563 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3564 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3566 if ( !BER_BVISNULL( &uuid ) ) {
3567 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3570 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3571 op->o_log_prefix, buf, 0 );
3573 op->o_req_dn = op->o_req_ndn;
3575 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3576 rs->sr_err = backend_check_restrictions( op, rs,
3577 (struct berval *)&pcache_exop_QUERY_DELETE );
3578 if ( rs->sr_err != LDAP_SUCCESS ) {
3582 if ( op->o_bd->be_extended == NULL ) {
3583 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3584 "backend does not support extended operations" );
3588 op->o_bd->be_extended( op, rs );
3591 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3592 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3593 BER_BVZERO( &op->o_req_ndn );
3594 BER_BVZERO( &op->o_req_dn );
3597 if ( !BER_BVISNULL( &uuid ) ) {
3598 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3607 pcache_op_extended( Operation *op, SlapReply *rs )
3609 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3610 cache_manager *cm = on->on_bi.bi_private;
3612 #ifdef PCACHE_CONTROL_PRIVDB
3613 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3614 return pcache_op_privdb( op, rs );
3616 #endif /* PCACHE_CONTROL_PRIVDB */
3618 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3619 struct berval uuid = BER_BVNULL;
3620 ber_tag_t tag = LBER_DEFAULT;
3622 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3623 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3624 assert( rs->sr_err == LDAP_SUCCESS );
3626 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3627 /* remove all queries related to the selected entry */
3628 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3629 cm, &op->o_req_ndn, &uuid );
3631 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3632 if ( !BER_BVISNULL( &uuid ) ) {
3633 Operation op2 = *op;
3634 SlapReply rs2 = { 0 };
3638 /* remove the selected query */
3639 remove_query_and_data( &op2, &rs2, cm, &uuid );
3641 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3642 rs->sr_err = LDAP_SUCCESS;
3645 /* TODO: remove all queries */
3646 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3647 rs->sr_text = "deletion of all queries not implemented";
3654 #endif /* PCACHE_EXOP_QUERY_DELETE */
3656 static slap_overinst pcache;
3658 static char *obsolete_names[] = {
3663 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3665 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3670 struct berval debugbv = BER_BVC("pcache");
3672 code = slap_loglevel_get( &debugbv, &pcache_debug );
3677 #ifdef PCACHE_CONTROL_PRIVDB
3678 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3679 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3680 parse_privdb_ctrl, &privDB_cid );
3681 if ( code != LDAP_SUCCESS ) {
3682 Debug( LDAP_DEBUG_ANY,
3683 "pcache_initialize: failed to register control %s (%d)\n",
3684 PCACHE_CONTROL_PRIVDB, code, 0 );
3687 #endif /* PCACHE_CONTROL_PRIVDB */
3689 #ifdef PCACHE_EXOP_QUERY_DELETE
3690 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3691 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3693 if ( code != LDAP_SUCCESS ) {
3694 Debug( LDAP_DEBUG_ANY,
3695 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3699 #endif /* PCACHE_EXOP_QUERY_DELETE */
3701 for ( i = 0; as[i].desc != NULL; i++ ) {
3702 code = register_at( as[i].desc, as[i].adp, 0 );
3704 Debug( LDAP_DEBUG_ANY,
3705 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3710 pcache.on_bi.bi_type = "pcache";
3711 pcache.on_bi.bi_obsolete_names = obsolete_names;
3712 pcache.on_bi.bi_db_init = pcache_db_init;
3713 pcache.on_bi.bi_db_config = pcache_db_config;
3714 pcache.on_bi.bi_db_open = pcache_db_open;
3715 pcache.on_bi.bi_db_close = pcache_db_close;
3716 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3718 pcache.on_bi.bi_op_search = pcache_op_search;
3719 #ifdef PCACHE_CONTROL_PRIVDB
3720 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3721 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3722 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3723 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3724 pcache.on_bi.bi_op_add = pcache_op_privdb;
3725 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3726 #endif /* PCACHE_CONTROL_PRIVDB */
3727 #ifdef PCACHE_EXOP_QUERY_DELETE
3728 pcache.on_bi.bi_extended = pcache_op_extended;
3729 #elif defined( PCACHE_CONTROL_PRIVDB )
3730 pcache.on_bi.bi_extended = pcache_op_privdb;
3733 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3735 pcache.on_bi.bi_cf_ocs = pcocs;
3737 code = config_register_schema( pccfg, pcocs );
3738 if ( code ) return code;
3740 return overlay_register( &pcache );
3743 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3744 int init_module(int argc, char *argv[]) {
3745 return pcache_initialize();
3749 #endif /* defined(SLAPD_OVER_PROXYCACHE) */