2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2007 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
40 * Control that allows to access the private DB
41 * instead of the public one
43 #define PCACHE_CONTROL_PRIVDB "1.3.6.1.4.1.4203.666.11.9.5.1"
46 * Extended Operation that allows to remove a query from the cache
48 #define PCACHE_EXOP_QUERY_DELETE "1.3.6.1.4.1.4203.666.11.9.6.1"
51 /* query cache structs */
54 typedef struct Query_s {
55 Filter* filter; /* Search Filter */
56 struct berval base; /* Search Base */
57 int scope; /* Search scope */
60 struct query_template_s;
62 typedef struct Qbase_s {
63 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
68 /* struct representing a cached query */
69 typedef struct cached_query_s {
74 struct berval q_uuid; /* query identifier */
75 struct query_template_s *qtemp; /* template of the query */
76 time_t expiry_time; /* time till the query is considered valid */
77 struct cached_query_s *next; /* next query in the template */
78 struct cached_query_s *prev; /* previous query in the template */
79 struct cached_query_s *lru_up; /* previous query in the LRU list */
80 struct cached_query_s *lru_down; /* next query in the LRU list */
86 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
88 * <base> ::= CachedQuery.qbase->base
89 * <scope> ::= CachedQuery.scope
90 * <filter> ::= filter2bv(CachedQuery.filter)
91 * <uuid> ::= CachedQuery.q_uuid
92 * <attrset> ::= CachedQuery.qtemp->attr_set_index
93 * <expiry> ::= CachedQuery.expiry_time
95 * quick hack: parse URI, call add_query() and then fix
96 * CachedQuery.expiry_time and CachedQuery.q_uuid
100 * Represents a set of projected attributes.
104 struct query_template_s *templates;
105 AttributeName* attrs; /* specifies the set */
107 #define PC_CONFIGURED (0x1)
108 #define PC_REFERENCED (0x2)
109 #define PC_GOT_OC (0x4)
110 int count; /* number of attributes */
113 /* struct representing a query template
114 * e.g. template string = &(cn=)(mail=)
116 typedef struct query_template_s {
117 struct query_template_s *qtnext;
118 struct query_template_s *qmnext;
121 CachedQuery* query; /* most recent query cached for the template */
122 CachedQuery* query_last; /* oldest query cached for the template */
123 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
124 struct berval querystr; /* Filter string corresponding to the QT */
126 int attr_set_index; /* determines the projected attributes */
127 int no_of_queries; /* Total number of queries in the template */
128 time_t ttl; /* TTL for the queries of this template */
129 time_t negttl; /* TTL for negative results */
130 struct attr_set t_attrs; /* filter attrs + attr_set */
133 struct query_manager_s;
135 /* prototypes for functions for 1) query containment
136 * 2) query addition, 3) cache replacement
138 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
139 typedef CachedQuery * (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
140 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
142 /* LDAP query cache */
143 typedef struct query_manager_s {
144 struct attr_set* attr_sets; /* possible sets of projected attributes */
145 QueryTemplate* templates; /* cacheable templates */
147 CachedQuery* lru_top; /* top and bottom of LRU list */
148 CachedQuery* lru_bottom;
150 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
152 /* Query cache methods */
153 QCfunc *qcfunc; /* Query containment*/
154 CRfunc *crfunc; /* cache replacement */
155 AddQueryfunc *addfunc; /* add query */
158 /* LDAP query cache manager */
159 typedef struct cache_manager_s {
160 BackendDB db; /* underlying database */
161 unsigned long num_cached_queries; /* total number of cached queries */
162 unsigned long max_queries; /* upper bound on # of cached queries */
163 int save_queries; /* save cached queries across restarts */
164 int numattrsets; /* number of attribute sets */
165 int cur_entries; /* current number of entries cached */
166 int max_entries; /* max number of entries cached */
167 int num_entries_limit; /* max # of entries in a cacheable query */
169 char response_cb; /* install the response callback
170 * at the tail of the callback list */
171 #define PCACHE_RESPONSE_CB_HEAD 0
172 #define PCACHE_RESPONSE_CB_TAIL 1
174 time_t cc_period; /* interval between successive consistency checks (sec) */
178 ldap_pvt_thread_mutex_t cache_mutex;
180 query_manager* qm; /* query cache managed by the cache manager */
183 static int pcache_debug;
185 #ifdef PCACHE_CONTROL_PRIVDB
186 static int privDB_cid;
187 #endif /* PCACHE_CONTROL_PRIVDB */
189 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
192 AttributeDescription **adp;
194 { "( 1.3.6.1.4.1.4203.666.11.9.1.1 "
196 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
197 "EQUALITY octetStringMatch "
198 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
199 "NO-USER-MODIFICATION "
200 "USAGE directoryOperation )",
202 { "( 1.3.6.1.4.1.4203.666.11.9.1.2 "
203 "NAME 'cachedQueryURL' "
204 "DESC 'URI describing a cached query' "
205 "EQUALITY caseExactMatch "
206 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
207 "NO-USER-MODIFICATION "
208 "USAGE directoryOperation )",
209 &ad_cachedQueryURL },
218 AttributeName** filter_attrs,
220 int* filter_got_oc );
227 QueryTemplate *templ,
234 struct berval *query_uuid );
237 * Turn a cached query into its URL representation
240 query2url( Operation *op, CachedQuery *q, struct berval *urlbv )
242 struct berval bv_scope,
244 char attrset_buf[ 32 ],
247 ber_len_t attrset_len,
250 ldap_pvt_scope2bv( q->scope, &bv_scope );
251 filter2bv_x( op, q->filter, &bv_filter );
252 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
253 "%lu", (unsigned long)q->qtemp->attr_set_index );
254 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
255 "%lu", (unsigned long)q->expiry_time );
257 urlbv->bv_len = STRLENOF( "ldap:///" )
258 + q->qbase->base.bv_len
263 + STRLENOF( "?x-uuid=" )
265 + STRLENOF( ",x-attrset=" )
267 + STRLENOF( ",x-expiry=" )
269 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
270 ptr = lutil_strcopy( ptr, "ldap:///" );
271 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
272 ptr = lutil_strcopy( ptr, "??" );
273 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
274 ptr = lutil_strcopy( ptr, "?" );
275 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
276 ptr = lutil_strcopy( ptr, "?x-uuid=" );
277 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
278 ptr = lutil_strcopy( ptr, ",x-attrset=" );
279 ptr = lutil_strcopy( ptr, attrset_buf );
280 ptr = lutil_strcopy( ptr, ",x-expiry=" );
281 ptr = lutil_strcopy( ptr, expiry_buf );
283 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
289 * Turn an URL representing a formerly cached query into a cached query,
290 * and try to cache it
301 LDAPURLDesc *lud = NULL;
303 tempstr = BER_BVNULL,
313 rc = ldap_url_parse( url, &lud );
314 if ( rc != LDAP_URL_SUCCESS ) {
318 /* non-allowed fields */
319 if ( lud->lud_host != NULL ) {
324 if ( lud->lud_attrs != NULL ) {
330 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
335 /* required fields */
336 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
341 switch ( lud->lud_scope ) {
342 case LDAP_SCOPE_BASE:
343 case LDAP_SCOPE_ONELEVEL:
344 case LDAP_SCOPE_SUBTREE:
345 case LDAP_SCOPE_SUBORDINATE:
353 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
358 if ( lud->lud_exts == NULL ) {
363 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
364 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
365 struct berval tmpUUID;
366 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
368 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
369 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
370 if ( rc != LDAP_SUCCESS ) {
375 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
376 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
382 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
385 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
389 expiry_time = (time_t)l;
403 if ( !got_attrset ) {
413 /* ignore expired queries */
414 if ( expiry_time <= slap_get_time()) {
416 SlapReply rs2 = { 0 };
418 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
420 (void)remove_query_data( &op2, &rs2, &uuid );
425 ber_str2bv( lud->lud_dn, 0, 0, &base );
426 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
427 if ( rc != LDAP_SUCCESS ) {
430 query.scope = lud->lud_scope;
431 query.filter = str2filter( lud->lud_filter );
433 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
435 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
436 ch_free( tempstr.bv_val );
441 /* check for query containment */
442 qt = qm->attr_sets[attrset].templates;
443 for ( ; qt; qt = qt->qtnext ) {
444 /* find if template i can potentially answer tempstr */
445 if ( bvmatch( &qt->querystr, &tempstr ) ) {
455 cq = add_query( op, qm, &query, qt, 1 );
457 cq->expiry_time = expiry_time;
460 /* it's now into cq->filter */
470 if ( query.filter != NULL ) filter_free( query.filter );
471 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
472 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
473 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
474 if ( lud != NULL ) ldap_free_urldesc( lud );
479 /* Return 1 for an added entry, else 0 */
484 struct berval* query_uuid )
487 Modifications* modlist = NULL;
488 const char* text = NULL;
490 char textbuf[SLAP_TEXT_BUFLEN];
491 size_t textlen = sizeof(textbuf);
493 SlapReply sreply = {REP_RESULT};
495 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
500 /* add queryId attribute */
501 attr_merge_one( e, ad_queryId, query_uuid, NULL );
503 /* append the attribute list from the fetched entry */
504 e->e_attrs->a_next = attr;
506 op->o_tag = LDAP_REQ_ADD;
507 op->o_protocol = LDAP_VERSION3;
508 op->o_callback = &cb;
509 op->o_time = slap_get_time();
510 op->o_do_not_cache = 1;
513 op->o_req_dn = e->e_name;
514 op->o_req_ndn = e->e_nname;
515 rc = op->o_bd->be_add( op, &sreply );
517 if ( rc != LDAP_SUCCESS ) {
518 if ( rc == LDAP_ALREADY_EXISTS ) {
519 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
520 modlist->sml_op = LDAP_MOD_ADD;
521 op->o_tag = LDAP_REQ_MODIFY;
522 op->orm_modlist = modlist;
523 op->o_bd->be_modify( op, &sreply );
524 slap_mods_free( modlist, 1 );
525 } else if ( rc == LDAP_REFERRAL ||
526 rc == LDAP_NO_SUCH_OBJECT ) {
527 syncrepl_add_glue( op, e );
536 if ( op->ora_e == e )
537 be_entry_release_w( op, e );
544 /* Length-ordered sort on normalized DNs */
545 static int pcache_dn_cmp( const void *v1, const void *v2 )
547 const Qbase *q1 = v1, *q2 = v2;
549 int rc = q1->base.bv_len - q2->base.bv_len;
551 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
555 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
558 dif = bv1->bv_len - bv2->bv_len;
560 if ( dif > 0 ) len -= dif;
561 len = memcmp( bv1->bv_val, bv2->bv_val, len );
567 /* compare the first value in each filter */
568 static int pcache_filter_cmp( const void *v1, const void *v2 )
570 const CachedQuery *q1 = v1, *q2 =v2;
571 int rc, weight1, weight2;
573 switch( q1->first->f_choice ) {
574 case LDAP_FILTER_PRESENT:
577 case LDAP_FILTER_EQUALITY:
585 switch( q2->first->f_choice ) {
586 case LDAP_FILTER_PRESENT:
589 case LDAP_FILTER_EQUALITY:
597 rc = weight1 - weight2;
602 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
605 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
607 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
608 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
609 rc = lex_bvcmp( &q1->first->f_sub_initial,
610 &q2->first->f_sub_initial );
614 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
618 if ( q1->first->f_sub_any ) {
619 if ( q2->first->f_sub_any ) {
620 rc = lex_bvcmp( q1->first->f_sub_any,
621 q2->first->f_sub_any );
625 } else if ( q2->first->f_sub_any ) {
629 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
630 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
631 rc = lex_bvcmp( &q1->first->f_sub_final,
632 &q2->first->f_sub_final );
636 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
640 rc = lex_bvcmp( &q1->first->f_mr_value,
641 &q2->first->f_mr_value );
650 /* add query on top of LRU list */
652 add_query_on_top (query_manager* qm, CachedQuery* qc)
654 CachedQuery* top = qm->lru_top;
665 Debug( pcache_debug, "Base of added query = %s\n",
666 qc->qbase->base.bv_val, 0, 0 );
669 /* remove_query from LRU list */
672 remove_query (query_manager* qm, CachedQuery* qc)
695 qc->lru_up = qc->lru_down = NULL;
698 /* find and remove string2 from string1
699 * from start if position = 1,
700 * from end if position = 3,
701 * from anywhere if position = 2
702 * string1 is overwritten if position = 2.
706 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
717 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
718 ber2->bv_val, ber2->bv_len )) {
720 ber1->bv_val += ber2->bv_len;
721 ber1->bv_len -= ber2->bv_len;
726 ber1->bv_val[ber1->bv_len] = '\0';
727 temp = strstr( ber1->bv_val, ber2->bv_val );
729 strcpy( temp, temp+ber2->bv_len );
730 ber1->bv_len -= ber2->bv_len;
736 if ( ber1->bv_len >= ber2->bv_len &&
737 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
740 ber1->bv_len -= ber2->bv_len;
748 static struct berval*
749 merge_init_final(Operation *op, struct berval* init, struct berval* any,
750 struct berval* final)
752 struct berval* merged, *temp;
753 int i, any_count, count;
755 for (any_count=0; any && any[any_count].bv_val; any_count++)
765 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
770 ber_dupbv_x( temp, init, op->o_tmpmemctx );
774 for (i=0; i<any_count; i++) {
775 ber_dupbv_x( temp, any, op->o_tmpmemctx );
780 ber_dupbv_x( temp, final, op->o_tmpmemctx );
787 /* Each element in stored must be found in incoming. Incoming is overwritten.
790 strings_containment(struct berval* stored, struct berval* incoming)
792 struct berval* element;
796 for ( element=stored; element->bv_val != NULL; element++ ) {
797 for (j = k; incoming[j].bv_val != NULL; j++) {
798 if (find_and_remove(&(incoming[j]), element, 2)) {
815 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
819 struct berval init_incoming;
820 struct berval final_incoming;
821 struct berval *remaining_incoming = NULL;
823 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
824 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
827 init_incoming = incoming->f_sub_initial;
828 final_incoming = incoming->f_sub_final;
830 if (find_and_remove(&init_incoming,
831 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
832 &(stored->f_sub_final), 3))
834 if (stored->f_sub_any == NULL) {
838 remaining_incoming = merge_init_final(op, &init_incoming,
839 incoming->f_sub_any, &final_incoming);
840 rc = strings_containment(stored->f_sub_any, remaining_incoming);
841 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
848 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
850 struct berval incoming_val[2];
853 incoming_val[1] = incoming->f_av_value;
855 if (find_and_remove(incoming_val+1,
856 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
857 &(stored->f_sub_final), 3)) {
858 if (stored->f_sub_any == NULL){
862 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
863 BER_BVZERO( incoming_val+1 );
864 rc = strings_containment(stored->f_sub_any, incoming_val);
865 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
872 filter_first( Filter *f )
874 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
881 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
885 MatchingRule* mrule = NULL;
886 int res=0, eqpass= 0;
894 /* substring matches sort to the end, and we just have to
895 * walk the entire list.
897 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
898 ptr = tavl_end( root, 1 );
901 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
902 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
911 /* an incoming substr query can only be satisfied by a cached
914 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
915 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
918 /* an incoming eq query can be satisfied by a cached eq or substr
921 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
923 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
924 nextpass: eqpass = 1;
925 ptr = tavl_end( root, 1 );
930 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
936 switch (fs->f_choice) {
937 case LDAP_FILTER_EQUALITY:
938 if (fi->f_choice == LDAP_FILTER_EQUALITY)
939 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
945 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
952 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
953 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
954 &(fi->f_ava->aa_value),
955 &(fs->f_ava->aa_value), &text);
956 if (rc != LDAP_SUCCESS) {
959 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
962 switch (fs->f_choice) {
964 case LDAP_FILTER_AND:
969 case LDAP_FILTER_SUBSTRINGS:
970 /* check if the equality query can be
971 * answered with cached substring query */
972 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
973 && substr_containment_equality( op,
976 /* check if the substring query can be
977 * answered with cached substring query */
978 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
979 ) && substr_containment_substr( op,
985 case LDAP_FILTER_PRESENT:
990 case LDAP_FILTER_EQUALITY:
997 if (mrule && ret >= 0)
1002 case LDAP_FILTER_LE:
1003 if (mrule && ret <= 0)
1008 case LDAP_FILTER_NOT:
1014 } while((res) && (fi != NULL) && (fs != NULL));
1018 ptr = tavl_next( ptr, dir );
1023 /* check whether query is contained in any of
1024 * the cached queries in template
1026 static CachedQuery *
1027 query_containment(Operation *op, query_manager *qm,
1029 QueryTemplate *templa)
1032 int depth = 0, tscope;
1033 Qbase qbase, *qbptr = NULL;
1036 if (query->filter != NULL) {
1039 Debug( pcache_debug, "Lock QC index = %p\n",
1040 (void *) templa, 0, 0 );
1041 qbase.base = query->base;
1043 first = filter_first( query->filter );
1045 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1048 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1050 tscope = query->scope;
1051 /* Find a matching scope:
1052 * match at depth 0 OK
1055 * subord at depth > 0 OK
1056 * subtree at any depth OK
1058 * subtree or subord at any depth OK
1060 * subtree or subord at any depth OK
1062 * subord at depth > 0 OK
1063 * subtree at any depth OK
1065 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1066 switch ( query->scope ) {
1067 case LDAP_SCOPE_BASE:
1068 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1069 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1070 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1072 case LDAP_SCOPE_ONE:
1073 if ( tscope == LDAP_SCOPE_BASE )
1074 tscope = LDAP_SCOPE_ONE;
1075 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1076 if ( !depth ) break;
1077 if ( tscope < LDAP_SCOPE_SUBTREE )
1078 tscope = LDAP_SCOPE_SUBTREE;
1080 case LDAP_SCOPE_SUBTREE:
1081 if ( tscope < LDAP_SCOPE_SUBTREE )
1082 tscope = LDAP_SCOPE_SUBTREE;
1083 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1085 case LDAP_SCOPE_CHILDREN:
1086 if ( tscope < LDAP_SCOPE_SUBTREE )
1087 tscope = LDAP_SCOPE_SUBTREE;
1090 if ( !qbptr->scopes[tscope] ) continue;
1093 qc = find_filter( op, qbptr->scopes[tscope],
1094 query->filter, first );
1096 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1097 if (qm->lru_top != qc) {
1098 remove_query(qm, qc);
1099 add_query_on_top(qm, qc);
1101 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1106 if ( be_issuffix( op->o_bd, &qbase.base ))
1109 dnParent( &qbase.base, &pdn );
1114 Debug( pcache_debug,
1115 "Not answerable: Unlock QC index=%p\n",
1116 (void *) templa, 0, 0 );
1117 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1123 free_query (CachedQuery* qc)
1125 free(qc->q_uuid.bv_val);
1126 filter_free(qc->filter);
1131 /* Add query to query cache */
1132 static CachedQuery *
1137 QueryTemplate *templ,
1140 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1145 new_cached_query->qtemp = templ;
1146 BER_BVZERO( &new_cached_query->q_uuid );
1148 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1150 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1152 new_cached_query->lru_up = NULL;
1153 new_cached_query->lru_down = NULL;
1154 Debug( pcache_debug, "Added query expires at %ld\n",
1155 (long) new_cached_query->expiry_time, 0, 0 );
1157 new_cached_query->scope = query->scope;
1158 new_cached_query->filter = query->filter;
1159 new_cached_query->first = first = filter_first( query->filter );
1161 qb.base = query->base;
1163 /* Adding a query */
1164 Debug( pcache_debug, "Lock AQ index = %p\n",
1165 (void *) templ, 0, 0 );
1166 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1167 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1169 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1170 qbase->base.bv_len = qb.base.bv_len;
1171 qbase->base.bv_val = (char *)(qbase+1);
1172 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1173 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1174 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1176 new_cached_query->next = templ->query;
1177 new_cached_query->prev = NULL;
1178 new_cached_query->qbase = qbase;
1179 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1180 pcache_filter_cmp, avl_dup_error );
1183 if (templ->query == NULL)
1184 templ->query_last = new_cached_query;
1186 templ->query->prev = new_cached_query;
1187 templ->query = new_cached_query;
1188 templ->no_of_queries++;
1190 ch_free( new_cached_query );
1191 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1192 query->filter, first );
1193 filter_free( query->filter );
1195 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1196 (void *) templ, templ->no_of_queries, 0 );
1198 Debug( pcache_debug, "Unlock AQ index = %p \n",
1199 (void *) templ, 0, 0 );
1200 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1202 /* Adding on top of LRU list */
1204 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1205 add_query_on_top(qm, new_cached_query);
1206 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1208 return rc == 0 ? new_cached_query : NULL;
1212 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1214 if (!qc->prev && !qc->next) {
1215 template->query_last = template->query = NULL;
1216 } else if (qc->prev == NULL) {
1217 qc->next->prev = NULL;
1218 template->query = qc->next;
1219 } else if (qc->next == NULL) {
1220 qc->prev->next = NULL;
1221 template->query_last = qc->prev;
1223 qc->next->prev = qc->prev;
1224 qc->prev->next = qc->next;
1226 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1227 qc->qbase->queries--;
1228 if ( qc->qbase->queries == 0 ) {
1229 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1230 ch_free( qc->qbase );
1234 template->no_of_queries--;
1237 /* remove bottom query of LRU list from the query cache */
1239 * NOTE: slight change in functionality.
1241 * - if result->bv_val is NULL, the query at the bottom of the LRU
1243 * - otherwise, the query whose UUID is *result is removed
1244 * - if not found, result->bv_val is zeroed
1247 cache_replacement(query_manager* qm, struct berval *result)
1249 CachedQuery* bottom;
1250 QueryTemplate *temp;
1252 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1253 if ( BER_BVISNULL( result ) ) {
1254 bottom = qm->lru_bottom;
1257 Debug ( pcache_debug,
1258 "Cache replacement invoked without "
1259 "any query in LRU list\n", 0, 0, 0 );
1260 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1265 for ( bottom = qm->lru_bottom;
1267 bottom = bottom->lru_up )
1269 if ( bvmatch( result, &bottom->q_uuid ) ) {
1275 Debug ( pcache_debug,
1276 "Could not find query with uuid=\"%s\""
1277 "in LRU list\n", result->bv_val, 0, 0 );
1278 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1279 BER_BVZERO( result );
1284 temp = bottom->qtemp;
1285 remove_query(qm, bottom);
1286 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1288 *result = bottom->q_uuid;
1289 bottom->q_uuid.bv_val = NULL;
1291 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1292 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1293 remove_from_template(bottom, temp);
1294 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1295 (void *) temp, temp->no_of_queries, 0 );
1296 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1297 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1302 struct query_info *next;
1314 struct query_info *qi;
1317 if ( rs->sr_type != REP_SEARCH ) return 0;
1319 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1320 if ( attr == NULL ) return 0;
1322 for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1324 assert( count > 0 );
1325 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1326 qi->next = op->o_callback->sc_private;
1327 op->o_callback->sc_private = qi;
1328 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1329 qi->del = ( count == 1 );
1338 struct berval *query_uuid )
1340 struct query_info *qi, *qnext;
1341 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1342 #ifdef LDAP_COMP_MATCH
1343 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1345 AttributeAssertion ava = { NULL, BER_BVNULL };
1347 Filter filter = {LDAP_FILTER_EQUALITY};
1348 SlapReply sreply = {REP_RESULT};
1349 slap_callback cb = { NULL, remove_func, NULL, NULL };
1352 sreply.sr_entry = NULL;
1353 sreply.sr_nentries = 0;
1354 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1355 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1356 filter.f_ava = &ava;
1357 filter.f_av_desc = ad_queryId;
1358 filter.f_av_value = *query_uuid;
1360 op->o_tag = LDAP_REQ_SEARCH;
1361 op->o_protocol = LDAP_VERSION3;
1362 op->o_callback = &cb;
1363 op->o_time = slap_get_time();
1364 op->o_do_not_cache = 1;
1366 op->o_req_dn = op->o_bd->be_suffix[0];
1367 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1368 op->ors_scope = LDAP_SCOPE_SUBTREE;
1369 op->ors_deref = LDAP_DEREF_NEVER;
1370 op->ors_slimit = SLAP_NO_LIMIT;
1371 op->ors_tlimit = SLAP_NO_LIMIT;
1372 op->ors_filter = &filter;
1373 op->ors_filterstr.bv_val = filter_str;
1374 op->ors_filterstr.bv_len = strlen(filter_str);
1375 op->ors_attrs = NULL;
1376 op->ors_attrsonly = 0;
1378 op->o_bd->be_search( op, &sreply );
1380 for ( qi=cb.sc_private; qi; qi=qnext ) {
1383 op->o_req_dn = qi->xdn;
1384 op->o_req_ndn = qi->xdn;
1387 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1388 query_uuid->bv_val, 0, 0 );
1390 op->o_tag = LDAP_REQ_DELETE;
1392 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1398 struct berval vals[2];
1400 vals[0] = *query_uuid;
1401 vals[1].bv_val = NULL;
1403 mod.sml_op = LDAP_MOD_DELETE;
1405 mod.sml_desc = ad_queryId;
1406 mod.sml_type = ad_queryId->ad_cname;
1407 mod.sml_values = vals;
1408 mod.sml_nvalues = NULL;
1409 mod.sml_next = NULL;
1410 Debug( pcache_debug,
1411 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1412 query_uuid->bv_val, 0, 0 );
1414 op->orm_modlist = &mod;
1416 op->o_bd->be_modify( op, &sreply );
1418 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1419 op->o_tmpfree( qi, op->o_tmpmemctx );
1426 AttributeName* attrs,
1435 struct berval *fstr,
1436 AttributeName** filter_attrs,
1438 int* filter_got_oc )
1440 AttributeDescription *ad;
1442 switch ( f->f_choice ) {
1443 case LDAP_FILTER_EQUALITY:
1445 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1446 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1449 case LDAP_FILTER_GE:
1451 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1452 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1455 case LDAP_FILTER_LE:
1457 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1458 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1461 case LDAP_FILTER_APPROX:
1463 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1464 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1467 case LDAP_FILTER_SUBSTRINGS:
1469 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1470 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1473 case LDAP_FILTER_PRESENT:
1475 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1476 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1479 case LDAP_FILTER_AND:
1480 case LDAP_FILTER_OR:
1481 case LDAP_FILTER_NOT: {
1483 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1484 f->f_choice == LDAP_FILTER_AND ? '&' :
1485 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1486 fstr->bv_len += sizeof("(%") - 1;
1488 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1489 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1493 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1494 fstr->bv_len += sizeof(")") - 1;
1500 strcpy( fstr->bv_val, "(?=?)" );
1501 fstr->bv_len += sizeof("(?=?)")-1;
1505 if ( filter_attrs != NULL ) {
1506 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1507 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1509 (*filter_attrs)[*filter_cnt].an_desc = ad;
1510 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1511 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1512 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1513 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1515 if ( ad == slap_schema.si_ad_objectClass )
1522 struct search_info {
1525 QueryTemplate *qtemp;
1526 AttributeName* save_attrs; /* original attributes, saved for response */
1534 remove_query_and_data(
1538 struct berval *uuid )
1540 query_manager* qm = cm->qm;
1542 qm->crfunc( qm, uuid );
1543 if ( !BER_BVISNULL( uuid ) ) {
1546 Debug( pcache_debug,
1547 "Removing query UUID %s\n",
1548 uuid->bv_val, 0, 0 );
1549 return_val = remove_query_data( op, rs, uuid );
1550 Debug( pcache_debug,
1551 "QUERY REMOVED, SIZE=%d\n",
1553 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1554 cm->cur_entries -= return_val;
1555 cm->num_cached_queries--;
1556 Debug( pcache_debug,
1557 "STORED QUERIES = %lu\n",
1558 cm->num_cached_queries, 0, 0 );
1559 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1560 Debug( pcache_debug,
1561 "QUERY REMOVED, CACHE ="
1563 cm->cur_entries, 0, 0 );
1568 * Callback used to fetch queryId values based on entryUUID;
1569 * used by pcache_remove_entries_from_cache()
1572 fetch_queryId_cb( Operation *op, SlapReply *rs )
1576 /* only care about searchEntry responses */
1577 if ( rs->sr_type != REP_SEARCH ) {
1581 /* allow only one response per entryUUID */
1582 if ( op->o_callback->sc_private != NULL ) {
1588 /* copy all queryId values into callback's private data */
1589 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1591 BerVarray vals = NULL;
1593 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1594 op->o_callback->sc_private = (void *)vals;
1598 /* clear entry if required */
1599 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1600 entry_free( rs->sr_entry );
1601 rs->sr_entry = NULL;
1602 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1609 * Call that allows to remove a set of entries from the cache,
1610 * by forcing the removal of all the related queries.
1613 pcache_remove_entries_from_cache(
1616 BerVarray entryUUIDs )
1618 Connection conn = { 0 };
1619 OperationBuffer opbuf;
1621 slap_callback sc = { 0 };
1622 SlapReply rs = { REP_RESULT };
1624 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1625 #ifdef LDAP_COMP_MATCH
1626 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1628 AttributeAssertion ava = { NULL, BER_BVNULL };
1630 AttributeName attrs[ 2 ] = { 0 };
1634 void *thrctx = ldap_pvt_thread_pool_context();
1636 connection_fake_init( &conn, &opbuf, thrctx );
1644 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1645 op->ors_scope = LDAP_SCOPE_SUBTREE;
1646 op->ors_deref = LDAP_DEREF_NEVER;
1647 f.f_choice = LDAP_FILTER_EQUALITY;
1649 ava.aa_desc = slap_schema.si_ad_entryUUID;
1650 op->ors_filter = &f;
1652 op->ors_tlimit = SLAP_NO_LIMIT;
1653 attrs[ 0 ].an_desc = ad_queryId;
1654 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1655 op->ors_attrs = attrs;
1656 op->ors_attrsonly = 0;
1658 op->o_req_dn = cm->db.be_suffix[ 0 ];
1659 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1661 op->o_tag = LDAP_REQ_SEARCH;
1662 op->o_protocol = LDAP_VERSION3;
1663 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1665 op->o_dn = op->o_bd->be_rootdn;
1666 op->o_ndn = op->o_bd->be_rootndn;
1667 sc.sc_response = fetch_queryId_cb;
1668 op->o_callback = ≻
1670 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1671 BerVarray vals = NULL;
1673 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1674 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1675 op->ors_filterstr.bv_val = filtbuf;
1676 ava.aa_value = entryUUIDs[ s ];
1678 rc = op->o_bd->be_search( op, &rs );
1679 if ( rc != LDAP_SUCCESS ) {
1683 vals = (BerVarray)op->o_callback->sc_private;
1684 if ( vals != NULL ) {
1687 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1688 struct berval val = vals[ i ];
1690 remove_query_and_data( op, &rs, cm, &val );
1692 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1693 ch_free( val.bv_val );
1697 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1698 op->o_callback->sc_private = NULL;
1706 * Call that allows to remove a query from the cache.
1709 pcache_remove_query_from_cache(
1712 struct berval *queryid )
1714 Operation op2 = *op;
1715 SlapReply rs2 = { 0 };
1719 /* remove the selected query */
1720 remove_query_and_data( &op2, &rs2, cm, queryid );
1722 return LDAP_SUCCESS;
1726 * Call that allows to remove a set of queries related to an entry
1727 * from the cache; if queryid is not null, the entry must belong to
1728 * the query indicated by queryid.
1731 pcache_remove_entry_queries_from_cache(
1735 struct berval *queryid )
1737 Connection conn = { 0 };
1738 OperationBuffer opbuf;
1740 slap_callback sc = { 0 };
1741 SlapReply rs = { REP_RESULT };
1743 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1744 #ifdef LDAP_COMP_MATCH
1745 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1747 AttributeAssertion ava = { NULL, BER_BVNULL };
1749 AttributeName attrs[ 2 ] = { 0 };
1752 BerVarray vals = NULL;
1755 void *thrctx = ldap_pvt_thread_pool_context();
1757 connection_fake_init( &conn, &opbuf, thrctx );
1765 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1766 op->ors_scope = LDAP_SCOPE_BASE;
1767 op->ors_deref = LDAP_DEREF_NEVER;
1768 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1769 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1770 f.f_choice = LDAP_FILTER_PRESENT;
1771 f.f_desc = slap_schema.si_ad_objectClass;
1774 op->ors_filterstr.bv_len = snprintf( filter_str,
1775 sizeof( filter_str ), "(%s=%s)",
1776 ad_queryId->ad_cname.bv_val, queryid->bv_val );
1777 f.f_choice = LDAP_FILTER_EQUALITY;
1779 f.f_av_desc = ad_queryId;
1780 f.f_av_value = *queryid;
1782 op->ors_filter = &f;
1784 op->ors_tlimit = SLAP_NO_LIMIT;
1785 attrs[ 0 ].an_desc = ad_queryId;
1786 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1787 op->ors_attrs = attrs;
1788 op->ors_attrsonly = 0;
1790 op->o_req_dn = *ndn;
1791 op->o_req_ndn = *ndn;
1793 op->o_tag = LDAP_REQ_SEARCH;
1794 op->o_protocol = LDAP_VERSION3;
1795 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1797 op->o_dn = op->o_bd->be_rootdn;
1798 op->o_ndn = op->o_bd->be_rootndn;
1799 sc.sc_response = fetch_queryId_cb;
1800 op->o_callback = ≻
1802 rc = op->o_bd->be_search( op, &rs );
1803 if ( rc != LDAP_SUCCESS ) {
1807 vals = (BerVarray)op->o_callback->sc_private;
1808 if ( vals != NULL ) {
1811 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1812 struct berval val = vals[ i ];
1814 remove_query_and_data( op, &rs, cm, &val );
1816 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1817 ch_free( val.bv_val );
1821 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1824 return LDAP_SUCCESS;
1831 struct berval *query_uuid )
1833 struct search_info *si = op->o_callback->sc_private;
1834 slap_overinst *on = si->on;
1835 cache_manager *cm = on->on_bi.bi_private;
1838 struct berval crp_uuid;
1839 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1840 Operation op_tmp = *op;
1842 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1843 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1845 op_tmp.o_bd = &cm->db;
1846 op_tmp.o_dn = cm->db.be_rootdn;
1847 op_tmp.o_ndn = cm->db.be_rootndn;
1849 Debug( pcache_debug, "UUID for query being added = %s\n",
1852 for ( e=si->head; e; e=si->head ) {
1853 si->head = e->e_private;
1854 e->e_private = NULL;
1855 while ( cm->cur_entries > (cm->max_entries) ) {
1856 BER_BVZERO( &crp_uuid );
1857 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1860 return_val = merge_entry(&op_tmp, e, query_uuid);
1861 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1862 cm->cur_entries += return_val;
1863 Debug( pcache_debug,
1864 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1865 cm->cur_entries, 0, 0 );
1867 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1874 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1875 slap_callback *cb = op->o_callback;
1876 struct search_info *si = cb->sc_private;
1877 if ( si->save_attrs != NULL ) {
1878 rs->sr_attrs = si->save_attrs;
1879 op->ors_attrs = si->save_attrs;
1881 op->o_callback = op->o_callback->sc_next;
1882 op->o_tmpfree( cb, op->o_tmpmemctx );
1883 return SLAP_CB_CONTINUE;
1891 struct search_info *si = op->o_callback->sc_private;
1892 slap_overinst *on = si->on;
1893 cache_manager *cm = on->on_bi.bi_private;
1894 query_manager* qm = cm->qm;
1896 if ( si->save_attrs != NULL ) {
1897 rs->sr_attrs = si->save_attrs;
1898 op->ors_attrs = si->save_attrs;
1901 if ( rs->sr_type == REP_SEARCH ) {
1903 /* If we haven't exceeded the limit for this query,
1904 * build a chain of answers to store. If we hit the
1905 * limit, empty the chain and ignore the rest.
1908 if ( si->count < si->max ) {
1910 e = entry_dup( rs->sr_entry );
1911 if ( !si->head ) si->head = e;
1912 if ( si->tail ) si->tail->e_private = e;
1917 for (;si->head; si->head=e) {
1918 e = si->head->e_private;
1919 si->head->e_private = NULL;
1920 entry_free(si->head);
1926 } else if ( rs->sr_type == REP_RESULT ) {
1928 ( si->qtemp->negttl && !si->count && !si->over &&
1929 rs->sr_err == LDAP_SUCCESS )) {
1930 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1935 cache_entries( op, rs, &qc->q_uuid );
1936 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1937 cm->num_cached_queries++;
1938 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1939 cm->num_cached_queries, 0, 0 );
1940 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1942 /* If the consistency checker suspended itself,
1945 if ( cm->cc_paused ) {
1946 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1947 if ( cm->cc_paused ) {
1949 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1951 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1953 } else if ( si->count ) {
1954 /* duplicate query, free it */
1956 for (;si->head; si->head=e) {
1957 e = si->head->e_private;
1958 si->head->e_private = NULL;
1959 entry_free(si->head);
1963 filter_free( si->query.filter );
1966 op->o_callback->sc_cleanup = pcache_op_cleanup;
1968 return SLAP_CB_CONTINUE;
1974 AttributeName** new_attrs,
1975 struct attr_set *attrs,
1976 AttributeName* filter_attrs,
1986 /* duplicate attrs */
1987 count = attrs->count + fattr_cnt;
1988 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1993 *new_attrs = (AttributeName*)ch_calloc( count + 1,
1994 sizeof(AttributeName) );
1995 for (i=0; i<attrs->count; i++) {
1996 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1997 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1999 BER_BVZERO( &(*new_attrs)[i].an_name );
2000 alluser = an_find(*new_attrs, &AllUser);
2001 allop = an_find(*new_attrs, &AllOper);
2004 for ( i=0; i<fattr_cnt; i++ ) {
2005 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2008 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2012 } else if ( alluser ) {
2015 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2016 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2017 (*new_attrs)[j].an_oc = NULL;
2018 (*new_attrs)[j].an_oc_exclude = 0;
2022 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2023 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2024 (*new_attrs)[j].an_oc = NULL;
2025 (*new_attrs)[j].an_oc_exclude = 0;
2028 BER_BVZERO( &(*new_attrs)[j].an_name );
2033 /* NOTE: this is a quick workaround to let pcache minimally interact
2034 * with pagedResults. A more articulated solutions would be to
2035 * perform the remote query without control and cache all results,
2036 * performing the pagedResults search only within the client
2037 * and the proxy. This requires pcache to understand pagedResults. */
2039 pcache_chk_controls(
2043 const char *non = "";
2044 const char *stripped = "";
2046 switch( op->o_pagedresults ) {
2047 case SLAP_CONTROL_NONCRITICAL:
2049 stripped = "; stripped";
2052 case SLAP_CONTROL_CRITICAL:
2053 Debug( pcache_debug, "%s: "
2054 "%scritical pagedResults control "
2055 "disabled with proxy cache%s.\n",
2056 op->o_log_prefix, non, stripped );
2058 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2062 rs->sr_err = SLAP_CB_CONTINUE;
2069 #ifdef PCACHE_CONTROL_PRIVDB
2075 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2076 cache_manager *cm = on->on_bi.bi_private;
2077 slap_callback *save_cb;
2080 /* skip if control is unset */
2081 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2082 return SLAP_CB_CONTINUE;
2085 /* FIXME: might be a little bit exaggerated... */
2086 if ( !be_isroot( op ) ) {
2087 save_cb = op->o_callback;
2088 op->o_callback = NULL;
2089 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2090 "pcachePrivDB: operation not allowed" );
2091 op->o_callback = save_cb;
2096 /* map tag to operation */
2097 type = slap_req2op( op->o_tag );
2098 if ( type != SLAP_OP_LAST ) {
2102 /* execute, if possible */
2103 func = &cm->db.be_bind;
2104 if ( func[ type ] != NULL ) {
2105 Operation op2 = *op;
2109 rc = func[ type ]( &op2, rs );
2110 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2111 op->o_conn->c_authz_cookie = cm->db.be_private;
2116 /* otherwise fall back to error */
2117 save_cb = op->o_callback;
2118 op->o_callback = NULL;
2119 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2120 "operation not supported with pcachePrivDB control" );
2121 op->o_callback = save_cb;
2125 #endif /* PCACHE_CONTROL_PRIVDB */
2132 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2133 cache_manager *cm = on->on_bi.bi_private;
2134 query_manager* qm = cm->qm;
2138 AttributeName *filter_attrs = NULL;
2141 QueryTemplate *qtemp = NULL;
2144 CachedQuery *answerable = NULL;
2147 int fattr_got_oc = 0;
2149 struct berval tempstr;
2151 #ifdef PCACHE_CONTROL_PRIVDB
2152 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2153 return pcache_op_privdb( op, rs );
2155 #endif /* PCACHE_CONTROL_PRIVDB */
2157 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2159 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2160 &fattr_cnt, &fattr_got_oc )) {
2161 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2162 return SLAP_CB_CONTINUE;
2165 Debug( pcache_debug, "query template of incoming query = %s\n",
2166 tempstr.bv_val, 0, 0 );
2168 /* FIXME: cannot cache/answer requests with pagedResults control */
2171 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2173 query.filter = op->ors_filter;
2174 query.base = op->o_req_ndn;
2175 query.scope = op->ors_scope;
2177 /* check for query containment */
2178 if (attr_set > -1) {
2179 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2180 for (; qt; qt = qt->qtnext ) {
2181 /* find if template i can potentially answer tempstr */
2182 if (qt->querystr.bv_len != tempstr.bv_len ||
2183 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2187 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2188 op->ors_filterstr.bv_val, 0, 0 );
2189 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2195 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2198 /* Need to clear the callbacks of the original operation,
2199 * in case there are other overlays */
2200 BackendDB *save_bd = op->o_bd;
2201 slap_callback *save_cb = op->o_callback;
2203 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2204 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2205 if ( BER_BVISNULL( &answerable->q_uuid )) {
2206 /* No entries cached, just an empty result set */
2208 send_ldap_result( op, rs );
2211 op->o_callback = NULL;
2212 i = cm->db.bd_info->bi_op_search( op, rs );
2214 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2216 op->o_callback = save_cb;
2220 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2222 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2223 if (cm->num_cached_queries >= cm->max_queries) {
2226 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2228 if (op->ors_attrsonly)
2233 struct search_info *si;
2235 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2236 query.filter = filter_dup(op->ors_filter, NULL);
2237 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2238 if ( !qtemp->t_attrs.count ) {
2239 qtemp->t_attrs.count = add_filter_attrs(op,
2240 &qtemp->t_attrs.attrs,
2241 &qm->attr_sets[attr_set],
2242 filter_attrs, fattr_cnt, fattr_got_oc);
2244 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2246 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2247 cb->sc_response = pcache_response;
2248 cb->sc_cleanup = NULL;
2249 cb->sc_private = (cb+1);
2250 si = cb->sc_private;
2254 si->max = cm->num_entries_limit ;
2259 si->save_attrs = op->ors_attrs;
2261 op->ors_attrs = qtemp->t_attrs.attrs;
2263 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2264 cb->sc_next = op->o_callback;
2265 op->o_callback = cb;
2268 slap_callback **pcb;
2270 /* need to move the callback at the end, in case other
2271 * overlays are present, so that the final entry is
2272 * actually cached */
2274 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2279 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2283 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2285 return SLAP_CB_CONTINUE;
2290 AttributeName* attrs,
2298 for ( ; attrs[count].an_name.bv_val; count++ );
2301 /* recognize a single "*" or a "1.1" */
2304 attrs = slap_anlist_all_user_attributes;
2306 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2311 for ( i = 0; i < num; i++ ) {
2315 if ( count > qm->attr_sets[i].count ) {
2320 if ( !qm->attr_sets[i].count ) {
2326 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2327 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2350 struct re_s *rtask = arg;
2351 slap_overinst *on = rtask->arg;
2352 cache_manager *cm = on->on_bi.bi_private;
2353 query_manager *qm = cm->qm;
2354 Connection conn = {0};
2355 OperationBuffer opbuf;
2358 SlapReply rs = {REP_RESULT};
2360 int return_val, pause = 1;
2361 QueryTemplate* templ;
2363 connection_fake_init( &conn, &opbuf, ctx );
2367 op->o_dn = cm->db.be_rootdn;
2368 op->o_ndn = cm->db.be_rootndn;
2372 for (templ = qm->templates; templ; templ=templ->qmnext) {
2373 query = templ->query_last;
2374 if ( query ) pause = 0;
2375 op->o_time = slap_get_time();
2376 while (query && (query->expiry_time < op->o_time)) {
2378 Debug( pcache_debug, "Lock CR index = %p\n",
2379 (void *) templ, 0, 0 );
2380 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2381 if ( query == templ->query_last ) {
2383 remove_from_template(query, templ);
2384 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2385 (void *) templ, templ->no_of_queries, 0 );
2386 Debug( pcache_debug, "Unlock CR index = %p\n",
2387 (void *) templ, 0, 0 );
2389 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2391 query = templ->query_last;
2394 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2395 remove_query(qm, query);
2396 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2397 if ( BER_BVISNULL( &query->q_uuid ))
2400 return_val = remove_query_data(op, &rs, &query->q_uuid);
2401 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2403 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2404 cm->cur_entries -= return_val;
2405 cm->num_cached_queries--;
2406 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2407 cm->num_cached_queries, 0, 0 );
2408 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2409 Debug( pcache_debug,
2410 "STALE QUERY REMOVED, CACHE ="
2412 cm->cur_entries, 0, 0 );
2414 query = templ->query_last;
2417 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2418 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2419 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2421 /* If there were no queries, defer processing for a while */
2422 cm->cc_paused = pause;
2423 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2425 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2430 #define MAX_ATTR_SETS 500
2440 static ConfigDriver pc_cf_gen;
2441 static ConfigLDAPadd pc_ldadd;
2442 static ConfigCfAdd pc_cfadd;
2444 static ConfigTable pccfg[] = {
2445 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2447 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2448 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2449 "DESC 'ProxyCache basic parameters' "
2450 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2451 { "proxyattrset", "index> <attributes...",
2452 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2453 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2454 "DESC 'A set of attributes to cache' "
2455 "SYNTAX OMsDirectoryString )", NULL, NULL },
2456 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2457 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2458 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2459 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2460 "SYNTAX OMsDirectoryString )", NULL, NULL },
2461 { "response-callback", "head|tail(default)",
2462 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2463 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2464 "DESC 'Response callback position in overlay stack' "
2465 "SYNTAX OMsDirectoryString )", NULL, NULL },
2466 { "proxyCacheQueries", "queries",
2467 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2468 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2469 "DESC 'Maximum number of queries to cache' "
2470 "SYNTAX OMsInteger )", NULL, NULL },
2471 { "proxySaveQueries", "TRUE|FALSE",
2472 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2473 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2474 "DESC 'Save cached queries for hot restart' "
2475 "SYNTAX OMsBoolean )", NULL, NULL },
2477 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2480 static ConfigOCs pcocs[] = {
2481 { "( OLcfgOvOc:2.1 "
2482 "NAME 'olcPcacheConfig' "
2483 "DESC 'ProxyCache configuration' "
2484 "SUP olcOverlayConfig "
2485 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2486 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2487 Cft_Overlay, pccfg, NULL, pc_cfadd },
2488 { "( OLcfgOvOc:2.2 "
2489 "NAME 'olcPcacheDatabase' "
2490 "DESC 'Cache database configuration' "
2491 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2496 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2501 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2502 p->ce_bi->bi_cf_ocs != pcocs )
2503 return LDAP_CONSTRAINT_VIOLATION;
2505 on = (slap_overinst *)p->ce_bi;
2506 cm = on->on_bi.bi_private;
2508 return LDAP_SUCCESS;
2512 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2514 CfEntryInfo *pe = p->e_private;
2515 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2516 cache_manager *cm = on->on_bi.bi_private;
2519 /* FIXME: should not hardcode "olcDatabase" here */
2520 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2521 bv.bv_val = ca->cr_msg;
2524 /* We can only create this entry if the database is table-driven
2526 if ( cm->db.bd_info->bi_cf_ocs )
2527 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2534 pc_cf_gen( ConfigArgs *c )
2536 slap_overinst *on = (slap_overinst *)c->bi;
2537 cache_manager* cm = on->on_bi.bi_private;
2538 query_manager* qm = cm->qm;
2539 QueryTemplate* temp;
2540 AttributeName* attr_name;
2541 AttributeName* attrarray;
2542 const char* text=NULL;
2547 if ( c->op == SLAP_CONFIG_EMIT ) {
2551 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2552 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2553 cm->num_entries_limit, cm->cc_period );
2554 bv.bv_val = c->cr_msg;
2555 value_add_one( &c->rvalue_vals, &bv );
2558 for (i=0; i<cm->numattrsets; i++) {
2559 if ( !qm->attr_sets[i].count ) continue;
2561 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2563 /* count the attr length */
2564 for ( attr_name = qm->attr_sets[i].attrs;
2565 attr_name->an_name.bv_val; attr_name++ )
2566 bv.bv_len += attr_name->an_name.bv_len + 1;
2568 bv.bv_val = ch_malloc( bv.bv_len+1 );
2569 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2570 for ( attr_name = qm->attr_sets[i].attrs;
2571 attr_name->an_name.bv_val; attr_name++ ) {
2573 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2575 ber_bvarray_add( &c->rvalue_vals, &bv );
2577 if ( !c->rvalue_vals )
2581 for (temp=qm->templates; temp; temp=temp->qmnext) {
2582 if ( temp->negttl ) {
2583 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2585 temp->attr_set_index,
2589 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2590 temp->attr_set_index,
2593 bv.bv_len += temp->querystr.bv_len + 2;
2594 bv.bv_val = ch_malloc( bv.bv_len+1 );
2597 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2599 strcpy( ptr, c->cr_msg );
2600 ber_bvarray_add( &c->rvalue_vals, &bv );
2602 if ( !c->rvalue_vals )
2606 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2607 BER_BVSTR( &bv, "head" );
2609 BER_BVSTR( &bv, "tail" );
2611 value_add_one( &c->rvalue_vals, &bv );
2614 c->value_int = cm->max_queries;
2618 } else if ( c->op == LDAP_MOD_DELETE ) {
2619 return 1; /* FIXME */
2631 if ( cm->numattrsets > 0 ) {
2632 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2633 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2637 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2638 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2640 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2643 if ( cm->numattrsets <= 0 ) {
2644 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2645 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2648 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2649 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2650 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2654 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2655 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2656 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2660 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2661 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2663 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2666 if ( cm->max_entries <= 0 ) {
2667 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2668 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2672 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2673 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2675 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2678 if ( cm->num_entries_limit <= 0 ) {
2679 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2680 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2683 if ( cm->num_entries_limit > cm->max_entries ) {
2684 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2685 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2689 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2690 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2692 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2695 cm->cc_period = (time_t)t;
2696 Debug( pcache_debug,
2697 "Total # of attribute sets to be cached = %d.\n",
2698 cm->numattrsets, 0, 0 );
2699 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2700 sizeof( struct attr_set ) );
2703 if ( cm->numattrsets == 0 ) {
2704 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2705 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2708 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2709 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2711 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2715 if ( num < 0 || num >= cm->numattrsets ) {
2716 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2717 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2718 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2721 qm->attr_sets[num].flags |= PC_CONFIGURED;
2722 if ( c->argc == 2 ) {
2724 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2725 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2726 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2729 } else if ( c->argc == 3 ) {
2730 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2731 qm->attr_sets[num].count = 1;
2732 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2733 sizeof( AttributeName ) );
2734 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2737 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2738 qm->attr_sets[num].count = 1;
2739 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2740 sizeof( AttributeName ) );
2741 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2744 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2747 /* else: fallthru */
2749 } else if ( c->argc == 4 ) {
2750 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2751 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2753 qm->attr_sets[num].count = 2;
2754 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2755 sizeof( AttributeName ) );
2756 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2757 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2760 /* else: fallthru */
2763 if ( c->argc > 2 ) {
2764 int all_user = 0, all_op = 0;
2766 qm->attr_sets[num].count = c->argc - 2;
2767 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2768 sizeof( AttributeName ) );
2769 attr_name = qm->attr_sets[num].attrs;
2770 for ( i = 2; i < c->argc; i++ ) {
2771 attr_name->an_desc = NULL;
2772 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2773 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2774 "invalid attr #%d \"%s\" in attrlist",
2775 i - 2, c->argv[i] );
2776 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2777 ch_free( qm->attr_sets[num].attrs );
2778 qm->attr_sets[num].attrs = NULL;
2779 qm->attr_sets[num].count = 0;
2782 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2784 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2785 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2787 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2789 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2790 strcpy( c->cr_msg, text );
2791 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2792 ch_free( qm->attr_sets[num].attrs );
2793 qm->attr_sets[num].attrs = NULL;
2794 qm->attr_sets[num].count = 0;
2797 attr_name->an_name = attr_name->an_desc->ad_cname;
2799 attr_name->an_oc = NULL;
2800 attr_name->an_oc_exclude = 0;
2801 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2802 qm->attr_sets[num].flags |= PC_GOT_OC;
2804 BER_BVZERO( &attr_name->an_name );
2807 /* warn if list contains both "*" and "+" */
2808 if ( i > 4 && all_user && all_op ) {
2809 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2810 "warning: attribute list contains \"*\" and \"+\"" );
2811 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2816 if ( cm->numattrsets == 0 ) {
2817 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2818 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2821 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2822 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2824 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2828 if ( i < 0 || i >= cm->numattrsets ||
2829 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2830 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2831 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2832 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2835 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2836 temp->qmnext = qm->templates;
2837 qm->templates = temp;
2838 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2839 temp->query = temp->query_last = NULL;
2840 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2841 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2843 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2846 temp->ttl = (time_t)t;
2847 if ( c->argc == 5 ) {
2848 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2849 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2850 "unable to parse template negttl=\"%s\"",
2852 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2855 temp->negttl = (time_t)t;
2860 temp->no_of_queries = 0;
2862 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2863 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2864 Debug( pcache_debug, " query template: %s\n",
2865 temp->querystr.bv_val, 0, 0 );
2866 temp->attr_set_index = i;
2867 qm->attr_sets[i].flags |= PC_REFERENCED;
2868 temp->qtnext = qm->attr_sets[i].templates;
2869 qm->attr_sets[i].templates = temp;
2870 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2871 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2872 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2873 Debug( pcache_debug, "\t%s\n",
2874 attrarray[i].an_name.bv_val, 0, 0 );
2878 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2879 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2881 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2882 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2885 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2886 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2891 if ( c->value_int <= 0 ) {
2892 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2893 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2896 cm->max_queries = c->value_int;
2911 slap_overinst *on = (slap_overinst *)be->bd_info;
2912 cache_manager* cm = on->on_bi.bi_private;
2914 /* Something for the cache database? */
2915 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2916 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2918 return SLAP_CONF_UNKNOWN;
2926 slap_overinst *on = (slap_overinst *)be->bd_info;
2930 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2931 on->on_bi.bi_private = cm;
2933 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2936 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2937 cm->db.be_private = NULL;
2938 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2940 cm->numattrsets = 0;
2941 cm->num_entries_limit = 5;
2942 cm->num_cached_queries = 0;
2943 cm->max_entries = 0;
2944 cm->cur_entries = 0;
2945 cm->max_queries = 10000;
2946 cm->save_queries = 0;
2947 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2948 cm->cc_period = 1000;
2951 qm->attr_sets = NULL;
2952 qm->templates = NULL;
2954 qm->lru_bottom = NULL;
2956 qm->qcfunc = query_containment;
2957 qm->crfunc = cache_replacement;
2958 qm->addfunc = add_query;
2959 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2961 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2966 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2968 assert( op->o_tag == LDAP_REQ_SEARCH );
2970 if ( rs->sr_type == REP_SEARCH ) {
2973 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2977 assert( a->a_nvals != NULL );
2979 valsp = op->o_callback->sc_private;
2980 assert( *valsp == NULL );
2982 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2990 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
2992 assert( op->o_tag == LDAP_REQ_SEARCH );
2994 if ( rs->sr_type == REP_SEARCH ) {
2995 int *countp = (int *)op->o_callback->sc_private;
3008 slap_overinst *on = (slap_overinst *)be->bd_info;
3009 cache_manager *cm = on->on_bi.bi_private;
3010 query_manager* qm = cm->qm;
3011 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3013 /* check attr sets */
3014 for ( i = 0; i < cm->numattrsets; i++) {
3015 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3016 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3017 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3021 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3025 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3026 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3031 if ( ncf || rf || nrf ) {
3032 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3033 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3034 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3041 /* need to inherit something from the original database... */
3042 cm->db.be_def_limit = be->be_def_limit;
3043 cm->db.be_limits = be->be_limits;
3044 cm->db.be_acl = be->be_acl;
3045 cm->db.be_dfltaccess = be->be_dfltaccess;
3047 if ( SLAP_DBMONITORING( be ) ) {
3048 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3051 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3054 rc = backend_startup_one( &cm->db, NULL );
3056 /* There is no runqueue in TOOL mode */
3057 if ( slapMode & SLAP_SERVER_MODE ) {
3058 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3059 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3060 consistency_check, on,
3061 "pcache_consistency", be->be_suffix[0].bv_val );
3062 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3064 /* Cached database must have the rootdn */
3065 if ( BER_BVISNULL( &cm->db.be_rootndn )
3066 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3068 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3069 "underlying database of type \"%s\"\n"
3070 " serving naming context \"%s\"\n"
3071 " has no \"rootdn\", required by \"proxycache\".\n",
3072 on->on_info->oi_orig->bi_type,
3073 cm->db.be_suffix[0].bv_val, 0 );
3077 if ( cm->save_queries ) {
3078 void *thrctx = ldap_pvt_thread_pool_context();
3079 Connection conn = { 0 };
3080 OperationBuffer opbuf;
3082 slap_callback cb = { 0 };
3083 SlapReply rs = { 0 };
3084 BerVarray vals = NULL;
3085 Filter f = { 0 }, f2 = { 0 };
3086 #ifdef LDAP_COMP_MATCH
3087 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
3089 AttributeAssertion ava = { NULL, BER_BVNULL };
3091 AttributeName attrs[ 2 ] = { 0 };
3093 connection_fake_init( &conn, &opbuf, thrctx );
3098 op->o_tag = LDAP_REQ_SEARCH;
3099 op->o_protocol = LDAP_VERSION3;
3100 cb.sc_response = pcache_cachedquery_open_cb;
3101 cb.sc_private = &vals;
3102 op->o_callback = &cb;
3103 op->o_time = slap_get_time();
3104 op->o_do_not_cache = 1;
3105 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3107 op->o_dn = cm->db.be_rootdn;
3108 op->o_ndn = cm->db.be_rootndn;
3109 op->o_req_dn = cm->db.be_suffix[ 0 ];
3110 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3112 op->ors_scope = LDAP_SCOPE_BASE;
3113 op->ors_deref = LDAP_DEREF_NEVER;
3115 op->ors_tlimit = SLAP_NO_LIMIT;
3116 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3117 f.f_choice = LDAP_FILTER_PRESENT;
3118 f.f_desc = ad_cachedQueryURL;
3119 op->ors_filter = &f;
3120 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3121 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3122 op->ors_attrs = attrs;
3123 op->ors_attrsonly = 0;
3125 rc = op->o_bd->be_search( op, &rs );
3126 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3129 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3130 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3131 cm->num_cached_queries++;
3135 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3138 /* count cached entries */
3139 f.f_choice = LDAP_FILTER_NOT;
3141 f2.f_choice = LDAP_FILTER_EQUALITY;
3143 f2.f_av_desc = slap_schema.si_ad_objectClass;
3144 BER_BVSTR( &f2.f_av_value, "glue" );
3145 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3147 op->ors_slimit = SLAP_NO_LIMIT;
3148 op->ors_scope = LDAP_SCOPE_SUBTREE;
3149 op->ors_attrs = slap_anlist_no_attrs;
3151 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3153 op->o_callback->sc_private = &rs.sr_nentries;
3155 rc = op->o_bd->be_search( op, &rs );
3157 cm->cur_entries = rs.sr_nentries;
3168 pcache_free_qbase( void *v )
3174 tavl_free( qb->scopes[i], NULL );
3184 slap_overinst *on = (slap_overinst *)be->bd_info;
3185 cache_manager *cm = on->on_bi.bi_private;
3186 query_manager *qm = cm->qm;
3190 if ( cm->save_queries ) {
3192 BerVarray vals = NULL;
3195 Connection conn = { 0 };
3196 OperationBuffer opbuf;
3198 slap_callback cb = { 0 };
3200 SlapReply rs = { REP_RESULT };
3201 Modifications mod = { 0 };
3203 thrctx = ldap_pvt_thread_pool_context();
3205 connection_fake_init( &conn, &opbuf, thrctx );
3208 if ( qm->templates != NULL ) {
3209 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3210 for ( qc = tm->query; qc; qc = qc->next ) {
3213 if ( query2url( op, qc, &bv ) == 0 ) {
3214 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3221 op->o_dn = cm->db.be_rootdn;
3222 op->o_ndn = cm->db.be_rootndn;
3224 op->o_tag = LDAP_REQ_MODIFY;
3225 op->o_protocol = LDAP_VERSION3;
3226 cb.sc_response = slap_null_cb;
3227 op->o_callback = &cb;
3228 op->o_time = slap_get_time();
3229 op->o_do_not_cache = 1;
3230 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3232 op->o_req_dn = op->o_bd->be_suffix[0];
3233 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3235 mod.sml_op = LDAP_MOD_REPLACE;
3237 mod.sml_desc = ad_cachedQueryURL;
3238 mod.sml_type = ad_cachedQueryURL->ad_cname;
3239 mod.sml_values = vals;
3240 mod.sml_nvalues = NULL;
3241 mod.sml_next = NULL;
3242 Debug( pcache_debug,
3243 "%sSETTING CACHED QUERY URLS\n",
3244 vals == NULL ? "RE" : "", 0, 0 );
3246 op->orm_modlist = &mod;
3248 op->o_bd->be_modify( op, &rs );
3250 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3253 /* cleanup stuff inherited from the original database... */
3254 cm->db.be_limits = NULL;
3255 cm->db.be_acl = NULL;
3257 /* stop the thread ... */
3259 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3260 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3261 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3263 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3264 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3267 if ( cm->db.bd_info->bi_db_close ) {
3268 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3270 while ( (tm = qm->templates) != NULL ) {
3271 CachedQuery *qc, *qn;
3272 qm->templates = tm->qmnext;
3273 for ( qc = tm->query; qc; qc = qn ) {
3277 avl_free( tm->qbase, pcache_free_qbase );
3278 free( tm->querystr.bv_val );
3279 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3280 free( tm->t_attrs.attrs );
3284 for ( i=0; i<cm->numattrsets; i++ ) {
3285 free( qm->attr_sets[i].attrs );
3287 free( qm->attr_sets );
3288 qm->attr_sets = NULL;
3299 slap_overinst *on = (slap_overinst *)be->bd_info;
3300 cache_manager *cm = on->on_bi.bi_private;
3301 query_manager *qm = cm->qm;
3303 if ( cm->db.be_private != NULL ) {
3304 backend_stopdown_one( &cm->db );
3307 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3308 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3315 #ifdef PCACHE_CONTROL_PRIVDB
3317 Control ::= SEQUENCE {
3318 controlType LDAPOID,
3319 criticality BOOLEAN DEFAULT FALSE,
3320 controlValue OCTET STRING OPTIONAL }
3322 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3324 * criticality must be TRUE; controlValue must be absent.
3332 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3333 rs->sr_text = "privateDB control specified multiple times";
3334 return LDAP_PROTOCOL_ERROR;
3337 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3338 rs->sr_text = "privateDB control value not absent";
3339 return LDAP_PROTOCOL_ERROR;
3342 if ( !ctrl->ldctl_iscritical ) {
3343 rs->sr_text = "privateDB control criticality required";
3344 return LDAP_PROTOCOL_ERROR;
3347 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3349 return LDAP_SUCCESS;
3352 static char *extops[] = {
3353 LDAP_EXOP_MODIFY_PASSWD,
3356 #endif /* PCACHE_CONTROL_PRIVDB */
3358 #ifdef PCACHE_EXOP_QUERY_DELETE
3359 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3361 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3362 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3363 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3366 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3367 requestName [0] LDAPOID,
3368 requestValue [1] OCTET STRING OPTIONAL }
3370 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3372 requestValue ::= SEQUENCE { CHOICE {
3374 entryDN [1] LDAPDN },
3375 queryID [2] OCTET STRING (SIZE(16))
3376 -- constrained to UUID }
3378 * Either baseDN or entryDN must be present, to allow database selection.
3380 * 1. if baseDN and queryID are present, then the query corresponding
3381 * to queryID is deleted;
3382 * 2. if baseDN is present and queryID is absent, then all queries
3384 * 3. if entryDN is present and queryID is absent, then all queries
3385 * corresponding to the queryID values present in entryDN are deleted;
3386 * 4. if entryDN and queryID are present, then all queries
3387 * corresponding to the queryID values present in entryDN are deleted,
3388 * but only if the value of queryID is contained in the entry;
3390 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3391 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3392 * or by removing the database files.
3394 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3395 COMPONENTS OF LDAPResult,
3396 responseName [10] LDAPOID OPTIONAL,
3397 responseValue [11] OCTET STRING OPTIONAL }
3399 * responseName and responseValue must be absent.
3403 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3404 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3405 * - if ndn != NULL, it is set to the normalized DN in the request
3406 * corresponding to either the baseDN or the entryDN, according
3407 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3408 * be freed by the caller.
3409 * - if uuid != NULL, it is set to point to the normalized UUID;
3410 * memory is malloc'ed on the Operation's slab, and must
3411 * be freed by the caller.
3414 pcache_parse_query_delete(
3418 struct berval *uuid,
3422 int rc = LDAP_SUCCESS;
3425 BerElementBuffer berbuf;
3426 BerElement *ber = (BerElement *)&berbuf;
3427 struct berval reqdata = BER_BVNULL;
3439 if ( in == NULL || in->bv_len == 0 ) {
3440 *text = "empty request data field in queryDelete exop";
3441 return LDAP_PROTOCOL_ERROR;
3444 ber_dupbv_x( &reqdata, in, ctx );
3446 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3447 ber_init2( ber, &reqdata, 0 );
3449 tag = ber_scanf( ber, "{" /*}*/ );
3451 if ( tag == LBER_ERROR ) {
3452 Debug( LDAP_DEBUG_TRACE,
3453 "pcache_parse_query_delete: decoding error.\n",
3455 goto decoding_error;
3458 tag = ber_peek_tag( ber, &len );
3459 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3460 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3464 if ( ndn != NULL ) {
3467 tag = ber_scanf( ber, "m", &dn );
3468 if ( tag == LBER_ERROR ) {
3469 Debug( LDAP_DEBUG_TRACE,
3470 "pcache_parse_query_delete: DN parse failed.\n",
3472 goto decoding_error;
3475 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3476 if ( rc != LDAP_SUCCESS ) {
3477 *text = "invalid DN in queryDelete exop request data";
3482 tag = ber_scanf( ber, "x" /* "m" */ );
3483 if ( tag == LBER_DEFAULT ) {
3484 goto decoding_error;
3488 tag = ber_peek_tag( ber, &len );
3491 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3492 if ( uuid != NULL ) {
3494 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3496 tag = ber_scanf( ber, "m", &bv );
3497 if ( tag == LBER_ERROR ) {
3498 Debug( LDAP_DEBUG_TRACE,
3499 "pcache_parse_query_delete: UUID parse failed.\n",
3501 goto decoding_error;
3504 if ( bv.bv_len != 16 ) {
3505 Debug( LDAP_DEBUG_TRACE,
3506 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3507 (unsigned long)bv.bv_len, 0, 0 );
3508 goto decoding_error;
3511 rc = lutil_uuidstr_from_normalized(
3512 bv.bv_val, bv.bv_len,
3513 uuidbuf, sizeof( uuidbuf ) );
3515 goto decoding_error;
3517 ber_str2bv( uuidbuf, rc, 1, uuid );
3521 tag = ber_skip_tag( ber, &len );
3522 if ( tag == LBER_DEFAULT ) {
3523 goto decoding_error;
3527 Debug( LDAP_DEBUG_TRACE,
3528 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3529 (unsigned long)len, 0, 0 );
3530 goto decoding_error;
3534 tag = ber_peek_tag( ber, &len );
3537 if ( tag != LBER_DEFAULT || len != 0 ) {
3539 Debug( LDAP_DEBUG_TRACE,
3540 "pcache_parse_query_delete: decoding error\n",
3542 rc = LDAP_PROTOCOL_ERROR;
3543 *text = "queryDelete data decoding error";
3546 if ( ndn && !BER_BVISNULL( ndn ) ) {
3547 slap_sl_free( ndn->bv_val, ctx );
3551 if ( uuid && !BER_BVISNULL( uuid ) ) {
3552 slap_sl_free( uuid->bv_val, ctx );
3557 if ( !BER_BVISNULL( &reqdata ) ) {
3558 ber_memfree_x( reqdata.bv_val, ctx );
3565 pcache_exop_query_delete(
3569 BackendDB *bd = op->o_bd;
3571 struct berval uuid = BER_BVNULL,
3573 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3575 ber_tag_t tag = LBER_DEFAULT;
3577 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3581 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3582 &tag, &op->o_req_ndn, uuidp,
3583 &rs->sr_text, op->o_tmpmemctx );
3584 if ( rs->sr_err != LDAP_SUCCESS ) {
3588 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3589 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3590 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3592 if ( !BER_BVISNULL( &uuid ) ) {
3593 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3596 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3597 op->o_log_prefix, buf, 0 );
3599 op->o_req_dn = op->o_req_ndn;
3601 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3602 rs->sr_err = backend_check_restrictions( op, rs,
3603 (struct berval *)&pcache_exop_QUERY_DELETE );
3604 if ( rs->sr_err != LDAP_SUCCESS ) {
3608 if ( op->o_bd->be_extended == NULL ) {
3609 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3610 "backend does not support extended operations" );
3614 op->o_bd->be_extended( op, rs );
3617 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3618 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3619 BER_BVZERO( &op->o_req_ndn );
3620 BER_BVZERO( &op->o_req_dn );
3623 if ( !BER_BVISNULL( &uuid ) ) {
3624 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3633 pcache_op_extended( Operation *op, SlapReply *rs )
3635 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3636 cache_manager *cm = on->on_bi.bi_private;
3638 #ifdef PCACHE_CONTROL_PRIVDB
3639 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3640 return pcache_op_privdb( op, rs );
3642 #endif /* PCACHE_CONTROL_PRIVDB */
3644 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3645 struct berval uuid = BER_BVNULL;
3646 ber_tag_t tag = LBER_DEFAULT;
3648 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3649 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3650 assert( rs->sr_err == LDAP_SUCCESS );
3652 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3653 /* remove all queries related to the selected entry */
3654 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3655 cm, &op->o_req_ndn, &uuid );
3657 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3658 if ( !BER_BVISNULL( &uuid ) ) {
3659 /* remove the selected query */
3660 rs->sr_err = pcache_remove_query_from_cache( op,
3664 /* TODO: remove all queries */
3665 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3666 rs->sr_text = "deletion of all queries not implemented";
3670 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3675 #endif /* PCACHE_EXOP_QUERY_DELETE */
3677 static slap_overinst pcache;
3679 static char *obsolete_names[] = {
3684 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3686 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3691 struct berval debugbv = BER_BVC("pcache");
3693 code = slap_loglevel_get( &debugbv, &pcache_debug );
3698 #ifdef PCACHE_CONTROL_PRIVDB
3699 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3700 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3701 parse_privdb_ctrl, &privDB_cid );
3702 if ( code != LDAP_SUCCESS ) {
3703 Debug( LDAP_DEBUG_ANY,
3704 "pcache_initialize: failed to register control %s (%d)\n",
3705 PCACHE_CONTROL_PRIVDB, code, 0 );
3708 #endif /* PCACHE_CONTROL_PRIVDB */
3710 #ifdef PCACHE_EXOP_QUERY_DELETE
3711 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3712 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3714 if ( code != LDAP_SUCCESS ) {
3715 Debug( LDAP_DEBUG_ANY,
3716 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3720 #endif /* PCACHE_EXOP_QUERY_DELETE */
3722 for ( i = 0; as[i].desc != NULL; i++ ) {
3723 code = register_at( as[i].desc, as[i].adp, 0 );
3725 Debug( LDAP_DEBUG_ANY,
3726 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3731 pcache.on_bi.bi_type = "pcache";
3732 pcache.on_bi.bi_obsolete_names = obsolete_names;
3733 pcache.on_bi.bi_db_init = pcache_db_init;
3734 pcache.on_bi.bi_db_config = pcache_db_config;
3735 pcache.on_bi.bi_db_open = pcache_db_open;
3736 pcache.on_bi.bi_db_close = pcache_db_close;
3737 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3739 pcache.on_bi.bi_op_search = pcache_op_search;
3740 #ifdef PCACHE_CONTROL_PRIVDB
3741 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3742 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3743 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3744 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3745 pcache.on_bi.bi_op_add = pcache_op_privdb;
3746 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3747 #endif /* PCACHE_CONTROL_PRIVDB */
3748 #ifdef PCACHE_EXOP_QUERY_DELETE
3749 pcache.on_bi.bi_extended = pcache_op_extended;
3750 #elif defined( PCACHE_CONTROL_PRIVDB )
3751 pcache.on_bi.bi_extended = pcache_op_privdb;
3754 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3756 pcache.on_bi.bi_cf_ocs = pcocs;
3758 code = config_register_schema( pccfg, pcocs );
3759 if ( code ) return code;
3761 return overlay_register( &pcache );
3764 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3765 int init_module(int argc, char *argv[]) {
3766 return pcache_initialize();
3770 #endif /* defined(SLAPD_OVER_PROXYCACHE) */