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;
1674 query_manager* qm = cm->qm;
1677 struct berval crp_uuid;
1678 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1679 Operation op_tmp = *op;
1681 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1682 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1684 op_tmp.o_bd = &cm->db;
1685 op_tmp.o_dn = cm->db.be_rootdn;
1686 op_tmp.o_ndn = cm->db.be_rootndn;
1688 Debug( pcache_debug, "UUID for query being added = %s\n",
1691 for ( e=si->head; e; e=si->head ) {
1692 si->head = e->e_private;
1693 e->e_private = NULL;
1694 while ( cm->cur_entries > (cm->max_entries) ) {
1695 BER_BVZERO( &crp_uuid );
1696 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1699 return_val = merge_entry(&op_tmp, e, query_uuid);
1700 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1701 cm->cur_entries += return_val;
1702 Debug( pcache_debug,
1703 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1704 cm->cur_entries, 0, 0 );
1706 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1713 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1714 slap_callback *cb = op->o_callback;
1715 struct search_info *si = cb->sc_private;
1716 if ( si->save_attrs != NULL ) {
1717 rs->sr_attrs = si->save_attrs;
1718 op->ors_attrs = si->save_attrs;
1720 op->o_callback = op->o_callback->sc_next;
1721 op->o_tmpfree( cb, op->o_tmpmemctx );
1722 return SLAP_CB_CONTINUE;
1730 struct search_info *si = op->o_callback->sc_private;
1731 slap_overinst *on = si->on;
1732 cache_manager *cm = on->on_bi.bi_private;
1733 query_manager* qm = cm->qm;
1735 if ( si->save_attrs != NULL ) {
1736 rs->sr_attrs = si->save_attrs;
1737 op->ors_attrs = si->save_attrs;
1740 if ( rs->sr_type == REP_SEARCH ) {
1742 /* If we haven't exceeded the limit for this query,
1743 * build a chain of answers to store. If we hit the
1744 * limit, empty the chain and ignore the rest.
1747 if ( si->count < si->max ) {
1749 e = entry_dup( rs->sr_entry );
1750 if ( !si->head ) si->head = e;
1751 if ( si->tail ) si->tail->e_private = e;
1756 for (;si->head; si->head=e) {
1757 e = si->head->e_private;
1758 si->head->e_private = NULL;
1759 entry_free(si->head);
1765 } else if ( rs->sr_type == REP_RESULT ) {
1767 ( si->qtemp->negttl && !si->count && !si->over &&
1768 rs->sr_err == LDAP_SUCCESS )) {
1769 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1774 cache_entries( op, rs, &qc->q_uuid );
1775 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1776 cm->num_cached_queries++;
1777 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1778 cm->num_cached_queries, 0, 0 );
1779 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1781 /* If the consistency checker suspended itself,
1784 if ( cm->cc_paused ) {
1785 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1786 if ( cm->cc_paused ) {
1788 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1790 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1792 } else if ( si->count ) {
1793 /* duplicate query, free it */
1795 for (;si->head; si->head=e) {
1796 e = si->head->e_private;
1797 si->head->e_private = NULL;
1798 entry_free(si->head);
1802 filter_free( si->query.filter );
1805 op->o_callback->sc_cleanup = pcache_op_cleanup;
1807 return SLAP_CB_CONTINUE;
1813 AttributeName** new_attrs,
1814 struct attr_set *attrs,
1815 AttributeName* filter_attrs,
1825 /* duplicate attrs */
1826 count = attrs->count + fattr_cnt;
1827 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1832 *new_attrs = (AttributeName*)ch_calloc( count + 1,
1833 sizeof(AttributeName) );
1834 for (i=0; i<attrs->count; i++) {
1835 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1836 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1838 BER_BVZERO( &(*new_attrs)[i].an_name );
1839 alluser = an_find(*new_attrs, &AllUser);
1840 allop = an_find(*new_attrs, &AllOper);
1843 for ( i=0; i<fattr_cnt; i++ ) {
1844 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
1847 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1851 } else if ( alluser ) {
1854 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1855 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1856 (*new_attrs)[j].an_oc = NULL;
1857 (*new_attrs)[j].an_oc_exclude = 0;
1861 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1862 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1863 (*new_attrs)[j].an_oc = NULL;
1864 (*new_attrs)[j].an_oc_exclude = 0;
1867 BER_BVZERO( &(*new_attrs)[j].an_name );
1872 /* NOTE: this is a quick workaround to let pcache minimally interact
1873 * with pagedResults. A more articulated solutions would be to
1874 * perform the remote query without control and cache all results,
1875 * performing the pagedResults search only within the client
1876 * and the proxy. This requires pcache to understand pagedResults. */
1878 pcache_chk_controls(
1882 const char *non = "";
1883 const char *stripped = "";
1885 switch( op->o_pagedresults ) {
1886 case SLAP_CONTROL_NONCRITICAL:
1888 stripped = "; stripped";
1891 case SLAP_CONTROL_CRITICAL:
1892 Debug( pcache_debug, "%s: "
1893 "%scritical pagedResults control "
1894 "disabled with proxy cache%s.\n",
1895 op->o_log_prefix, non, stripped );
1897 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1901 rs->sr_err = SLAP_CB_CONTINUE;
1913 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1914 cache_manager *cm = on->on_bi.bi_private;
1915 query_manager* qm = cm->qm;
1919 AttributeName *filter_attrs = NULL;
1922 QueryTemplate *qtemp = NULL;
1925 CachedQuery *answerable = NULL;
1928 int fattr_got_oc = 0;
1930 struct berval tempstr;
1932 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1934 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1935 &fattr_cnt, &fattr_got_oc )) {
1936 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1937 return SLAP_CB_CONTINUE;
1940 Debug( pcache_debug, "query template of incoming query = %s\n",
1941 tempstr.bv_val, 0, 0 );
1943 /* FIXME: cannot cache/answer requests with pagedResults control */
1946 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1948 query.filter = op->ors_filter;
1949 query.base = op->o_req_ndn;
1950 query.scope = op->ors_scope;
1952 /* check for query containment */
1953 if (attr_set > -1) {
1954 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1955 for (; qt; qt = qt->qtnext ) {
1956 /* find if template i can potentially answer tempstr */
1957 if (qt->querystr.bv_len != tempstr.bv_len ||
1958 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1962 Debug( pcache_debug, "Entering QC, querystr = %s\n",
1963 op->ors_filterstr.bv_val, 0, 0 );
1964 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1970 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1973 /* Need to clear the callbacks of the original operation,
1974 * in case there are other overlays */
1975 BackendDB *save_bd = op->o_bd;
1976 slap_callback *save_cb = op->o_callback;
1978 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1979 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1980 if ( BER_BVISNULL( &answerable->q_uuid )) {
1981 /* No entries cached, just an empty result set */
1983 send_ldap_result( op, rs );
1986 op->o_callback = NULL;
1987 i = cm->db.bd_info->bi_op_search( op, rs );
1989 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1991 op->o_callback = save_cb;
1995 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1997 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1998 if (cm->num_cached_queries >= cm->max_queries) {
2001 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2003 if (op->ors_attrsonly)
2008 struct search_info *si;
2010 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2011 query.filter = filter_dup(op->ors_filter, NULL);
2012 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2013 if ( !qtemp->t_attrs.count ) {
2014 qtemp->t_attrs.count = add_filter_attrs(op,
2015 &qtemp->t_attrs.attrs,
2016 &qm->attr_sets[attr_set],
2017 filter_attrs, fattr_cnt, fattr_got_oc);
2019 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2021 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2022 cb->sc_response = pcache_response;
2023 cb->sc_cleanup = NULL;
2024 cb->sc_private = (cb+1);
2025 si = cb->sc_private;
2029 si->max = cm->num_entries_limit ;
2034 si->save_attrs = op->ors_attrs;
2036 op->ors_attrs = qtemp->t_attrs.attrs;
2038 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2039 cb->sc_next = op->o_callback;
2040 op->o_callback = cb;
2043 slap_callback **pcb;
2045 /* need to move the callback at the end, in case other
2046 * overlays are present, so that the final entry is
2047 * actually cached */
2049 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2054 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2058 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2060 return SLAP_CB_CONTINUE;
2065 AttributeName* attrs,
2073 for ( ; attrs[count].an_name.bv_val; count++ );
2076 /* recognize a single "*" or a "1.1" */
2079 attrs = slap_anlist_all_user_attributes;
2081 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2086 for ( i = 0; i < num; i++ ) {
2090 if ( count > qm->attr_sets[i].count ) {
2095 if ( !qm->attr_sets[i].count ) {
2101 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2102 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2125 struct re_s *rtask = arg;
2126 slap_overinst *on = rtask->arg;
2127 cache_manager *cm = on->on_bi.bi_private;
2128 query_manager *qm = cm->qm;
2129 Connection conn = {0};
2130 OperationBuffer opbuf;
2133 SlapReply rs = {REP_RESULT};
2135 int return_val, pause = 1;
2136 QueryTemplate* templ;
2138 connection_fake_init( &conn, &opbuf, ctx );
2142 op->o_dn = cm->db.be_rootdn;
2143 op->o_ndn = cm->db.be_rootndn;
2147 for (templ = qm->templates; templ; templ=templ->qmnext) {
2148 query = templ->query_last;
2149 if ( query ) pause = 0;
2150 op->o_time = slap_get_time();
2151 while (query && (query->expiry_time < op->o_time)) {
2153 Debug( pcache_debug, "Lock CR index = %p\n",
2154 (void *) templ, 0, 0 );
2155 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2156 if ( query == templ->query_last ) {
2158 remove_from_template(query, templ);
2159 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2160 (void *) templ, templ->no_of_queries, 0 );
2161 Debug( pcache_debug, "Unlock CR index = %p\n",
2162 (void *) templ, 0, 0 );
2164 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2166 query = templ->query_last;
2169 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2170 remove_query(qm, query);
2171 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2172 if ( BER_BVISNULL( &query->q_uuid ))
2175 return_val = remove_query_data(op, &rs, &query->q_uuid);
2176 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2178 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2179 cm->cur_entries -= return_val;
2180 cm->num_cached_queries--;
2181 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2182 cm->num_cached_queries, 0, 0 );
2183 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2184 Debug( pcache_debug,
2185 "STALE QUERY REMOVED, CACHE ="
2187 cm->cur_entries, 0, 0 );
2189 query = templ->query_last;
2192 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2193 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2194 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2196 /* If there were no queries, defer processing for a while */
2197 cm->cc_paused = pause;
2198 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2200 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2205 #define MAX_ATTR_SETS 500
2215 static ConfigDriver pc_cf_gen;
2216 static ConfigLDAPadd pc_ldadd;
2217 static ConfigCfAdd pc_cfadd;
2219 static ConfigTable pccfg[] = {
2220 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2222 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2223 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2224 "DESC 'ProxyCache basic parameters' "
2225 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2226 { "proxyattrset", "index> <attributes...",
2227 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2228 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2229 "DESC 'A set of attributes to cache' "
2230 "SYNTAX OMsDirectoryString )", NULL, NULL },
2231 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2232 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2233 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2234 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2235 "SYNTAX OMsDirectoryString )", NULL, NULL },
2236 { "response-callback", "head|tail(default)",
2237 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2238 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2239 "DESC 'Response callback position in overlay stack' "
2240 "SYNTAX OMsDirectoryString )", NULL, NULL },
2241 { "proxyCacheQueries", "queries",
2242 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2243 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2244 "DESC 'Maximum number of queries to cache' "
2245 "SYNTAX OMsInteger )", NULL, NULL },
2246 { "proxySaveQueries", "TRUE|FALSE",
2247 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2248 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2249 "DESC 'Save cached queries for hot restart' "
2250 "SYNTAX OMsBoolean )", NULL, NULL },
2252 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2255 static ConfigOCs pcocs[] = {
2256 { "( OLcfgOvOc:2.1 "
2257 "NAME 'olcPcacheConfig' "
2258 "DESC 'ProxyCache configuration' "
2259 "SUP olcOverlayConfig "
2260 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2261 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2262 Cft_Overlay, pccfg, NULL, pc_cfadd },
2263 { "( OLcfgOvOc:2.2 "
2264 "NAME 'olcPcacheDatabase' "
2265 "DESC 'Cache database configuration' "
2266 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2271 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2276 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2277 p->ce_bi->bi_cf_ocs != pcocs )
2278 return LDAP_CONSTRAINT_VIOLATION;
2280 on = (slap_overinst *)p->ce_bi;
2281 cm = on->on_bi.bi_private;
2283 return LDAP_SUCCESS;
2287 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2289 CfEntryInfo *pe = p->e_private;
2290 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2291 cache_manager *cm = on->on_bi.bi_private;
2294 /* FIXME: should not hardcode "olcDatabase" here */
2295 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2296 bv.bv_val = ca->cr_msg;
2299 /* We can only create this entry if the database is table-driven
2301 if ( cm->db.bd_info->bi_cf_ocs )
2302 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2309 pc_cf_gen( ConfigArgs *c )
2311 slap_overinst *on = (slap_overinst *)c->bi;
2312 cache_manager* cm = on->on_bi.bi_private;
2313 query_manager* qm = cm->qm;
2314 QueryTemplate* temp;
2315 AttributeName* attr_name;
2316 AttributeName* attrarray;
2317 const char* text=NULL;
2322 if ( c->op == SLAP_CONFIG_EMIT ) {
2326 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2327 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2328 cm->num_entries_limit, cm->cc_period );
2329 bv.bv_val = c->cr_msg;
2330 value_add_one( &c->rvalue_vals, &bv );
2333 for (i=0; i<cm->numattrsets; i++) {
2334 if ( !qm->attr_sets[i].count ) continue;
2336 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2338 /* count the attr length */
2339 for ( attr_name = qm->attr_sets[i].attrs;
2340 attr_name->an_name.bv_val; attr_name++ )
2341 bv.bv_len += attr_name->an_name.bv_len + 1;
2343 bv.bv_val = ch_malloc( bv.bv_len+1 );
2344 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2345 for ( attr_name = qm->attr_sets[i].attrs;
2346 attr_name->an_name.bv_val; attr_name++ ) {
2348 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2350 ber_bvarray_add( &c->rvalue_vals, &bv );
2352 if ( !c->rvalue_vals )
2356 for (temp=qm->templates; temp; temp=temp->qmnext) {
2357 if ( temp->negttl ) {
2358 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2360 temp->attr_set_index,
2364 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2365 temp->attr_set_index,
2368 bv.bv_len += temp->querystr.bv_len + 2;
2369 bv.bv_val = ch_malloc( bv.bv_len+1 );
2372 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2374 strcpy( ptr, c->cr_msg );
2375 ber_bvarray_add( &c->rvalue_vals, &bv );
2377 if ( !c->rvalue_vals )
2381 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2382 BER_BVSTR( &bv, "head" );
2384 BER_BVSTR( &bv, "tail" );
2386 value_add_one( &c->rvalue_vals, &bv );
2389 c->value_int = cm->max_queries;
2393 } else if ( c->op == LDAP_MOD_DELETE ) {
2394 return 1; /* FIXME */
2406 if ( cm->numattrsets > 0 ) {
2407 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2408 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2412 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2413 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2415 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2418 if ( cm->numattrsets <= 0 ) {
2419 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2420 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2423 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2424 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2425 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2429 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2430 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2431 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2435 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2436 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2438 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2441 if ( cm->max_entries <= 0 ) {
2442 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2443 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2447 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2448 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2450 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2453 if ( cm->num_entries_limit <= 0 ) {
2454 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2455 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2458 if ( cm->num_entries_limit > cm->max_entries ) {
2459 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2460 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2464 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2465 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2467 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2470 cm->cc_period = (time_t)t;
2471 Debug( pcache_debug,
2472 "Total # of attribute sets to be cached = %d.\n",
2473 cm->numattrsets, 0, 0 );
2474 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2475 sizeof( struct attr_set ) );
2478 if ( cm->numattrsets == 0 ) {
2479 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2480 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2483 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2484 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2486 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2490 if ( num < 0 || num >= cm->numattrsets ) {
2491 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2492 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2493 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2496 qm->attr_sets[num].flags |= PC_CONFIGURED;
2497 if ( c->argc == 2 ) {
2499 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2500 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2501 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2504 } else if ( c->argc == 3 ) {
2505 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2506 qm->attr_sets[num].count = 1;
2507 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2508 sizeof( AttributeName ) );
2509 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2512 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2513 qm->attr_sets[num].count = 1;
2514 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2515 sizeof( AttributeName ) );
2516 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2519 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2522 /* else: fallthru */
2524 } else if ( c->argc == 4 ) {
2525 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2526 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2528 qm->attr_sets[num].count = 2;
2529 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2530 sizeof( AttributeName ) );
2531 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2532 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2535 /* else: fallthru */
2538 if ( c->argc > 2 ) {
2539 int all_user = 0, all_op = 0;
2541 qm->attr_sets[num].count = c->argc - 2;
2542 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2543 sizeof( AttributeName ) );
2544 attr_name = qm->attr_sets[num].attrs;
2545 for ( i = 2; i < c->argc; i++ ) {
2546 attr_name->an_desc = NULL;
2547 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2548 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2549 "invalid attr #%d \"%s\" in attrlist",
2550 i - 2, c->argv[i] );
2551 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2552 ch_free( qm->attr_sets[num].attrs );
2553 qm->attr_sets[num].attrs = NULL;
2554 qm->attr_sets[num].count = 0;
2557 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2559 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2560 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2562 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2564 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2565 strcpy( c->cr_msg, text );
2566 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2567 ch_free( qm->attr_sets[num].attrs );
2568 qm->attr_sets[num].attrs = NULL;
2569 qm->attr_sets[num].count = 0;
2572 attr_name->an_name = attr_name->an_desc->ad_cname;
2574 attr_name->an_oc = NULL;
2575 attr_name->an_oc_exclude = 0;
2576 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2577 qm->attr_sets[num].flags |= PC_GOT_OC;
2579 BER_BVZERO( &attr_name->an_name );
2582 /* warn if list contains both "*" and "+" */
2583 if ( i > 4 && all_user && all_op ) {
2584 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2585 "warning: attribute list contains \"*\" and \"+\"" );
2586 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2591 if ( cm->numattrsets == 0 ) {
2592 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2593 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2596 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2597 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2599 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2603 if ( i < 0 || i >= cm->numattrsets ||
2604 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2605 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2606 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2607 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2610 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2611 temp->qmnext = qm->templates;
2612 qm->templates = temp;
2613 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2614 temp->query = temp->query_last = NULL;
2615 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2616 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2618 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2621 temp->ttl = (time_t)t;
2622 if ( c->argc == 5 ) {
2623 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2624 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2625 "unable to parse template negttl=\"%s\"",
2627 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2630 temp->negttl = (time_t)t;
2635 temp->no_of_queries = 0;
2637 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2638 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2639 Debug( pcache_debug, " query template: %s\n",
2640 temp->querystr.bv_val, 0, 0 );
2641 temp->attr_set_index = i;
2642 qm->attr_sets[i].flags |= PC_REFERENCED;
2643 temp->qtnext = qm->attr_sets[i].templates;
2644 qm->attr_sets[i].templates = temp;
2645 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2646 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2647 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2648 Debug( pcache_debug, "\t%s\n",
2649 attrarray[i].an_name.bv_val, 0, 0 );
2653 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2654 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2656 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2657 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2660 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2661 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2666 if ( c->value_int <= 0 ) {
2667 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2668 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2671 cm->max_queries = c->value_int;
2686 slap_overinst *on = (slap_overinst *)be->bd_info;
2687 cache_manager* cm = on->on_bi.bi_private;
2689 /* Something for the cache database? */
2690 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2691 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2693 return SLAP_CONF_UNKNOWN;
2701 slap_overinst *on = (slap_overinst *)be->bd_info;
2705 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2706 on->on_bi.bi_private = cm;
2708 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2711 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2712 cm->db.be_private = NULL;
2713 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2715 cm->numattrsets = 0;
2716 cm->num_entries_limit = 5;
2717 cm->num_cached_queries = 0;
2718 cm->max_entries = 0;
2719 cm->cur_entries = 0;
2720 cm->max_queries = 10000;
2721 cm->save_queries = 0;
2722 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2723 cm->cc_period = 1000;
2726 qm->attr_sets = NULL;
2727 qm->templates = NULL;
2729 qm->lru_bottom = NULL;
2731 qm->qcfunc = query_containment;
2732 qm->crfunc = cache_replacement;
2733 qm->addfunc = add_query;
2734 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2736 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2741 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2743 assert( op->o_tag == LDAP_REQ_SEARCH );
2745 if ( rs->sr_type == REP_SEARCH ) {
2748 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2752 assert( a->a_nvals != NULL );
2754 valsp = op->o_callback->sc_private;
2755 assert( *valsp == NULL );
2757 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2769 slap_overinst *on = (slap_overinst *)be->bd_info;
2770 cache_manager *cm = on->on_bi.bi_private;
2771 query_manager* qm = cm->qm;
2772 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2774 /* check attr sets */
2775 for ( i = 0; i < cm->numattrsets; i++) {
2776 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2777 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2778 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2782 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2786 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2787 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2792 if ( ncf || rf || nrf ) {
2793 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2794 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2795 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2802 /* need to inherit something from the original database... */
2803 cm->db.be_def_limit = be->be_def_limit;
2804 cm->db.be_limits = be->be_limits;
2805 cm->db.be_acl = be->be_acl;
2806 cm->db.be_dfltaccess = be->be_dfltaccess;
2808 if ( SLAP_DBMONITORING( be ) ) {
2809 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2812 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2815 rc = backend_startup_one( &cm->db, NULL );
2817 /* There is no runqueue in TOOL mode */
2818 if ( slapMode & SLAP_SERVER_MODE ) {
2819 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2820 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2821 consistency_check, on,
2822 "pcache_consistency", be->be_suffix[0].bv_val );
2823 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2825 /* Cached database must have the rootdn */
2826 if ( BER_BVISNULL( &cm->db.be_rootndn )
2827 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2829 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2830 "underlying database of type \"%s\"\n"
2831 " serving naming context \"%s\"\n"
2832 " has no \"rootdn\", required by \"proxycache\".\n",
2833 on->on_info->oi_orig->bi_type,
2834 cm->db.be_suffix[0].bv_val, 0 );
2838 if ( cm->save_queries ) {
2839 void *thrctx = ldap_pvt_thread_pool_context();
2840 Connection conn = { 0 };
2841 OperationBuffer opbuf;
2843 slap_callback cb = { 0 };
2844 SlapReply rs = { 0 };
2845 BerVarray vals = NULL;
2846 AttributeName attrs[ 2 ] = { 0 };
2848 connection_fake_init( &conn, &opbuf, thrctx );
2853 op->o_tag = LDAP_REQ_SEARCH;
2854 op->o_protocol = LDAP_VERSION3;
2855 cb.sc_response = pcache_cachedquery_open_cb;
2856 cb.sc_private = &vals;
2857 op->o_callback = &cb;
2858 op->o_time = slap_get_time();
2859 op->o_do_not_cache = 1;
2860 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2862 op->o_dn = cm->db.be_rootdn;
2863 op->o_ndn = cm->db.be_rootndn;
2864 op->o_req_dn = cm->db.be_suffix[ 0 ];
2865 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2867 op->ors_scope = LDAP_SCOPE_BASE;
2868 op->ors_deref = LDAP_DEREF_NEVER;
2870 op->ors_tlimit = SLAP_NO_LIMIT;
2871 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
2872 op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
2873 if ( op->ors_filter != NULL ) {
2874 attrs[ 0 ].an_desc = ad_cachedQueryURL;
2875 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
2876 op->ors_attrs = attrs;
2877 op->ors_attrsonly = 0;
2879 rc = op->o_bd->be_search( op, &rs );
2880 if ( rc == LDAP_SUCCESS && vals != NULL ) {
2883 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2884 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
2885 cm->num_cached_queries++;
2889 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2892 filter_free_x( op, op->ors_filter );
2904 pcache_free_qbase( void *v )
2910 tavl_free( qb->scopes[i], NULL );
2920 slap_overinst *on = (slap_overinst *)be->bd_info;
2921 cache_manager *cm = on->on_bi.bi_private;
2922 query_manager *qm = cm->qm;
2926 if ( cm->save_queries && qm->templates != NULL ) {
2928 BerVarray vals = NULL;
2930 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
2931 for ( qc = tm->query; qc; qc = qc->next ) {
2934 if ( query2url( qc, &bv ) == 0 ) {
2935 ber_bvarray_add( &vals, &bv );
2940 if ( vals != NULL ) {
2941 void *thrctx = ldap_pvt_thread_pool_context();
2942 Connection conn = { 0 };
2943 OperationBuffer opbuf;
2945 slap_callback cb = { 0 };
2947 SlapReply rs = { REP_RESULT };
2948 Modifications mod = { 0 };
2950 connection_fake_init( &conn, &opbuf, thrctx );
2954 op->o_dn = cm->db.be_rootdn;
2955 op->o_ndn = cm->db.be_rootndn;
2957 op->o_tag = LDAP_REQ_MODIFY;
2958 op->o_protocol = LDAP_VERSION3;
2959 cb.sc_response = slap_null_cb;
2960 op->o_callback = &cb;
2961 op->o_time = slap_get_time();
2962 op->o_do_not_cache = 1;
2963 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2965 op->o_req_dn = op->o_bd->be_suffix[0];
2966 op->o_req_ndn = op->o_bd->be_nsuffix[0];
2968 mod.sml_op = LDAP_MOD_REPLACE;
2970 mod.sml_desc = ad_cachedQueryURL;
2971 mod.sml_type = ad_cachedQueryURL->ad_cname;
2972 mod.sml_values = vals;
2973 mod.sml_nvalues = NULL;
2974 mod.sml_next = NULL;
2975 Debug( pcache_debug,
2976 "SETTING CACHED QUERY URLS\n",
2979 op->orm_modlist = &mod;
2981 op->o_bd->be_modify( op, &rs );
2983 ber_bvarray_free( vals );
2987 /* cleanup stuff inherited from the original database... */
2988 cm->db.be_limits = NULL;
2989 cm->db.be_acl = NULL;
2991 /* stop the thread ... */
2993 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2994 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
2995 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
2997 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
2998 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3001 if ( cm->db.bd_info->bi_db_close ) {
3002 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3004 while ( (tm = qm->templates) != NULL ) {
3005 CachedQuery *qc, *qn;
3006 qm->templates = tm->qmnext;
3007 for ( qc = tm->query; qc; qc = qn ) {
3011 avl_free( tm->qbase, pcache_free_qbase );
3012 free( tm->querystr.bv_val );
3013 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3014 free( tm->t_attrs.attrs );
3018 for ( i=0; i<cm->numattrsets; i++ ) {
3019 free( qm->attr_sets[i].attrs );
3021 free( qm->attr_sets );
3022 qm->attr_sets = NULL;
3033 slap_overinst *on = (slap_overinst *)be->bd_info;
3034 cache_manager *cm = on->on_bi.bi_private;
3035 query_manager *qm = cm->qm;
3037 if ( cm->db.be_private != NULL ) {
3038 backend_stopdown_one( &cm->db );
3041 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3042 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3049 static slap_overinst pcache;
3051 static char *obsolete_names[] = {
3056 int pcache_initialize()
3059 struct berval debugbv = BER_BVC("pcache");
3061 code = slap_loglevel_get( &debugbv, &pcache_debug );
3066 for ( i = 0; as[i].desc != NULL; i++ ) {
3067 code = register_at( as[i].desc, as[i].adp, 0 );
3069 Debug( LDAP_DEBUG_ANY,
3070 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3075 syn_UUID = syn_find( "1.3.6.1.1.16.1 ");
3076 if ( syn_UUID == NULL ) {
3077 Debug( LDAP_DEBUG_ANY,
3078 "pcache_initialize: unable to find UUID syntax\n",
3083 pcache.on_bi.bi_type = "pcache";
3084 pcache.on_bi.bi_obsolete_names = obsolete_names;
3085 pcache.on_bi.bi_db_init = pcache_db_init;
3086 pcache.on_bi.bi_db_config = pcache_db_config;
3087 pcache.on_bi.bi_db_open = pcache_db_open;
3088 pcache.on_bi.bi_db_close = pcache_db_close;
3089 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3091 pcache.on_bi.bi_op_search = pcache_op_search;
3093 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3095 pcache.on_bi.bi_cf_ocs = pcocs;
3097 code = config_register_schema( pccfg, pcocs );
3098 if ( code ) return code;
3100 return overlay_register( &pcache );
3103 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3104 int init_module(int argc, char *argv[]) {
3105 return pcache_initialize();
3109 #endif /* defined(SLAPD_OVER_PROXYCACHE) */