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>
38 /* query cache structs */
41 typedef struct Query_s {
42 Filter* filter; /* Search Filter */
43 struct berval base; /* Search Base */
44 int scope; /* Search scope */
47 struct query_template_s;
49 typedef struct Qbase_s {
50 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
55 /* struct representing a cached query */
56 typedef struct cached_query_s {
61 struct berval q_uuid; /* query identifier */
62 struct query_template_s *qtemp; /* template of the query */
63 time_t expiry_time; /* time till the query is considered valid */
64 struct cached_query_s *next; /* next query in the template */
65 struct cached_query_s *prev; /* previous query in the template */
66 struct cached_query_s *lru_up; /* previous query in the LRU list */
67 struct cached_query_s *lru_down; /* next query in the LRU list */
73 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
75 * <base> ::= CachedQuery.qbase->base
76 * <scope> ::= CachedQuery.scope
77 * <filter> ::= filter2bv(CachedQuery.filter)
78 * <uuid> ::= CachedQuery.q_uuid
79 * <template> ::= CachedQuery.qtemp->querystr [FIXME: better give it an ID?]
80 * <attrset> ::= CachedQuery.qtemp->attr_set_index [FIXME: better give it an ID?]
81 * <expiry> ::= CachedQuery.expiry_time
83 * quick hack: parse URI, call add_query() and then fix
84 * CachedQuery.expiry_time and CachedQuery.q_uuid
88 * Represents a set of projected attributes.
92 struct query_template_s *templates;
93 AttributeName* attrs; /* specifies the set */
95 #define PC_CONFIGURED (0x1)
96 #define PC_REFERENCED (0x2)
97 #define PC_GOT_OC (0x4)
98 int count; /* number of attributes */
101 /* struct representing a query template
102 * e.g. template string = &(cn=)(mail=)
104 typedef struct query_template_s {
105 struct query_template_s *qtnext;
106 struct query_template_s *qmnext;
109 CachedQuery* query; /* most recent query cached for the template */
110 CachedQuery* query_last; /* oldest query cached for the template */
111 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
112 struct berval querystr; /* Filter string corresponding to the QT */
114 int attr_set_index; /* determines the projected attributes */
115 int no_of_queries; /* Total number of queries in the template */
116 time_t ttl; /* TTL for the queries of this template */
117 time_t negttl; /* TTL for negative results */
118 struct attr_set t_attrs; /* filter attrs + attr_set */
121 struct query_manager_s;
123 /* prototypes for functions for 1) query containment
124 * 2) query addition, 3) cache replacement
126 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
127 typedef CachedQuery * (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
128 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
130 /* LDAP query cache */
131 typedef struct query_manager_s {
132 struct attr_set* attr_sets; /* possible sets of projected attributes */
133 QueryTemplate* templates; /* cacheable templates */
135 CachedQuery* lru_top; /* top and bottom of LRU list */
136 CachedQuery* lru_bottom;
138 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
140 /* Query cache methods */
141 QCfunc *qcfunc; /* Query containment*/
142 CRfunc *crfunc; /* cache replacement */
143 AddQueryfunc *addfunc; /* add query */
146 /* LDAP query cache manager */
147 typedef struct cache_manager_s {
148 BackendDB db; /* underlying database */
149 unsigned long num_cached_queries; /* total number of cached queries */
150 unsigned long max_queries; /* upper bound on # of cached queries */
151 int save_queries; /* save cached queries across restarts */
152 int numattrsets; /* number of attribute sets */
153 int cur_entries; /* current number of entries cached */
154 int max_entries; /* max number of entries cached */
155 int num_entries_limit; /* max # of entries in a cacheable query */
157 char response_cb; /* install the response callback
158 * at the tail of the callback list */
159 #define PCACHE_RESPONSE_CB_HEAD 0
160 #define PCACHE_RESPONSE_CB_TAIL 1
162 time_t cc_period; /* interval between successive consistency checks (sec) */
166 ldap_pvt_thread_mutex_t cache_mutex;
168 query_manager* qm; /* query cache managed by the cache manager */
171 static int pcache_debug;
173 static AttributeDescription *ad_queryid, *ad_cachedQueryURL;
176 AttributeDescription **adp;
178 { "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
179 "DESC 'list of queries the entry belongs to' "
180 "EQUALITY octetStringMatch "
181 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
182 "NO-USER-MODIFICATION USAGE directoryOperation )",
184 { "(1.3.6.1.4.1.4203.666.1.999999 NAME 'cachedQueryURL' "
185 "DESC 'URI describing a cached query' "
186 "EQUALITY caseExactMatch "
187 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
188 "NO-USER-MODIFICATION USAGE directoryOperation )",
189 &ad_cachedQueryURL },
198 AttributeName** filter_attrs,
200 int* filter_got_oc );
207 QueryTemplate *templ,
211 * Turn a cached query into its URL representation
214 query2url( CachedQuery *q, struct berval *urlbv )
216 struct berval bv_scope,
218 char attrset_buf[ 32 ],
221 ber_len_t attrset_len,
224 ldap_pvt_scope2bv( q->scope, &bv_scope );
225 filter2bv( q->filter, &bv_filter );
226 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
227 "%lu", (unsigned long)q->qtemp->attr_set_index );
228 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
229 "%lu", (unsigned long)q->expiry_time );
231 urlbv->bv_len = STRLENOF( "ldap:///" )
232 + q->qbase->base.bv_len
237 + STRLENOF( "?x-uuid=" )
239 + STRLENOF( ",x-attrset=" )
241 + STRLENOF( ",x-expiry=" )
243 ptr = urlbv->bv_val = ch_malloc( urlbv->bv_len + 1 );
244 ptr = lutil_strcopy( ptr, "ldap:///" );
245 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
246 ptr = lutil_strcopy( ptr, "??" );
247 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
248 ptr = lutil_strcopy( ptr, "?" );
249 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
250 ptr = lutil_strcopy( ptr, "?x-uuid=" );
251 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
252 ptr = lutil_strcopy( ptr, ",x-attrset=" );
253 ptr = lutil_strcopy( ptr, attrset_buf );
254 ptr = lutil_strcopy( ptr, ",x-expiry=" );
255 ptr = lutil_strcopy( ptr, expiry_buf );
257 ber_memfree( bv_filter.bv_val );
262 static Syntax *syn_UUID;
265 * Turn an URL representing a formerly cached query into a cached query,
266 * and try to cache it
277 LDAPURLDesc *lud = NULL;
279 tempstr = BER_BVNULL,
289 rc = ldap_url_parse( url, &lud );
290 if ( rc != LDAP_URL_SUCCESS ) {
294 /* non-allowed fields */
295 if ( lud->lud_host != NULL ) {
300 if ( lud->lud_attrs != NULL ) {
306 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
311 /* required fields */
312 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
317 switch ( lud->lud_scope ) {
318 case LDAP_SCOPE_BASE:
319 case LDAP_SCOPE_ONELEVEL:
320 case LDAP_SCOPE_SUBTREE:
321 case LDAP_SCOPE_SUBORDINATE:
329 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
334 if ( lud->lud_exts == NULL ) {
339 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
340 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
341 struct berval tmpUUID;
342 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
343 assert( syn_UUID->ssyn_pretty != NULL );
344 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
345 if ( rc != LDAP_SUCCESS ) {
350 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
351 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
357 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
360 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
364 expiry_time = (time_t)l;
367 /* ignore expired queries */
368 if ( expiry_time <= slap_get_time()) {
384 if ( !got_attrset ) {
394 ber_str2bv( lud->lud_dn, 0, 0, &base );
395 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
396 if ( rc != LDAP_SUCCESS ) {
399 query.scope = lud->lud_scope;
400 query.filter = str2filter( lud->lud_filter );
402 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
404 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
405 ch_free( tempstr.bv_val );
410 /* check for query containment */
411 qt = qm->attr_sets[attrset].templates;
412 for ( ; qt; qt = qt->qtnext ) {
413 /* find if template i can potentially answer tempstr */
414 if ( bvmatch( &qt->querystr, &tempstr ) ) {
425 cq = add_query( op, qm, &query, qt, 1 );
427 cq->expiry_time = expiry_time;
430 /* it's now into cq->filter */
439 if ( query.filter != NULL ) filter_free( query.filter );
440 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
441 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
442 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
443 if ( lud != NULL ) ldap_free_urldesc( lud );
448 /* Return 1 for an added entry, else 0 */
453 struct berval* query_uuid )
456 Modifications* modlist = NULL;
457 const char* text = NULL;
459 char textbuf[SLAP_TEXT_BUFLEN];
460 size_t textlen = sizeof(textbuf);
462 SlapReply sreply = {REP_RESULT};
464 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
469 /* add queryid attribute */
470 attr_merge_one( e, ad_queryid, query_uuid, NULL );
472 /* append the attribute list from the fetched entry */
473 e->e_attrs->a_next = attr;
475 op->o_tag = LDAP_REQ_ADD;
476 op->o_protocol = LDAP_VERSION3;
477 op->o_callback = &cb;
478 op->o_time = slap_get_time();
479 op->o_do_not_cache = 1;
482 op->o_req_dn = e->e_name;
483 op->o_req_ndn = e->e_nname;
484 rc = op->o_bd->be_add( op, &sreply );
486 if ( rc != LDAP_SUCCESS ) {
487 if ( rc == LDAP_ALREADY_EXISTS ) {
488 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
489 modlist->sml_op = LDAP_MOD_ADD;
490 op->o_tag = LDAP_REQ_MODIFY;
491 op->orm_modlist = modlist;
492 op->o_bd->be_modify( op, &sreply );
493 slap_mods_free( modlist, 1 );
494 } else if ( rc == LDAP_REFERRAL ||
495 rc == LDAP_NO_SUCH_OBJECT ) {
496 syncrepl_add_glue( op, e );
505 if ( op->ora_e == e )
506 be_entry_release_w( op, e );
513 /* Length-ordered sort on normalized DNs */
514 static int pcache_dn_cmp( const void *v1, const void *v2 )
516 const Qbase *q1 = v1, *q2 = v2;
518 int rc = q1->base.bv_len - q2->base.bv_len;
520 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
524 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
527 dif = bv1->bv_len - bv2->bv_len;
529 if ( dif > 0 ) len -= dif;
530 len = memcmp( bv1->bv_val, bv2->bv_val, len );
536 /* compare the first value in each filter */
537 static int pcache_filter_cmp( const void *v1, const void *v2 )
539 const CachedQuery *q1 = v1, *q2 =v2;
540 int rc, weight1, weight2;
542 switch( q1->first->f_choice ) {
543 case LDAP_FILTER_PRESENT:
546 case LDAP_FILTER_EQUALITY:
554 switch( q2->first->f_choice ) {
555 case LDAP_FILTER_PRESENT:
558 case LDAP_FILTER_EQUALITY:
566 rc = weight1 - weight2;
571 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
574 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
576 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
577 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
578 rc = lex_bvcmp( &q1->first->f_sub_initial,
579 &q2->first->f_sub_initial );
583 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
587 if ( q1->first->f_sub_any ) {
588 if ( q2->first->f_sub_any ) {
589 rc = lex_bvcmp( q1->first->f_sub_any,
590 q2->first->f_sub_any );
594 } else if ( q2->first->f_sub_any ) {
598 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
599 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
600 rc = lex_bvcmp( &q1->first->f_sub_final,
601 &q2->first->f_sub_final );
605 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
609 rc = lex_bvcmp( &q1->first->f_mr_value,
610 &q2->first->f_mr_value );
619 /* add query on top of LRU list */
621 add_query_on_top (query_manager* qm, CachedQuery* qc)
623 CachedQuery* top = qm->lru_top;
634 Debug( pcache_debug, "Base of added query = %s\n",
635 qc->qbase->base.bv_val, 0, 0 );
638 /* remove_query from LRU list */
641 remove_query (query_manager* qm, CachedQuery* qc)
664 qc->lru_up = qc->lru_down = NULL;
667 /* find and remove string2 from string1
668 * from start if position = 1,
669 * from end if position = 3,
670 * from anywhere if position = 2
671 * string1 is overwritten if position = 2.
675 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
686 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
687 ber2->bv_val, ber2->bv_len )) {
689 ber1->bv_val += ber2->bv_len;
690 ber1->bv_len -= ber2->bv_len;
695 ber1->bv_val[ber1->bv_len] = '\0';
696 temp = strstr( ber1->bv_val, ber2->bv_val );
698 strcpy( temp, temp+ber2->bv_len );
699 ber1->bv_len -= ber2->bv_len;
705 if ( ber1->bv_len >= ber2->bv_len &&
706 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
709 ber1->bv_len -= ber2->bv_len;
717 static struct berval*
718 merge_init_final(Operation *op, struct berval* init, struct berval* any,
719 struct berval* final)
721 struct berval* merged, *temp;
722 int i, any_count, count;
724 for (any_count=0; any && any[any_count].bv_val; any_count++)
734 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
739 ber_dupbv_x( temp, init, op->o_tmpmemctx );
743 for (i=0; i<any_count; i++) {
744 ber_dupbv_x( temp, any, op->o_tmpmemctx );
749 ber_dupbv_x( temp, final, op->o_tmpmemctx );
756 /* Each element in stored must be found in incoming. Incoming is overwritten.
759 strings_containment(struct berval* stored, struct berval* incoming)
761 struct berval* element;
765 for ( element=stored; element->bv_val != NULL; element++ ) {
766 for (j = k; incoming[j].bv_val != NULL; j++) {
767 if (find_and_remove(&(incoming[j]), element, 2)) {
784 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
788 struct berval init_incoming;
789 struct berval final_incoming;
790 struct berval *remaining_incoming = NULL;
792 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
793 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
796 init_incoming = incoming->f_sub_initial;
797 final_incoming = incoming->f_sub_final;
799 if (find_and_remove(&init_incoming,
800 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
801 &(stored->f_sub_final), 3))
803 if (stored->f_sub_any == NULL) {
807 remaining_incoming = merge_init_final(op, &init_incoming,
808 incoming->f_sub_any, &final_incoming);
809 rc = strings_containment(stored->f_sub_any, remaining_incoming);
810 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
817 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
819 struct berval incoming_val[2];
822 incoming_val[1] = incoming->f_av_value;
824 if (find_and_remove(incoming_val+1,
825 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
826 &(stored->f_sub_final), 3)) {
827 if (stored->f_sub_any == NULL){
831 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
832 BER_BVZERO( incoming_val+1 );
833 rc = strings_containment(stored->f_sub_any, incoming_val);
834 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
841 filter_first( Filter *f )
843 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
850 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
854 MatchingRule* mrule = NULL;
855 int res=0, eqpass= 0;
863 /* substring matches sort to the end, and we just have to
864 * walk the entire list.
866 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
867 ptr = tavl_end( root, 1 );
870 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
871 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
880 /* an incoming substr query can only be satisfied by a cached
883 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
884 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
887 /* an incoming eq query can be satisfied by a cached eq or substr
890 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
892 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
893 nextpass: eqpass = 1;
894 ptr = tavl_end( root, 1 );
899 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
905 switch (fs->f_choice) {
906 case LDAP_FILTER_EQUALITY:
907 if (fi->f_choice == LDAP_FILTER_EQUALITY)
908 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
914 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
921 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
922 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
923 &(fi->f_ava->aa_value),
924 &(fs->f_ava->aa_value), &text);
925 if (rc != LDAP_SUCCESS) {
928 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
931 switch (fs->f_choice) {
933 case LDAP_FILTER_AND:
938 case LDAP_FILTER_SUBSTRINGS:
939 /* check if the equality query can be
940 * answered with cached substring query */
941 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
942 && substr_containment_equality( op,
945 /* check if the substring query can be
946 * answered with cached substring query */
947 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
948 ) && substr_containment_substr( op,
954 case LDAP_FILTER_PRESENT:
959 case LDAP_FILTER_EQUALITY:
966 if (mrule && ret >= 0)
972 if (mrule && ret <= 0)
977 case LDAP_FILTER_NOT:
983 } while((res) && (fi != NULL) && (fs != NULL));
987 ptr = tavl_next( ptr, dir );
992 /* check whether query is contained in any of
993 * the cached queries in template
996 query_containment(Operation *op, query_manager *qm,
998 QueryTemplate *templa)
1001 int depth = 0, tscope;
1002 Qbase qbase, *qbptr = NULL;
1005 if (query->filter != NULL) {
1008 Debug( pcache_debug, "Lock QC index = %p\n",
1009 (void *) templa, 0, 0 );
1010 qbase.base = query->base;
1012 first = filter_first( query->filter );
1014 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1017 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1019 tscope = query->scope;
1020 /* Find a matching scope:
1021 * match at depth 0 OK
1024 * subord at depth > 0 OK
1025 * subtree at any depth OK
1027 * subtree or subord at any depth OK
1029 * subtree or subord at any depth OK
1031 * subord at depth > 0 OK
1032 * subtree at any depth OK
1034 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1035 switch ( query->scope ) {
1036 case LDAP_SCOPE_BASE:
1037 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1038 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1039 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1041 case LDAP_SCOPE_ONE:
1042 if ( tscope == LDAP_SCOPE_BASE )
1043 tscope = LDAP_SCOPE_ONE;
1044 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1045 if ( !depth ) break;
1046 if ( tscope < LDAP_SCOPE_SUBTREE )
1047 tscope = LDAP_SCOPE_SUBTREE;
1049 case LDAP_SCOPE_SUBTREE:
1050 if ( tscope < LDAP_SCOPE_SUBTREE )
1051 tscope = LDAP_SCOPE_SUBTREE;
1052 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1054 case LDAP_SCOPE_CHILDREN:
1055 if ( tscope < LDAP_SCOPE_SUBTREE )
1056 tscope = LDAP_SCOPE_SUBTREE;
1059 if ( !qbptr->scopes[tscope] ) continue;
1062 qc = find_filter( op, qbptr->scopes[tscope],
1063 query->filter, first );
1065 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1066 if (qm->lru_top != qc) {
1067 remove_query(qm, qc);
1068 add_query_on_top(qm, qc);
1070 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1075 if ( be_issuffix( op->o_bd, &qbase.base ))
1078 dnParent( &qbase.base, &pdn );
1083 Debug( pcache_debug,
1084 "Not answerable: Unlock QC index=%p\n",
1085 (void *) templa, 0, 0 );
1086 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1092 free_query (CachedQuery* qc)
1094 free(qc->q_uuid.bv_val);
1095 filter_free(qc->filter);
1100 /* Add query to query cache */
1101 static CachedQuery *
1106 QueryTemplate *templ,
1109 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1114 new_cached_query->qtemp = templ;
1115 BER_BVZERO( &new_cached_query->q_uuid );
1117 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1119 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1121 new_cached_query->lru_up = NULL;
1122 new_cached_query->lru_down = NULL;
1123 Debug( pcache_debug, "Added query expires at %ld\n",
1124 (long) new_cached_query->expiry_time, 0, 0 );
1126 new_cached_query->scope = query->scope;
1127 new_cached_query->filter = query->filter;
1128 new_cached_query->first = first = filter_first( query->filter );
1130 qb.base = query->base;
1132 /* Adding a query */
1133 Debug( pcache_debug, "Lock AQ index = %p\n",
1134 (void *) templ, 0, 0 );
1135 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1136 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1138 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1139 qbase->base.bv_len = qb.base.bv_len;
1140 qbase->base.bv_val = (char *)(qbase+1);
1141 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1142 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1143 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1145 new_cached_query->next = templ->query;
1146 new_cached_query->prev = NULL;
1147 new_cached_query->qbase = qbase;
1148 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1149 pcache_filter_cmp, avl_dup_error );
1152 if (templ->query == NULL)
1153 templ->query_last = new_cached_query;
1155 templ->query->prev = new_cached_query;
1156 templ->query = new_cached_query;
1157 templ->no_of_queries++;
1159 ch_free( new_cached_query );
1160 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1161 query->filter, first );
1162 filter_free( query->filter );
1164 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1165 (void *) templ, templ->no_of_queries, 0 );
1167 Debug( pcache_debug, "Unlock AQ index = %p \n",
1168 (void *) templ, 0, 0 );
1169 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1171 /* Adding on top of LRU list */
1173 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1174 add_query_on_top(qm, new_cached_query);
1175 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1177 return rc == 0 ? new_cached_query : NULL;
1181 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1183 if (!qc->prev && !qc->next) {
1184 template->query_last = template->query = NULL;
1185 } else if (qc->prev == NULL) {
1186 qc->next->prev = NULL;
1187 template->query = qc->next;
1188 } else if (qc->next == NULL) {
1189 qc->prev->next = NULL;
1190 template->query_last = qc->prev;
1192 qc->next->prev = qc->prev;
1193 qc->prev->next = qc->next;
1195 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1196 qc->qbase->queries--;
1197 if ( qc->qbase->queries == 0 ) {
1198 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1199 ch_free( qc->qbase );
1203 template->no_of_queries--;
1206 /* remove bottom query of LRU list from the query cache */
1208 * NOTE: slight change in functionality.
1210 * - if result->bv_val is NULL, the query at the bottom of the LRU
1212 * - otherwise, the query whose UUID is *result is removed
1213 * - if not found, result->bv_val is zeroed
1216 cache_replacement(query_manager* qm, struct berval *result)
1218 CachedQuery* bottom;
1219 QueryTemplate *temp;
1221 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1222 if ( BER_BVISNULL( result ) ) {
1223 bottom = qm->lru_bottom;
1226 Debug ( pcache_debug,
1227 "Cache replacement invoked without "
1228 "any query in LRU list\n", 0, 0, 0 );
1229 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1234 for ( bottom = qm->lru_bottom;
1236 bottom = bottom->lru_up )
1238 if ( bvmatch( result, &bottom->q_uuid ) ) {
1244 Debug ( pcache_debug,
1245 "Could not find query with uuid=\"%s\""
1246 "in LRU list\n", result->bv_val, 0, 0 );
1247 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1248 BER_BVZERO( result );
1253 temp = bottom->qtemp;
1254 remove_query(qm, bottom);
1255 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1257 *result = bottom->q_uuid;
1258 bottom->q_uuid.bv_val = NULL;
1260 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1261 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1262 remove_from_template(bottom, temp);
1263 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1264 (void *) temp, temp->no_of_queries, 0 );
1265 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1266 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1271 struct query_info *next;
1283 struct query_info *qi;
1286 if ( rs->sr_type != REP_SEARCH ) return 0;
1288 attr = attr_find( rs->sr_entry->e_attrs, ad_queryid );
1289 if ( attr == NULL ) return 0;
1291 for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1293 assert( count > 0 );
1294 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1295 qi->next = op->o_callback->sc_private;
1296 op->o_callback->sc_private = qi;
1297 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1298 qi->del = ( count == 1 );
1307 struct berval* query_uuid)
1309 struct query_info *qi, *qnext;
1310 char filter_str[64];
1311 #ifdef LDAP_COMP_MATCH
1312 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1314 AttributeAssertion ava = { NULL, BER_BVNULL };
1316 Filter filter = {LDAP_FILTER_EQUALITY};
1317 SlapReply sreply = {REP_RESULT};
1318 slap_callback cb = { NULL, remove_func, NULL, NULL };
1321 sreply.sr_entry = NULL;
1322 sreply.sr_nentries = 0;
1323 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1324 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
1325 filter.f_ava = &ava;
1326 filter.f_av_desc = ad_queryid;
1327 filter.f_av_value = *query_uuid;
1329 op->o_tag = LDAP_REQ_SEARCH;
1330 op->o_protocol = LDAP_VERSION3;
1331 op->o_callback = &cb;
1332 op->o_time = slap_get_time();
1333 op->o_do_not_cache = 1;
1335 op->o_req_dn = op->o_bd->be_suffix[0];
1336 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1337 op->ors_scope = LDAP_SCOPE_SUBTREE;
1338 op->ors_deref = LDAP_DEREF_NEVER;
1339 op->ors_slimit = SLAP_NO_LIMIT;
1340 op->ors_tlimit = SLAP_NO_LIMIT;
1341 op->ors_filter = &filter;
1342 op->ors_filterstr.bv_val = filter_str;
1343 op->ors_filterstr.bv_len = strlen(filter_str);
1344 op->ors_attrs = NULL;
1345 op->ors_attrsonly = 0;
1347 op->o_bd->be_search( op, &sreply );
1349 for ( qi=cb.sc_private; qi; qi=qnext ) {
1352 op->o_req_dn = qi->xdn;
1353 op->o_req_ndn = qi->xdn;
1356 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1357 query_uuid->bv_val, 0, 0 );
1359 op->o_tag = LDAP_REQ_DELETE;
1361 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1366 struct berval vals[2];
1368 vals[0] = *query_uuid;
1369 vals[1].bv_val = NULL;
1371 mod.sml_op = LDAP_MOD_DELETE;
1373 mod.sml_desc = ad_queryid;
1374 mod.sml_type = ad_queryid->ad_cname;
1375 mod.sml_values = vals;
1376 mod.sml_nvalues = NULL;
1377 mod.sml_next = NULL;
1378 Debug( pcache_debug,
1379 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1380 query_uuid->bv_val, 0, 0 );
1382 op->orm_modlist = &mod;
1384 op->o_bd->be_modify( op, &sreply );
1386 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1387 op->o_tmpfree( qi, op->o_tmpmemctx );
1394 AttributeName* attrs,
1403 struct berval *fstr,
1404 AttributeName** filter_attrs,
1406 int* filter_got_oc )
1408 AttributeDescription *ad;
1410 switch ( f->f_choice ) {
1411 case LDAP_FILTER_EQUALITY:
1413 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1414 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1417 case LDAP_FILTER_GE:
1419 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1420 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1423 case LDAP_FILTER_LE:
1425 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1426 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1429 case LDAP_FILTER_APPROX:
1431 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1432 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1435 case LDAP_FILTER_SUBSTRINGS:
1437 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1438 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1441 case LDAP_FILTER_PRESENT:
1443 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1444 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1447 case LDAP_FILTER_AND:
1448 case LDAP_FILTER_OR:
1449 case LDAP_FILTER_NOT: {
1451 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1452 f->f_choice == LDAP_FILTER_AND ? '&' :
1453 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1454 fstr->bv_len += sizeof("(%") - 1;
1456 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1457 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1461 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1462 fstr->bv_len += sizeof(")") - 1;
1468 strcpy( fstr->bv_val, "(?=?)" );
1469 fstr->bv_len += sizeof("(?=?)")-1;
1473 if ( filter_attrs != NULL ) {
1474 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1475 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1477 (*filter_attrs)[*filter_cnt].an_desc = ad;
1478 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1479 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1480 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1481 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1483 if ( ad == slap_schema.si_ad_objectClass )
1490 struct search_info {
1493 QueryTemplate *qtemp;
1494 AttributeName* save_attrs; /* original attributes, saved for response */
1502 remove_query_and_data(
1506 struct berval *uuid )
1508 query_manager* qm = cm->qm;
1510 qm->crfunc( qm, uuid );
1511 if ( !BER_BVISNULL( uuid ) ) {
1514 Debug( pcache_debug,
1515 "Removing query UUID %s\n",
1516 uuid->bv_val, 0, 0 );
1517 return_val = remove_query_data( op, rs, uuid );
1518 Debug( pcache_debug,
1519 "QUERY REMOVED, SIZE=%d\n",
1521 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1522 cm->cur_entries -= return_val;
1523 cm->num_cached_queries--;
1524 Debug( pcache_debug,
1525 "STORED QUERIES = %lu\n",
1526 cm->num_cached_queries, 0, 0 );
1527 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1528 Debug( pcache_debug,
1529 "QUERY REMOVED, CACHE ="
1531 cm->cur_entries, 0, 0 );
1536 * Callback used to fetch queryid values based on entryUUID;
1537 * used by pcache_remove_entries_from_cache()
1540 fetch_queryid_cb( Operation *op, SlapReply *rs )
1544 /* only care about searchEntry responses */
1545 if ( rs->sr_type != REP_SEARCH ) {
1549 /* allow only one response per entryUUID */
1550 if ( op->o_callback->sc_private != NULL ) {
1556 /* copy all queryid values into callback's private data */
1557 a = attr_find( rs->sr_entry->e_attrs, ad_queryid );
1559 BerVarray vals = NULL;
1561 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1562 op->o_callback->sc_private = (void *)vals;
1566 /* clear entry if required */
1567 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1568 entry_free( rs->sr_entry );
1569 rs->sr_entry = NULL;
1570 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1577 * Call that allows to remove an entry from the cache, by forcing
1578 * the removal of all the related queries.
1581 pcache_remove_entries_from_cache(
1585 void *thrctx = ldap_pvt_thread_pool_context();
1587 Connection conn = { 0 };
1588 OperationBuffer opbuf;
1590 slap_callback sc = { 0 };
1591 SlapReply rs = { REP_RESULT };
1593 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1594 #ifdef LDAP_COMP_MATCH
1595 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1597 AttributeAssertion ava = { NULL, BER_BVNULL };
1599 AttributeName attrs[ 2 ] = { 0 };
1602 connection_fake_init( &conn, &opbuf, thrctx );
1605 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1606 op->ors_scope = LDAP_SCOPE_SUBTREE;
1607 op->ors_deref = LDAP_DEREF_NEVER;
1608 f.f_choice = LDAP_FILTER_EQUALITY;
1610 ava.aa_desc = slap_schema.si_ad_entryUUID;
1611 op->ors_filter = &f;
1613 op->ors_tlimit = SLAP_NO_LIMIT;
1614 attrs[ 0 ].an_desc = ad_queryid;
1615 attrs[ 0 ].an_name = ad_queryid->ad_cname;
1616 op->ors_attrs = attrs;
1617 op->ors_attrsonly = 0;
1619 op->o_req_dn = cm->db.be_suffix[ 0 ];
1620 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1622 op->o_tag = LDAP_REQ_SEARCH;
1623 op->o_protocol = LDAP_VERSION3;
1624 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1626 op->o_dn = op->o_bd->be_rootdn;
1627 op->o_ndn = op->o_bd->be_rootndn;
1628 sc.sc_response = fetch_queryid_cb;
1629 op->o_callback = ≻
1631 for ( s = 0; !BER_BVISNULL( &UUIDs[ s ] ); s++ ) {
1632 BerVarray vals = NULL;
1635 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1636 "(entryUUID=%s)", UUIDs[ s ].bv_val );
1637 op->ors_filterstr.bv_val = filtbuf;
1638 ava.aa_value = UUIDs[ s ];
1640 rc = op->o_bd->be_search( op, &rs );
1641 if ( rc != LDAP_SUCCESS ) {
1645 vals = (BerVarray)op->o_callback->sc_private;
1646 if ( vals != NULL ) {
1647 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1648 struct berval val = vals[ i ];
1650 remove_query_and_data( op, &rs, cm, &val );
1652 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1653 ch_free( val.bv_val );
1657 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1658 op->o_callback->sc_private = NULL;
1669 struct berval *query_uuid)
1671 struct search_info *si = op->o_callback->sc_private;
1672 slap_overinst *on = si->on;
1673 cache_manager *cm = on->on_bi.bi_private;
1676 struct berval crp_uuid;
1677 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1678 Operation op_tmp = *op;
1680 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1681 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1683 op_tmp.o_bd = &cm->db;
1684 op_tmp.o_dn = cm->db.be_rootdn;
1685 op_tmp.o_ndn = cm->db.be_rootndn;
1687 Debug( pcache_debug, "UUID for query being added = %s\n",
1690 for ( e=si->head; e; e=si->head ) {
1691 si->head = e->e_private;
1692 e->e_private = NULL;
1693 while ( cm->cur_entries > (cm->max_entries) ) {
1694 BER_BVZERO( &crp_uuid );
1695 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1698 return_val = merge_entry(&op_tmp, e, query_uuid);
1699 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1700 cm->cur_entries += return_val;
1701 Debug( pcache_debug,
1702 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1703 cm->cur_entries, 0, 0 );
1705 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1712 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1713 slap_callback *cb = op->o_callback;
1714 struct search_info *si = cb->sc_private;
1715 if ( si->save_attrs != NULL ) {
1716 rs->sr_attrs = si->save_attrs;
1717 op->ors_attrs = si->save_attrs;
1719 op->o_callback = op->o_callback->sc_next;
1720 op->o_tmpfree( cb, op->o_tmpmemctx );
1721 return SLAP_CB_CONTINUE;
1729 struct search_info *si = op->o_callback->sc_private;
1730 slap_overinst *on = si->on;
1731 cache_manager *cm = on->on_bi.bi_private;
1732 query_manager* qm = cm->qm;
1734 if ( si->save_attrs != NULL ) {
1735 rs->sr_attrs = si->save_attrs;
1736 op->ors_attrs = si->save_attrs;
1739 if ( rs->sr_type == REP_SEARCH ) {
1741 /* If we haven't exceeded the limit for this query,
1742 * build a chain of answers to store. If we hit the
1743 * limit, empty the chain and ignore the rest.
1746 if ( si->count < si->max ) {
1748 e = entry_dup( rs->sr_entry );
1749 if ( !si->head ) si->head = e;
1750 if ( si->tail ) si->tail->e_private = e;
1755 for (;si->head; si->head=e) {
1756 e = si->head->e_private;
1757 si->head->e_private = NULL;
1758 entry_free(si->head);
1764 } else if ( rs->sr_type == REP_RESULT ) {
1766 ( si->qtemp->negttl && !si->count && !si->over &&
1767 rs->sr_err == LDAP_SUCCESS )) {
1768 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1773 cache_entries( op, rs, &qc->q_uuid );
1774 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1775 cm->num_cached_queries++;
1776 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1777 cm->num_cached_queries, 0, 0 );
1778 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1780 /* If the consistency checker suspended itself,
1783 if ( cm->cc_paused ) {
1784 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1785 if ( cm->cc_paused ) {
1787 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1789 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1791 } else if ( si->count ) {
1792 /* duplicate query, free it */
1794 for (;si->head; si->head=e) {
1795 e = si->head->e_private;
1796 si->head->e_private = NULL;
1797 entry_free(si->head);
1801 filter_free( si->query.filter );
1804 op->o_callback->sc_cleanup = pcache_op_cleanup;
1806 return SLAP_CB_CONTINUE;
1812 AttributeName** new_attrs,
1813 struct attr_set *attrs,
1814 AttributeName* filter_attrs,
1824 /* duplicate attrs */
1825 count = attrs->count + fattr_cnt;
1826 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1831 *new_attrs = (AttributeName*)ch_calloc( count + 1,
1832 sizeof(AttributeName) );
1833 for (i=0; i<attrs->count; i++) {
1834 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1835 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1837 BER_BVZERO( &(*new_attrs)[i].an_name );
1838 alluser = an_find(*new_attrs, &AllUser);
1839 allop = an_find(*new_attrs, &AllOper);
1842 for ( i=0; i<fattr_cnt; i++ ) {
1843 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
1846 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1850 } else if ( alluser ) {
1853 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1854 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1855 (*new_attrs)[j].an_oc = NULL;
1856 (*new_attrs)[j].an_oc_exclude = 0;
1860 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1861 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1862 (*new_attrs)[j].an_oc = NULL;
1863 (*new_attrs)[j].an_oc_exclude = 0;
1866 BER_BVZERO( &(*new_attrs)[j].an_name );
1871 /* NOTE: this is a quick workaround to let pcache minimally interact
1872 * with pagedResults. A more articulated solutions would be to
1873 * perform the remote query without control and cache all results,
1874 * performing the pagedResults search only within the client
1875 * and the proxy. This requires pcache to understand pagedResults. */
1877 pcache_chk_controls(
1881 const char *non = "";
1882 const char *stripped = "";
1884 switch( op->o_pagedresults ) {
1885 case SLAP_CONTROL_NONCRITICAL:
1887 stripped = "; stripped";
1890 case SLAP_CONTROL_CRITICAL:
1891 Debug( pcache_debug, "%s: "
1892 "%scritical pagedResults control "
1893 "disabled with proxy cache%s.\n",
1894 op->o_log_prefix, non, stripped );
1896 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1900 rs->sr_err = SLAP_CB_CONTINUE;
1912 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1913 cache_manager *cm = on->on_bi.bi_private;
1914 query_manager* qm = cm->qm;
1918 AttributeName *filter_attrs = NULL;
1921 QueryTemplate *qtemp = NULL;
1924 CachedQuery *answerable = NULL;
1927 int fattr_got_oc = 0;
1929 struct berval tempstr;
1931 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1933 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1934 &fattr_cnt, &fattr_got_oc )) {
1935 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1936 return SLAP_CB_CONTINUE;
1939 Debug( pcache_debug, "query template of incoming query = %s\n",
1940 tempstr.bv_val, 0, 0 );
1942 /* FIXME: cannot cache/answer requests with pagedResults control */
1945 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1947 query.filter = op->ors_filter;
1948 query.base = op->o_req_ndn;
1949 query.scope = op->ors_scope;
1951 /* check for query containment */
1952 if (attr_set > -1) {
1953 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1954 for (; qt; qt = qt->qtnext ) {
1955 /* find if template i can potentially answer tempstr */
1956 if (qt->querystr.bv_len != tempstr.bv_len ||
1957 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1961 Debug( pcache_debug, "Entering QC, querystr = %s\n",
1962 op->ors_filterstr.bv_val, 0, 0 );
1963 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1969 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1972 /* Need to clear the callbacks of the original operation,
1973 * in case there are other overlays */
1974 BackendDB *save_bd = op->o_bd;
1975 slap_callback *save_cb = op->o_callback;
1977 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1978 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1979 if ( BER_BVISNULL( &answerable->q_uuid )) {
1980 /* No entries cached, just an empty result set */
1982 send_ldap_result( op, rs );
1985 op->o_callback = NULL;
1986 i = cm->db.bd_info->bi_op_search( op, rs );
1988 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1990 op->o_callback = save_cb;
1994 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1996 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1997 if (cm->num_cached_queries >= cm->max_queries) {
2000 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2002 if (op->ors_attrsonly)
2007 struct search_info *si;
2009 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2010 query.filter = filter_dup(op->ors_filter, NULL);
2011 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2012 if ( !qtemp->t_attrs.count ) {
2013 qtemp->t_attrs.count = add_filter_attrs(op,
2014 &qtemp->t_attrs.attrs,
2015 &qm->attr_sets[attr_set],
2016 filter_attrs, fattr_cnt, fattr_got_oc);
2018 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2020 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2021 cb->sc_response = pcache_response;
2022 cb->sc_cleanup = NULL;
2023 cb->sc_private = (cb+1);
2024 si = cb->sc_private;
2028 si->max = cm->num_entries_limit ;
2033 si->save_attrs = op->ors_attrs;
2035 op->ors_attrs = qtemp->t_attrs.attrs;
2037 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2038 cb->sc_next = op->o_callback;
2039 op->o_callback = cb;
2042 slap_callback **pcb;
2044 /* need to move the callback at the end, in case other
2045 * overlays are present, so that the final entry is
2046 * actually cached */
2048 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2053 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2057 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2059 return SLAP_CB_CONTINUE;
2064 AttributeName* attrs,
2072 for ( ; attrs[count].an_name.bv_val; count++ );
2075 /* recognize a single "*" or a "1.1" */
2078 attrs = slap_anlist_all_user_attributes;
2080 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2085 for ( i = 0; i < num; i++ ) {
2089 if ( count > qm->attr_sets[i].count ) {
2094 if ( !qm->attr_sets[i].count ) {
2100 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2101 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2124 struct re_s *rtask = arg;
2125 slap_overinst *on = rtask->arg;
2126 cache_manager *cm = on->on_bi.bi_private;
2127 query_manager *qm = cm->qm;
2128 Connection conn = {0};
2129 OperationBuffer opbuf;
2132 SlapReply rs = {REP_RESULT};
2134 int return_val, pause = 1;
2135 QueryTemplate* templ;
2137 connection_fake_init( &conn, &opbuf, ctx );
2141 op->o_dn = cm->db.be_rootdn;
2142 op->o_ndn = cm->db.be_rootndn;
2146 for (templ = qm->templates; templ; templ=templ->qmnext) {
2147 query = templ->query_last;
2148 if ( query ) pause = 0;
2149 op->o_time = slap_get_time();
2150 while (query && (query->expiry_time < op->o_time)) {
2152 Debug( pcache_debug, "Lock CR index = %p\n",
2153 (void *) templ, 0, 0 );
2154 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2155 if ( query == templ->query_last ) {
2157 remove_from_template(query, templ);
2158 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2159 (void *) templ, templ->no_of_queries, 0 );
2160 Debug( pcache_debug, "Unlock CR index = %p\n",
2161 (void *) templ, 0, 0 );
2163 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2165 query = templ->query_last;
2168 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2169 remove_query(qm, query);
2170 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2171 if ( BER_BVISNULL( &query->q_uuid ))
2174 return_val = remove_query_data(op, &rs, &query->q_uuid);
2175 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2177 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2178 cm->cur_entries -= return_val;
2179 cm->num_cached_queries--;
2180 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2181 cm->num_cached_queries, 0, 0 );
2182 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2183 Debug( pcache_debug,
2184 "STALE QUERY REMOVED, CACHE ="
2186 cm->cur_entries, 0, 0 );
2188 query = templ->query_last;
2191 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2192 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2193 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2195 /* If there were no queries, defer processing for a while */
2196 cm->cc_paused = pause;
2197 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2199 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2204 #define MAX_ATTR_SETS 500
2214 static ConfigDriver pc_cf_gen;
2215 static ConfigLDAPadd pc_ldadd;
2216 static ConfigCfAdd pc_cfadd;
2218 static ConfigTable pccfg[] = {
2219 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2221 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2222 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2223 "DESC 'ProxyCache basic parameters' "
2224 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2225 { "proxyattrset", "index> <attributes...",
2226 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2227 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2228 "DESC 'A set of attributes to cache' "
2229 "SYNTAX OMsDirectoryString )", NULL, NULL },
2230 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2231 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2232 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2233 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2234 "SYNTAX OMsDirectoryString )", NULL, NULL },
2235 { "response-callback", "head|tail(default)",
2236 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2237 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2238 "DESC 'Response callback position in overlay stack' "
2239 "SYNTAX OMsDirectoryString )", NULL, NULL },
2240 { "proxyCacheQueries", "queries",
2241 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2242 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2243 "DESC 'Maximum number of queries to cache' "
2244 "SYNTAX OMsInteger )", NULL, NULL },
2245 { "proxySaveQueries", "TRUE|FALSE",
2246 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2247 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2248 "DESC 'Save cached queries for hot restart' "
2249 "SYNTAX OMsBoolean )", NULL, NULL },
2251 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2254 static ConfigOCs pcocs[] = {
2255 { "( OLcfgOvOc:2.1 "
2256 "NAME 'olcPcacheConfig' "
2257 "DESC 'ProxyCache configuration' "
2258 "SUP olcOverlayConfig "
2259 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2260 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2261 Cft_Overlay, pccfg, NULL, pc_cfadd },
2262 { "( OLcfgOvOc:2.2 "
2263 "NAME 'olcPcacheDatabase' "
2264 "DESC 'Cache database configuration' "
2265 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2270 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2275 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2276 p->ce_bi->bi_cf_ocs != pcocs )
2277 return LDAP_CONSTRAINT_VIOLATION;
2279 on = (slap_overinst *)p->ce_bi;
2280 cm = on->on_bi.bi_private;
2282 return LDAP_SUCCESS;
2286 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2288 CfEntryInfo *pe = p->e_private;
2289 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2290 cache_manager *cm = on->on_bi.bi_private;
2293 /* FIXME: should not hardcode "olcDatabase" here */
2294 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2295 bv.bv_val = ca->cr_msg;
2298 /* We can only create this entry if the database is table-driven
2300 if ( cm->db.bd_info->bi_cf_ocs )
2301 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2308 pc_cf_gen( ConfigArgs *c )
2310 slap_overinst *on = (slap_overinst *)c->bi;
2311 cache_manager* cm = on->on_bi.bi_private;
2312 query_manager* qm = cm->qm;
2313 QueryTemplate* temp;
2314 AttributeName* attr_name;
2315 AttributeName* attrarray;
2316 const char* text=NULL;
2321 if ( c->op == SLAP_CONFIG_EMIT ) {
2325 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2326 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2327 cm->num_entries_limit, cm->cc_period );
2328 bv.bv_val = c->cr_msg;
2329 value_add_one( &c->rvalue_vals, &bv );
2332 for (i=0; i<cm->numattrsets; i++) {
2333 if ( !qm->attr_sets[i].count ) continue;
2335 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2337 /* count the attr length */
2338 for ( attr_name = qm->attr_sets[i].attrs;
2339 attr_name->an_name.bv_val; attr_name++ )
2340 bv.bv_len += attr_name->an_name.bv_len + 1;
2342 bv.bv_val = ch_malloc( bv.bv_len+1 );
2343 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2344 for ( attr_name = qm->attr_sets[i].attrs;
2345 attr_name->an_name.bv_val; attr_name++ ) {
2347 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2349 ber_bvarray_add( &c->rvalue_vals, &bv );
2351 if ( !c->rvalue_vals )
2355 for (temp=qm->templates; temp; temp=temp->qmnext) {
2356 if ( temp->negttl ) {
2357 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2359 temp->attr_set_index,
2363 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2364 temp->attr_set_index,
2367 bv.bv_len += temp->querystr.bv_len + 2;
2368 bv.bv_val = ch_malloc( bv.bv_len+1 );
2371 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2373 strcpy( ptr, c->cr_msg );
2374 ber_bvarray_add( &c->rvalue_vals, &bv );
2376 if ( !c->rvalue_vals )
2380 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2381 BER_BVSTR( &bv, "head" );
2383 BER_BVSTR( &bv, "tail" );
2385 value_add_one( &c->rvalue_vals, &bv );
2388 c->value_int = cm->max_queries;
2392 } else if ( c->op == LDAP_MOD_DELETE ) {
2393 return 1; /* FIXME */
2405 if ( cm->numattrsets > 0 ) {
2406 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2407 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2411 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2412 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2414 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2417 if ( cm->numattrsets <= 0 ) {
2418 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2419 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2422 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2423 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2424 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2428 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2429 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2430 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2434 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2435 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2437 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2440 if ( cm->max_entries <= 0 ) {
2441 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2442 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2446 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2447 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2449 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2452 if ( cm->num_entries_limit <= 0 ) {
2453 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2454 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2457 if ( cm->num_entries_limit > cm->max_entries ) {
2458 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2459 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2463 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2464 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2466 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2469 cm->cc_period = (time_t)t;
2470 Debug( pcache_debug,
2471 "Total # of attribute sets to be cached = %d.\n",
2472 cm->numattrsets, 0, 0 );
2473 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2474 sizeof( struct attr_set ) );
2477 if ( cm->numattrsets == 0 ) {
2478 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2479 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2482 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2483 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2485 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2489 if ( num < 0 || num >= cm->numattrsets ) {
2490 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2491 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2492 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2495 qm->attr_sets[num].flags |= PC_CONFIGURED;
2496 if ( c->argc == 2 ) {
2498 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2499 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2500 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2503 } else if ( c->argc == 3 ) {
2504 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2505 qm->attr_sets[num].count = 1;
2506 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2507 sizeof( AttributeName ) );
2508 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2511 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2512 qm->attr_sets[num].count = 1;
2513 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2514 sizeof( AttributeName ) );
2515 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2518 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2521 /* else: fallthru */
2523 } else if ( c->argc == 4 ) {
2524 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2525 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2527 qm->attr_sets[num].count = 2;
2528 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2529 sizeof( AttributeName ) );
2530 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2531 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2534 /* else: fallthru */
2537 if ( c->argc > 2 ) {
2538 int all_user = 0, all_op = 0;
2540 qm->attr_sets[num].count = c->argc - 2;
2541 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2542 sizeof( AttributeName ) );
2543 attr_name = qm->attr_sets[num].attrs;
2544 for ( i = 2; i < c->argc; i++ ) {
2545 attr_name->an_desc = NULL;
2546 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2547 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2548 "invalid attr #%d \"%s\" in attrlist",
2549 i - 2, c->argv[i] );
2550 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2551 ch_free( qm->attr_sets[num].attrs );
2552 qm->attr_sets[num].attrs = NULL;
2553 qm->attr_sets[num].count = 0;
2556 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2558 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2559 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2561 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2563 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2564 strcpy( c->cr_msg, text );
2565 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2566 ch_free( qm->attr_sets[num].attrs );
2567 qm->attr_sets[num].attrs = NULL;
2568 qm->attr_sets[num].count = 0;
2571 attr_name->an_name = attr_name->an_desc->ad_cname;
2573 attr_name->an_oc = NULL;
2574 attr_name->an_oc_exclude = 0;
2575 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2576 qm->attr_sets[num].flags |= PC_GOT_OC;
2578 BER_BVZERO( &attr_name->an_name );
2581 /* warn if list contains both "*" and "+" */
2582 if ( i > 4 && all_user && all_op ) {
2583 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2584 "warning: attribute list contains \"*\" and \"+\"" );
2585 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2590 if ( cm->numattrsets == 0 ) {
2591 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2592 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2595 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2596 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2598 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2602 if ( i < 0 || i >= cm->numattrsets ||
2603 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2604 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2605 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2606 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2609 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2610 temp->qmnext = qm->templates;
2611 qm->templates = temp;
2612 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2613 temp->query = temp->query_last = NULL;
2614 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2615 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2617 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2620 temp->ttl = (time_t)t;
2621 if ( c->argc == 5 ) {
2622 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2623 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2624 "unable to parse template negttl=\"%s\"",
2626 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2629 temp->negttl = (time_t)t;
2634 temp->no_of_queries = 0;
2636 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2637 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2638 Debug( pcache_debug, " query template: %s\n",
2639 temp->querystr.bv_val, 0, 0 );
2640 temp->attr_set_index = i;
2641 qm->attr_sets[i].flags |= PC_REFERENCED;
2642 temp->qtnext = qm->attr_sets[i].templates;
2643 qm->attr_sets[i].templates = temp;
2644 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2645 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2646 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2647 Debug( pcache_debug, "\t%s\n",
2648 attrarray[i].an_name.bv_val, 0, 0 );
2652 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2653 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2655 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2656 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2659 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2660 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2665 if ( c->value_int <= 0 ) {
2666 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2667 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2670 cm->max_queries = c->value_int;
2685 slap_overinst *on = (slap_overinst *)be->bd_info;
2686 cache_manager* cm = on->on_bi.bi_private;
2688 /* Something for the cache database? */
2689 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2690 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2692 return SLAP_CONF_UNKNOWN;
2700 slap_overinst *on = (slap_overinst *)be->bd_info;
2704 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2705 on->on_bi.bi_private = cm;
2707 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2710 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2711 cm->db.be_private = NULL;
2712 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2714 cm->numattrsets = 0;
2715 cm->num_entries_limit = 5;
2716 cm->num_cached_queries = 0;
2717 cm->max_entries = 0;
2718 cm->cur_entries = 0;
2719 cm->max_queries = 10000;
2720 cm->save_queries = 0;
2721 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2722 cm->cc_period = 1000;
2725 qm->attr_sets = NULL;
2726 qm->templates = NULL;
2728 qm->lru_bottom = NULL;
2730 qm->qcfunc = query_containment;
2731 qm->crfunc = cache_replacement;
2732 qm->addfunc = add_query;
2733 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2735 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2740 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2742 assert( op->o_tag == LDAP_REQ_SEARCH );
2744 if ( rs->sr_type == REP_SEARCH ) {
2747 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2751 assert( a->a_nvals != NULL );
2753 valsp = op->o_callback->sc_private;
2754 assert( *valsp == NULL );
2756 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2768 slap_overinst *on = (slap_overinst *)be->bd_info;
2769 cache_manager *cm = on->on_bi.bi_private;
2770 query_manager* qm = cm->qm;
2771 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2773 /* check attr sets */
2774 for ( i = 0; i < cm->numattrsets; i++) {
2775 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2776 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2777 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2781 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2785 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2786 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2791 if ( ncf || rf || nrf ) {
2792 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2793 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2794 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2801 /* need to inherit something from the original database... */
2802 cm->db.be_def_limit = be->be_def_limit;
2803 cm->db.be_limits = be->be_limits;
2804 cm->db.be_acl = be->be_acl;
2805 cm->db.be_dfltaccess = be->be_dfltaccess;
2807 if ( SLAP_DBMONITORING( be ) ) {
2808 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2811 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2814 rc = backend_startup_one( &cm->db, NULL );
2816 /* There is no runqueue in TOOL mode */
2817 if ( slapMode & SLAP_SERVER_MODE ) {
2818 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2819 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2820 consistency_check, on,
2821 "pcache_consistency", be->be_suffix[0].bv_val );
2822 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2824 /* Cached database must have the rootdn */
2825 if ( BER_BVISNULL( &cm->db.be_rootndn )
2826 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2828 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2829 "underlying database of type \"%s\"\n"
2830 " serving naming context \"%s\"\n"
2831 " has no \"rootdn\", required by \"proxycache\".\n",
2832 on->on_info->oi_orig->bi_type,
2833 cm->db.be_suffix[0].bv_val, 0 );
2837 if ( cm->save_queries ) {
2838 void *thrctx = ldap_pvt_thread_pool_context();
2839 Connection conn = { 0 };
2840 OperationBuffer opbuf;
2842 slap_callback cb = { 0 };
2843 SlapReply rs = { 0 };
2844 BerVarray vals = NULL;
2845 AttributeName attrs[ 2 ] = { 0 };
2847 connection_fake_init( &conn, &opbuf, thrctx );
2852 op->o_tag = LDAP_REQ_SEARCH;
2853 op->o_protocol = LDAP_VERSION3;
2854 cb.sc_response = pcache_cachedquery_open_cb;
2855 cb.sc_private = &vals;
2856 op->o_callback = &cb;
2857 op->o_time = slap_get_time();
2858 op->o_do_not_cache = 1;
2859 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2861 op->o_dn = cm->db.be_rootdn;
2862 op->o_ndn = cm->db.be_rootndn;
2863 op->o_req_dn = cm->db.be_suffix[ 0 ];
2864 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2866 op->ors_scope = LDAP_SCOPE_BASE;
2867 op->ors_deref = LDAP_DEREF_NEVER;
2869 op->ors_tlimit = SLAP_NO_LIMIT;
2870 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
2871 op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
2872 if ( op->ors_filter != NULL ) {
2873 attrs[ 0 ].an_desc = ad_cachedQueryURL;
2874 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
2875 op->ors_attrs = attrs;
2876 op->ors_attrsonly = 0;
2878 rc = op->o_bd->be_search( op, &rs );
2879 if ( rc == LDAP_SUCCESS && vals != NULL ) {
2882 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2883 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
2884 cm->num_cached_queries++;
2888 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2891 filter_free_x( op, op->ors_filter );
2903 pcache_free_qbase( void *v )
2909 tavl_free( qb->scopes[i], NULL );
2919 slap_overinst *on = (slap_overinst *)be->bd_info;
2920 cache_manager *cm = on->on_bi.bi_private;
2921 query_manager *qm = cm->qm;
2925 if ( cm->save_queries && qm->templates != NULL ) {
2927 BerVarray vals = NULL;
2929 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
2930 for ( qc = tm->query; qc; qc = qc->next ) {
2933 if ( query2url( qc, &bv ) == 0 ) {
2934 ber_bvarray_add( &vals, &bv );
2939 if ( vals != NULL ) {
2940 void *thrctx = ldap_pvt_thread_pool_context();
2941 Connection conn = { 0 };
2942 OperationBuffer opbuf;
2944 slap_callback cb = { 0 };
2946 SlapReply rs = { REP_RESULT };
2947 Modifications mod = { 0 };
2949 connection_fake_init( &conn, &opbuf, thrctx );
2953 op->o_dn = cm->db.be_rootdn;
2954 op->o_ndn = cm->db.be_rootndn;
2956 op->o_tag = LDAP_REQ_MODIFY;
2957 op->o_protocol = LDAP_VERSION3;
2958 cb.sc_response = slap_null_cb;
2959 op->o_callback = &cb;
2960 op->o_time = slap_get_time();
2961 op->o_do_not_cache = 1;
2962 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2964 op->o_req_dn = op->o_bd->be_suffix[0];
2965 op->o_req_ndn = op->o_bd->be_nsuffix[0];
2967 mod.sml_op = LDAP_MOD_REPLACE;
2969 mod.sml_desc = ad_cachedQueryURL;
2970 mod.sml_type = ad_cachedQueryURL->ad_cname;
2971 mod.sml_values = vals;
2972 mod.sml_nvalues = NULL;
2973 mod.sml_next = NULL;
2974 Debug( pcache_debug,
2975 "SETTING CACHED QUERY URLS\n",
2978 op->orm_modlist = &mod;
2980 op->o_bd->be_modify( op, &rs );
2982 ber_bvarray_free( vals );
2986 /* cleanup stuff inherited from the original database... */
2987 cm->db.be_limits = NULL;
2988 cm->db.be_acl = NULL;
2990 /* stop the thread ... */
2992 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2993 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
2994 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
2996 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
2997 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3000 if ( cm->db.bd_info->bi_db_close ) {
3001 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3003 while ( (tm = qm->templates) != NULL ) {
3004 CachedQuery *qc, *qn;
3005 qm->templates = tm->qmnext;
3006 for ( qc = tm->query; qc; qc = qn ) {
3010 avl_free( tm->qbase, pcache_free_qbase );
3011 free( tm->querystr.bv_val );
3012 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3013 free( tm->t_attrs.attrs );
3017 for ( i=0; i<cm->numattrsets; i++ ) {
3018 free( qm->attr_sets[i].attrs );
3020 free( qm->attr_sets );
3021 qm->attr_sets = NULL;
3032 slap_overinst *on = (slap_overinst *)be->bd_info;
3033 cache_manager *cm = on->on_bi.bi_private;
3034 query_manager *qm = cm->qm;
3036 if ( cm->db.be_private != NULL ) {
3037 backend_stopdown_one( &cm->db );
3040 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3041 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3048 static slap_overinst pcache;
3050 static char *obsolete_names[] = {
3055 int pcache_initialize()
3058 struct berval debugbv = BER_BVC("pcache");
3060 code = slap_loglevel_get( &debugbv, &pcache_debug );
3065 for ( i = 0; as[i].desc != NULL; i++ ) {
3066 code = register_at( as[i].desc, as[i].adp, 0 );
3068 Debug( LDAP_DEBUG_ANY,
3069 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3074 syn_UUID = syn_find( "1.3.6.1.1.16.1");
3075 if ( syn_UUID == NULL ) {
3076 Debug( LDAP_DEBUG_ANY,
3077 "pcache_initialize: unable to find UUID syntax\n",
3082 pcache.on_bi.bi_type = "pcache";
3083 pcache.on_bi.bi_obsolete_names = obsolete_names;
3084 pcache.on_bi.bi_db_init = pcache_db_init;
3085 pcache.on_bi.bi_db_config = pcache_db_config;
3086 pcache.on_bi.bi_db_open = pcache_db_open;
3087 pcache.on_bi.bi_db_close = pcache_db_close;
3088 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3090 pcache.on_bi.bi_op_search = pcache_op_search;
3092 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3094 pcache.on_bi.bi_cf_ocs = pcocs;
3096 code = config_register_schema( pccfg, pcocs );
3097 if ( code ) return code;
3099 return overlay_register( &pcache );
3102 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3103 int init_module(int argc, char *argv[]) {
3104 return pcache_initialize();
3108 #endif /* defined(SLAPD_OVER_PROXYCACHE) */