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 ) {
2101 /* execute, if possible */
2102 func = &cm->db.be_bind;
2103 if ( func[ type ] != NULL ) {
2104 Operation op2 = *op;
2108 return func[ type ]( &op2, rs );
2112 /* otherwise fall back to error */
2113 save_cb = op->o_callback;
2114 op->o_callback = NULL;
2115 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2116 "operation not supported with pcachePrivDB control" );
2117 op->o_callback = save_cb;
2121 #endif /* PCACHE_CONTROL_PRIVDB */
2128 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2129 cache_manager *cm = on->on_bi.bi_private;
2130 query_manager* qm = cm->qm;
2134 AttributeName *filter_attrs = NULL;
2137 QueryTemplate *qtemp = NULL;
2140 CachedQuery *answerable = NULL;
2143 int fattr_got_oc = 0;
2145 struct berval tempstr;
2147 #ifdef PCACHE_CONTROL_PRIVDB
2148 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2149 return pcache_op_privdb( op, rs );
2151 #endif /* PCACHE_CONTROL_PRIVDB */
2153 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2155 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2156 &fattr_cnt, &fattr_got_oc )) {
2157 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2158 return SLAP_CB_CONTINUE;
2161 Debug( pcache_debug, "query template of incoming query = %s\n",
2162 tempstr.bv_val, 0, 0 );
2164 /* FIXME: cannot cache/answer requests with pagedResults control */
2167 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2169 query.filter = op->ors_filter;
2170 query.base = op->o_req_ndn;
2171 query.scope = op->ors_scope;
2173 /* check for query containment */
2174 if (attr_set > -1) {
2175 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2176 for (; qt; qt = qt->qtnext ) {
2177 /* find if template i can potentially answer tempstr */
2178 if (qt->querystr.bv_len != tempstr.bv_len ||
2179 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2183 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2184 op->ors_filterstr.bv_val, 0, 0 );
2185 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2191 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2194 /* Need to clear the callbacks of the original operation,
2195 * in case there are other overlays */
2196 BackendDB *save_bd = op->o_bd;
2197 slap_callback *save_cb = op->o_callback;
2199 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2200 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2201 if ( BER_BVISNULL( &answerable->q_uuid )) {
2202 /* No entries cached, just an empty result set */
2204 send_ldap_result( op, rs );
2207 op->o_callback = NULL;
2208 i = cm->db.bd_info->bi_op_search( op, rs );
2210 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2212 op->o_callback = save_cb;
2216 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2218 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2219 if (cm->num_cached_queries >= cm->max_queries) {
2222 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2224 if (op->ors_attrsonly)
2229 struct search_info *si;
2231 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2232 query.filter = filter_dup(op->ors_filter, NULL);
2233 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2234 if ( !qtemp->t_attrs.count ) {
2235 qtemp->t_attrs.count = add_filter_attrs(op,
2236 &qtemp->t_attrs.attrs,
2237 &qm->attr_sets[attr_set],
2238 filter_attrs, fattr_cnt, fattr_got_oc);
2240 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2242 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2243 cb->sc_response = pcache_response;
2244 cb->sc_cleanup = NULL;
2245 cb->sc_private = (cb+1);
2246 si = cb->sc_private;
2250 si->max = cm->num_entries_limit ;
2255 si->save_attrs = op->ors_attrs;
2257 op->ors_attrs = qtemp->t_attrs.attrs;
2259 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2260 cb->sc_next = op->o_callback;
2261 op->o_callback = cb;
2264 slap_callback **pcb;
2266 /* need to move the callback at the end, in case other
2267 * overlays are present, so that the final entry is
2268 * actually cached */
2270 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2275 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2279 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2281 return SLAP_CB_CONTINUE;
2286 AttributeName* attrs,
2294 for ( ; attrs[count].an_name.bv_val; count++ );
2297 /* recognize a single "*" or a "1.1" */
2300 attrs = slap_anlist_all_user_attributes;
2302 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2307 for ( i = 0; i < num; i++ ) {
2311 if ( count > qm->attr_sets[i].count ) {
2316 if ( !qm->attr_sets[i].count ) {
2322 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2323 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2346 struct re_s *rtask = arg;
2347 slap_overinst *on = rtask->arg;
2348 cache_manager *cm = on->on_bi.bi_private;
2349 query_manager *qm = cm->qm;
2350 Connection conn = {0};
2351 OperationBuffer opbuf;
2354 SlapReply rs = {REP_RESULT};
2356 int return_val, pause = 1;
2357 QueryTemplate* templ;
2359 connection_fake_init( &conn, &opbuf, ctx );
2363 op->o_dn = cm->db.be_rootdn;
2364 op->o_ndn = cm->db.be_rootndn;
2368 for (templ = qm->templates; templ; templ=templ->qmnext) {
2369 query = templ->query_last;
2370 if ( query ) pause = 0;
2371 op->o_time = slap_get_time();
2372 while (query && (query->expiry_time < op->o_time)) {
2374 Debug( pcache_debug, "Lock CR index = %p\n",
2375 (void *) templ, 0, 0 );
2376 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2377 if ( query == templ->query_last ) {
2379 remove_from_template(query, templ);
2380 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2381 (void *) templ, templ->no_of_queries, 0 );
2382 Debug( pcache_debug, "Unlock CR index = %p\n",
2383 (void *) templ, 0, 0 );
2385 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2387 query = templ->query_last;
2390 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2391 remove_query(qm, query);
2392 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2393 if ( BER_BVISNULL( &query->q_uuid ))
2396 return_val = remove_query_data(op, &rs, &query->q_uuid);
2397 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2399 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2400 cm->cur_entries -= return_val;
2401 cm->num_cached_queries--;
2402 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2403 cm->num_cached_queries, 0, 0 );
2404 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2405 Debug( pcache_debug,
2406 "STALE QUERY REMOVED, CACHE ="
2408 cm->cur_entries, 0, 0 );
2410 query = templ->query_last;
2413 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2414 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2415 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2417 /* If there were no queries, defer processing for a while */
2418 cm->cc_paused = pause;
2419 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2421 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2426 #define MAX_ATTR_SETS 500
2436 static ConfigDriver pc_cf_gen;
2437 static ConfigLDAPadd pc_ldadd;
2438 static ConfigCfAdd pc_cfadd;
2440 static ConfigTable pccfg[] = {
2441 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2443 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2444 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2445 "DESC 'ProxyCache basic parameters' "
2446 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2447 { "proxyattrset", "index> <attributes...",
2448 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2449 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2450 "DESC 'A set of attributes to cache' "
2451 "SYNTAX OMsDirectoryString )", NULL, NULL },
2452 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2453 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2454 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2455 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2456 "SYNTAX OMsDirectoryString )", NULL, NULL },
2457 { "response-callback", "head|tail(default)",
2458 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2459 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2460 "DESC 'Response callback position in overlay stack' "
2461 "SYNTAX OMsDirectoryString )", NULL, NULL },
2462 { "proxyCacheQueries", "queries",
2463 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2464 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2465 "DESC 'Maximum number of queries to cache' "
2466 "SYNTAX OMsInteger )", NULL, NULL },
2467 { "proxySaveQueries", "TRUE|FALSE",
2468 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2469 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2470 "DESC 'Save cached queries for hot restart' "
2471 "SYNTAX OMsBoolean )", NULL, NULL },
2473 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2476 static ConfigOCs pcocs[] = {
2477 { "( OLcfgOvOc:2.1 "
2478 "NAME 'olcPcacheConfig' "
2479 "DESC 'ProxyCache configuration' "
2480 "SUP olcOverlayConfig "
2481 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2482 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2483 Cft_Overlay, pccfg, NULL, pc_cfadd },
2484 { "( OLcfgOvOc:2.2 "
2485 "NAME 'olcPcacheDatabase' "
2486 "DESC 'Cache database configuration' "
2487 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2492 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2497 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2498 p->ce_bi->bi_cf_ocs != pcocs )
2499 return LDAP_CONSTRAINT_VIOLATION;
2501 on = (slap_overinst *)p->ce_bi;
2502 cm = on->on_bi.bi_private;
2504 return LDAP_SUCCESS;
2508 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2510 CfEntryInfo *pe = p->e_private;
2511 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2512 cache_manager *cm = on->on_bi.bi_private;
2515 /* FIXME: should not hardcode "olcDatabase" here */
2516 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2517 bv.bv_val = ca->cr_msg;
2520 /* We can only create this entry if the database is table-driven
2522 if ( cm->db.bd_info->bi_cf_ocs )
2523 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2530 pc_cf_gen( ConfigArgs *c )
2532 slap_overinst *on = (slap_overinst *)c->bi;
2533 cache_manager* cm = on->on_bi.bi_private;
2534 query_manager* qm = cm->qm;
2535 QueryTemplate* temp;
2536 AttributeName* attr_name;
2537 AttributeName* attrarray;
2538 const char* text=NULL;
2543 if ( c->op == SLAP_CONFIG_EMIT ) {
2547 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2548 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2549 cm->num_entries_limit, cm->cc_period );
2550 bv.bv_val = c->cr_msg;
2551 value_add_one( &c->rvalue_vals, &bv );
2554 for (i=0; i<cm->numattrsets; i++) {
2555 if ( !qm->attr_sets[i].count ) continue;
2557 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2559 /* count the attr length */
2560 for ( attr_name = qm->attr_sets[i].attrs;
2561 attr_name->an_name.bv_val; attr_name++ )
2562 bv.bv_len += attr_name->an_name.bv_len + 1;
2564 bv.bv_val = ch_malloc( bv.bv_len+1 );
2565 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2566 for ( attr_name = qm->attr_sets[i].attrs;
2567 attr_name->an_name.bv_val; attr_name++ ) {
2569 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2571 ber_bvarray_add( &c->rvalue_vals, &bv );
2573 if ( !c->rvalue_vals )
2577 for (temp=qm->templates; temp; temp=temp->qmnext) {
2578 if ( temp->negttl ) {
2579 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2581 temp->attr_set_index,
2585 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2586 temp->attr_set_index,
2589 bv.bv_len += temp->querystr.bv_len + 2;
2590 bv.bv_val = ch_malloc( bv.bv_len+1 );
2593 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2595 strcpy( ptr, c->cr_msg );
2596 ber_bvarray_add( &c->rvalue_vals, &bv );
2598 if ( !c->rvalue_vals )
2602 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2603 BER_BVSTR( &bv, "head" );
2605 BER_BVSTR( &bv, "tail" );
2607 value_add_one( &c->rvalue_vals, &bv );
2610 c->value_int = cm->max_queries;
2614 } else if ( c->op == LDAP_MOD_DELETE ) {
2615 return 1; /* FIXME */
2627 if ( cm->numattrsets > 0 ) {
2628 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2629 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2633 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2634 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2636 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2639 if ( cm->numattrsets <= 0 ) {
2640 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2641 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2644 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2645 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2646 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2650 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2651 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2652 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2656 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2657 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2659 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2662 if ( cm->max_entries <= 0 ) {
2663 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2664 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2668 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2669 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2671 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2674 if ( cm->num_entries_limit <= 0 ) {
2675 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2676 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2679 if ( cm->num_entries_limit > cm->max_entries ) {
2680 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2681 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2685 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2686 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2688 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2691 cm->cc_period = (time_t)t;
2692 Debug( pcache_debug,
2693 "Total # of attribute sets to be cached = %d.\n",
2694 cm->numattrsets, 0, 0 );
2695 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2696 sizeof( struct attr_set ) );
2699 if ( cm->numattrsets == 0 ) {
2700 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2701 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2704 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2705 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2707 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2711 if ( num < 0 || num >= cm->numattrsets ) {
2712 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2713 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2714 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2717 qm->attr_sets[num].flags |= PC_CONFIGURED;
2718 if ( c->argc == 2 ) {
2720 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2721 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2722 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2725 } else if ( c->argc == 3 ) {
2726 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2727 qm->attr_sets[num].count = 1;
2728 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2729 sizeof( AttributeName ) );
2730 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2733 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2734 qm->attr_sets[num].count = 1;
2735 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2736 sizeof( AttributeName ) );
2737 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2740 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2743 /* else: fallthru */
2745 } else if ( c->argc == 4 ) {
2746 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2747 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2749 qm->attr_sets[num].count = 2;
2750 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2751 sizeof( AttributeName ) );
2752 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2753 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2756 /* else: fallthru */
2759 if ( c->argc > 2 ) {
2760 int all_user = 0, all_op = 0;
2762 qm->attr_sets[num].count = c->argc - 2;
2763 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2764 sizeof( AttributeName ) );
2765 attr_name = qm->attr_sets[num].attrs;
2766 for ( i = 2; i < c->argc; i++ ) {
2767 attr_name->an_desc = NULL;
2768 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2769 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2770 "invalid attr #%d \"%s\" in attrlist",
2771 i - 2, c->argv[i] );
2772 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2773 ch_free( qm->attr_sets[num].attrs );
2774 qm->attr_sets[num].attrs = NULL;
2775 qm->attr_sets[num].count = 0;
2778 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2780 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2781 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2783 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2785 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2786 strcpy( c->cr_msg, text );
2787 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2788 ch_free( qm->attr_sets[num].attrs );
2789 qm->attr_sets[num].attrs = NULL;
2790 qm->attr_sets[num].count = 0;
2793 attr_name->an_name = attr_name->an_desc->ad_cname;
2795 attr_name->an_oc = NULL;
2796 attr_name->an_oc_exclude = 0;
2797 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2798 qm->attr_sets[num].flags |= PC_GOT_OC;
2800 BER_BVZERO( &attr_name->an_name );
2803 /* warn if list contains both "*" and "+" */
2804 if ( i > 4 && all_user && all_op ) {
2805 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2806 "warning: attribute list contains \"*\" and \"+\"" );
2807 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2812 if ( cm->numattrsets == 0 ) {
2813 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2814 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2817 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2818 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2820 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2824 if ( i < 0 || i >= cm->numattrsets ||
2825 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2826 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2827 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2828 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2831 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2832 temp->qmnext = qm->templates;
2833 qm->templates = temp;
2834 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2835 temp->query = temp->query_last = NULL;
2836 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2837 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2839 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2842 temp->ttl = (time_t)t;
2843 if ( c->argc == 5 ) {
2844 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2845 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2846 "unable to parse template negttl=\"%s\"",
2848 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2851 temp->negttl = (time_t)t;
2856 temp->no_of_queries = 0;
2858 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2859 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2860 Debug( pcache_debug, " query template: %s\n",
2861 temp->querystr.bv_val, 0, 0 );
2862 temp->attr_set_index = i;
2863 qm->attr_sets[i].flags |= PC_REFERENCED;
2864 temp->qtnext = qm->attr_sets[i].templates;
2865 qm->attr_sets[i].templates = temp;
2866 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2867 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2868 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2869 Debug( pcache_debug, "\t%s\n",
2870 attrarray[i].an_name.bv_val, 0, 0 );
2874 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2875 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2877 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2878 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2881 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2882 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2887 if ( c->value_int <= 0 ) {
2888 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2889 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2892 cm->max_queries = c->value_int;
2907 slap_overinst *on = (slap_overinst *)be->bd_info;
2908 cache_manager* cm = on->on_bi.bi_private;
2910 /* Something for the cache database? */
2911 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2912 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2914 return SLAP_CONF_UNKNOWN;
2922 slap_overinst *on = (slap_overinst *)be->bd_info;
2926 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2927 on->on_bi.bi_private = cm;
2929 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2932 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2933 cm->db.be_private = NULL;
2934 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2936 cm->numattrsets = 0;
2937 cm->num_entries_limit = 5;
2938 cm->num_cached_queries = 0;
2939 cm->max_entries = 0;
2940 cm->cur_entries = 0;
2941 cm->max_queries = 10000;
2942 cm->save_queries = 0;
2943 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2944 cm->cc_period = 1000;
2947 qm->attr_sets = NULL;
2948 qm->templates = NULL;
2950 qm->lru_bottom = NULL;
2952 qm->qcfunc = query_containment;
2953 qm->crfunc = cache_replacement;
2954 qm->addfunc = add_query;
2955 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2957 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2962 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2964 assert( op->o_tag == LDAP_REQ_SEARCH );
2966 if ( rs->sr_type == REP_SEARCH ) {
2969 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2973 assert( a->a_nvals != NULL );
2975 valsp = op->o_callback->sc_private;
2976 assert( *valsp == NULL );
2978 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2986 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
2988 assert( op->o_tag == LDAP_REQ_SEARCH );
2990 if ( rs->sr_type == REP_SEARCH ) {
2991 int *countp = (int *)op->o_callback->sc_private;
3004 slap_overinst *on = (slap_overinst *)be->bd_info;
3005 cache_manager *cm = on->on_bi.bi_private;
3006 query_manager* qm = cm->qm;
3007 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3009 /* check attr sets */
3010 for ( i = 0; i < cm->numattrsets; i++) {
3011 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3012 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3013 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3017 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3021 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3022 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3027 if ( ncf || rf || nrf ) {
3028 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3029 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3030 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3037 /* need to inherit something from the original database... */
3038 cm->db.be_def_limit = be->be_def_limit;
3039 cm->db.be_limits = be->be_limits;
3040 cm->db.be_acl = be->be_acl;
3041 cm->db.be_dfltaccess = be->be_dfltaccess;
3043 if ( SLAP_DBMONITORING( be ) ) {
3044 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3047 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3050 rc = backend_startup_one( &cm->db, NULL );
3052 /* There is no runqueue in TOOL mode */
3053 if ( slapMode & SLAP_SERVER_MODE ) {
3054 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3055 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3056 consistency_check, on,
3057 "pcache_consistency", be->be_suffix[0].bv_val );
3058 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3060 /* Cached database must have the rootdn */
3061 if ( BER_BVISNULL( &cm->db.be_rootndn )
3062 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3064 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3065 "underlying database of type \"%s\"\n"
3066 " serving naming context \"%s\"\n"
3067 " has no \"rootdn\", required by \"proxycache\".\n",
3068 on->on_info->oi_orig->bi_type,
3069 cm->db.be_suffix[0].bv_val, 0 );
3073 if ( cm->save_queries ) {
3074 void *thrctx = ldap_pvt_thread_pool_context();
3075 Connection conn = { 0 };
3076 OperationBuffer opbuf;
3078 slap_callback cb = { 0 };
3079 SlapReply rs = { 0 };
3080 BerVarray vals = NULL;
3081 Filter f = { 0 }, f2 = { 0 };
3082 #ifdef LDAP_COMP_MATCH
3083 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
3085 AttributeAssertion ava = { NULL, BER_BVNULL };
3087 AttributeName attrs[ 2 ] = { 0 };
3089 connection_fake_init( &conn, &opbuf, thrctx );
3094 op->o_tag = LDAP_REQ_SEARCH;
3095 op->o_protocol = LDAP_VERSION3;
3096 cb.sc_response = pcache_cachedquery_open_cb;
3097 cb.sc_private = &vals;
3098 op->o_callback = &cb;
3099 op->o_time = slap_get_time();
3100 op->o_do_not_cache = 1;
3101 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3103 op->o_dn = cm->db.be_rootdn;
3104 op->o_ndn = cm->db.be_rootndn;
3105 op->o_req_dn = cm->db.be_suffix[ 0 ];
3106 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3108 op->ors_scope = LDAP_SCOPE_BASE;
3109 op->ors_deref = LDAP_DEREF_NEVER;
3111 op->ors_tlimit = SLAP_NO_LIMIT;
3112 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3113 f.f_choice = LDAP_FILTER_PRESENT;
3114 f.f_desc = ad_cachedQueryURL;
3115 op->ors_filter = &f;
3116 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3117 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3118 op->ors_attrs = attrs;
3119 op->ors_attrsonly = 0;
3121 rc = op->o_bd->be_search( op, &rs );
3122 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3125 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3126 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3127 cm->num_cached_queries++;
3131 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3134 /* count cached entries */
3135 f.f_choice = LDAP_FILTER_NOT;
3137 f2.f_choice = LDAP_FILTER_EQUALITY;
3139 f2.f_av_desc = slap_schema.si_ad_objectClass;
3140 BER_BVSTR( &f2.f_av_value, "glue" );
3141 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3143 op->ors_slimit = SLAP_NO_LIMIT;
3144 op->ors_scope = LDAP_SCOPE_SUBTREE;
3145 op->ors_attrs = slap_anlist_no_attrs;
3147 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3149 op->o_callback->sc_private = &rs.sr_nentries;
3151 rc = op->o_bd->be_search( op, &rs );
3153 cm->cur_entries = rs.sr_nentries;
3164 pcache_free_qbase( void *v )
3170 tavl_free( qb->scopes[i], NULL );
3180 slap_overinst *on = (slap_overinst *)be->bd_info;
3181 cache_manager *cm = on->on_bi.bi_private;
3182 query_manager *qm = cm->qm;
3186 if ( cm->save_queries ) {
3188 BerVarray vals = NULL;
3191 Connection conn = { 0 };
3192 OperationBuffer opbuf;
3194 slap_callback cb = { 0 };
3196 SlapReply rs = { REP_RESULT };
3197 Modifications mod = { 0 };
3199 thrctx = ldap_pvt_thread_pool_context();
3201 connection_fake_init( &conn, &opbuf, thrctx );
3204 if ( qm->templates != NULL ) {
3205 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3206 for ( qc = tm->query; qc; qc = qc->next ) {
3209 if ( query2url( op, qc, &bv ) == 0 ) {
3210 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3217 op->o_dn = cm->db.be_rootdn;
3218 op->o_ndn = cm->db.be_rootndn;
3220 op->o_tag = LDAP_REQ_MODIFY;
3221 op->o_protocol = LDAP_VERSION3;
3222 cb.sc_response = slap_null_cb;
3223 op->o_callback = &cb;
3224 op->o_time = slap_get_time();
3225 op->o_do_not_cache = 1;
3226 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3228 op->o_req_dn = op->o_bd->be_suffix[0];
3229 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3231 mod.sml_op = LDAP_MOD_REPLACE;
3233 mod.sml_desc = ad_cachedQueryURL;
3234 mod.sml_type = ad_cachedQueryURL->ad_cname;
3235 mod.sml_values = vals;
3236 mod.sml_nvalues = NULL;
3237 mod.sml_next = NULL;
3238 Debug( pcache_debug,
3239 "%sSETTING CACHED QUERY URLS\n",
3240 vals == NULL ? "RE" : "", 0, 0 );
3242 op->orm_modlist = &mod;
3244 op->o_bd->be_modify( op, &rs );
3246 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3249 /* cleanup stuff inherited from the original database... */
3250 cm->db.be_limits = NULL;
3251 cm->db.be_acl = NULL;
3253 /* stop the thread ... */
3255 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3256 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3257 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3259 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3260 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3263 if ( cm->db.bd_info->bi_db_close ) {
3264 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3266 while ( (tm = qm->templates) != NULL ) {
3267 CachedQuery *qc, *qn;
3268 qm->templates = tm->qmnext;
3269 for ( qc = tm->query; qc; qc = qn ) {
3273 avl_free( tm->qbase, pcache_free_qbase );
3274 free( tm->querystr.bv_val );
3275 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3276 free( tm->t_attrs.attrs );
3280 for ( i=0; i<cm->numattrsets; i++ ) {
3281 free( qm->attr_sets[i].attrs );
3283 free( qm->attr_sets );
3284 qm->attr_sets = NULL;
3295 slap_overinst *on = (slap_overinst *)be->bd_info;
3296 cache_manager *cm = on->on_bi.bi_private;
3297 query_manager *qm = cm->qm;
3299 if ( cm->db.be_private != NULL ) {
3300 backend_stopdown_one( &cm->db );
3303 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3304 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3311 #ifdef PCACHE_CONTROL_PRIVDB
3313 Control ::= SEQUENCE {
3314 controlType LDAPOID,
3315 criticality BOOLEAN DEFAULT FALSE,
3316 controlValue OCTET STRING OPTIONAL }
3318 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3320 * criticality must be TRUE; controlValue must be absent.
3328 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3329 rs->sr_text = "privateDB control specified multiple times";
3330 return LDAP_PROTOCOL_ERROR;
3333 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3334 rs->sr_text = "privateDB control value not absent";
3335 return LDAP_PROTOCOL_ERROR;
3338 if ( !ctrl->ldctl_iscritical ) {
3339 rs->sr_text = "privateDB control criticality required";
3340 return LDAP_PROTOCOL_ERROR;
3343 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3345 return LDAP_SUCCESS;
3348 static char *extops[] = {
3349 LDAP_EXOP_MODIFY_PASSWD,
3352 #endif /* PCACHE_CONTROL_PRIVDB */
3354 #ifdef PCACHE_EXOP_QUERY_DELETE
3355 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3357 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3358 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3359 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3362 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3363 requestName [0] LDAPOID,
3364 requestValue [1] OCTET STRING OPTIONAL }
3366 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3368 requestValue ::= SEQUENCE { CHOICE {
3370 entryDN [1] LDAPDN },
3371 queryID [2] OCTET STRING (SIZE(16))
3372 -- constrained to UUID }
3374 * Either baseDN or entryDN must be present, to allow database selection.
3376 * 1. if baseDN and queryID are present, then the query corresponding
3377 * to queryID is deleted;
3378 * 2. if baseDN is present and queryID is absent, then all queries
3380 * 3. if entryDN is present and queryID is absent, then all queries
3381 * corresponding to the queryID values present in entryDN are deleted;
3382 * 4. if entryDN and queryID are present, then all queries
3383 * corresponding to the queryID values present in entryDN are deleted,
3384 * but only if the value of queryID is contained in the entry;
3386 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3387 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3388 * or by removing the database files.
3390 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3391 COMPONENTS OF LDAPResult,
3392 responseName [10] LDAPOID OPTIONAL,
3393 responseValue [11] OCTET STRING OPTIONAL }
3395 * responseName and responseValue must be absent.
3399 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3400 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3401 * - if ndn != NULL, it is set to the normalized DN in the request
3402 * corresponding to either the baseDN or the entryDN, according
3403 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3404 * be freed by the caller.
3405 * - if uuid != NULL, it is set to point to the normalized UUID;
3406 * memory is malloc'ed on the Operation's slab, and must
3407 * be freed by the caller.
3410 pcache_parse_query_delete(
3414 struct berval *uuid,
3418 int rc = LDAP_SUCCESS;
3421 BerElementBuffer berbuf;
3422 BerElement *ber = (BerElement *)&berbuf;
3423 struct berval reqdata = BER_BVNULL;
3435 if ( in == NULL || in->bv_len == 0 ) {
3436 *text = "empty request data field in queryDelete exop";
3437 return LDAP_PROTOCOL_ERROR;
3440 ber_dupbv_x( &reqdata, in, ctx );
3442 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3443 ber_init2( ber, &reqdata, 0 );
3445 tag = ber_scanf( ber, "{" /*}*/ );
3447 if ( tag == LBER_ERROR ) {
3448 Debug( LDAP_DEBUG_TRACE,
3449 "pcache_parse_query_delete: decoding error.\n",
3451 goto decoding_error;
3454 tag = ber_peek_tag( ber, &len );
3455 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3456 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3460 if ( ndn != NULL ) {
3463 tag = ber_scanf( ber, "m", &dn );
3464 if ( tag == LBER_ERROR ) {
3465 Debug( LDAP_DEBUG_TRACE,
3466 "pcache_parse_query_delete: DN parse failed.\n",
3468 goto decoding_error;
3471 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3472 if ( rc != LDAP_SUCCESS ) {
3473 *text = "invalid DN in queryDelete exop request data";
3478 tag = ber_scanf( ber, "x" /* "m" */ );
3479 if ( tag == LBER_DEFAULT ) {
3480 goto decoding_error;
3484 tag = ber_peek_tag( ber, &len );
3487 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3488 if ( uuid != NULL ) {
3490 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3492 tag = ber_scanf( ber, "m", &bv );
3493 if ( tag == LBER_ERROR ) {
3494 Debug( LDAP_DEBUG_TRACE,
3495 "pcache_parse_query_delete: UUID parse failed.\n",
3497 goto decoding_error;
3500 if ( bv.bv_len != 16 ) {
3501 Debug( LDAP_DEBUG_TRACE,
3502 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3503 (unsigned long)bv.bv_len, 0, 0 );
3504 goto decoding_error;
3507 rc = lutil_uuidstr_from_normalized(
3508 bv.bv_val, bv.bv_len,
3509 uuidbuf, sizeof( uuidbuf ) );
3511 goto decoding_error;
3513 ber_str2bv( uuidbuf, rc, 1, uuid );
3517 tag = ber_skip_tag( ber, &len );
3518 if ( tag == LBER_DEFAULT ) {
3519 goto decoding_error;
3523 Debug( LDAP_DEBUG_TRACE,
3524 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3525 (unsigned long)len, 0, 0 );
3526 goto decoding_error;
3530 tag = ber_peek_tag( ber, &len );
3533 if ( tag != LBER_DEFAULT || len != 0 ) {
3535 Debug( LDAP_DEBUG_TRACE,
3536 "pcache_parse_query_delete: decoding error\n",
3538 rc = LDAP_PROTOCOL_ERROR;
3539 *text = "queryDelete data decoding error";
3542 if ( ndn && !BER_BVISNULL( ndn ) ) {
3543 slap_sl_free( ndn->bv_val, ctx );
3547 if ( uuid && !BER_BVISNULL( uuid ) ) {
3548 slap_sl_free( uuid->bv_val, ctx );
3553 if ( !BER_BVISNULL( &reqdata ) ) {
3554 ber_memfree_x( reqdata.bv_val, ctx );
3561 pcache_exop_query_delete(
3565 BackendDB *bd = op->o_bd;
3567 struct berval uuid = BER_BVNULL,
3569 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3571 ber_tag_t tag = LBER_DEFAULT;
3573 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3577 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3578 &tag, &op->o_req_ndn, uuidp,
3579 &rs->sr_text, op->o_tmpmemctx );
3580 if ( rs->sr_err != LDAP_SUCCESS ) {
3584 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3585 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3586 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3588 if ( !BER_BVISNULL( &uuid ) ) {
3589 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3592 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3593 op->o_log_prefix, buf, 0 );
3595 op->o_req_dn = op->o_req_ndn;
3597 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3598 rs->sr_err = backend_check_restrictions( op, rs,
3599 (struct berval *)&pcache_exop_QUERY_DELETE );
3600 if ( rs->sr_err != LDAP_SUCCESS ) {
3604 if ( op->o_bd->be_extended == NULL ) {
3605 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3606 "backend does not support extended operations" );
3610 op->o_bd->be_extended( op, rs );
3613 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3614 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3615 BER_BVZERO( &op->o_req_ndn );
3616 BER_BVZERO( &op->o_req_dn );
3619 if ( !BER_BVISNULL( &uuid ) ) {
3620 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3629 pcache_op_extended( Operation *op, SlapReply *rs )
3631 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3632 cache_manager *cm = on->on_bi.bi_private;
3634 #ifdef PCACHE_CONTROL_PRIVDB
3635 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3636 return pcache_op_privdb( op, rs );
3638 #endif /* PCACHE_CONTROL_PRIVDB */
3640 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3641 struct berval uuid = BER_BVNULL;
3642 ber_tag_t tag = LBER_DEFAULT;
3644 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3645 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3646 assert( rs->sr_err == LDAP_SUCCESS );
3648 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3649 /* remove all queries related to the selected entry */
3650 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3651 cm, &op->o_req_ndn, &uuid );
3653 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3654 if ( !BER_BVISNULL( &uuid ) ) {
3655 /* remove the selected query */
3656 rs->sr_err = pcache_remove_query_from_cache( op,
3660 /* TODO: remove all queries */
3661 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3662 rs->sr_text = "deletion of all queries not implemented";
3666 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3671 #endif /* PCACHE_EXOP_QUERY_DELETE */
3673 static slap_overinst pcache;
3675 static char *obsolete_names[] = {
3680 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3682 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3687 struct berval debugbv = BER_BVC("pcache");
3689 code = slap_loglevel_get( &debugbv, &pcache_debug );
3694 #ifdef PCACHE_CONTROL_PRIVDB
3695 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3696 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3697 parse_privdb_ctrl, &privDB_cid );
3698 if ( code != LDAP_SUCCESS ) {
3699 Debug( LDAP_DEBUG_ANY,
3700 "pcache_initialize: failed to register control %s (%d)\n",
3701 PCACHE_CONTROL_PRIVDB, code, 0 );
3704 #endif /* PCACHE_CONTROL_PRIVDB */
3706 #ifdef PCACHE_EXOP_QUERY_DELETE
3707 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3708 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3710 if ( code != LDAP_SUCCESS ) {
3711 Debug( LDAP_DEBUG_ANY,
3712 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3716 #endif /* PCACHE_EXOP_QUERY_DELETE */
3718 for ( i = 0; as[i].desc != NULL; i++ ) {
3719 code = register_at( as[i].desc, as[i].adp, 0 );
3721 Debug( LDAP_DEBUG_ANY,
3722 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3727 pcache.on_bi.bi_type = "pcache";
3728 pcache.on_bi.bi_obsolete_names = obsolete_names;
3729 pcache.on_bi.bi_db_init = pcache_db_init;
3730 pcache.on_bi.bi_db_config = pcache_db_config;
3731 pcache.on_bi.bi_db_open = pcache_db_open;
3732 pcache.on_bi.bi_db_close = pcache_db_close;
3733 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3735 pcache.on_bi.bi_op_search = pcache_op_search;
3736 #ifdef PCACHE_CONTROL_PRIVDB
3737 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3738 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3739 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3740 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3741 pcache.on_bi.bi_op_add = pcache_op_privdb;
3742 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3743 #endif /* PCACHE_CONTROL_PRIVDB */
3744 #ifdef PCACHE_EXOP_QUERY_DELETE
3745 pcache.on_bi.bi_extended = pcache_op_extended;
3746 #elif defined( PCACHE_CONTROL_PRIVDB )
3747 pcache.on_bi.bi_extended = pcache_op_privdb;
3750 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3752 pcache.on_bi.bi_cf_ocs = pcocs;
3754 code = config_register_schema( pccfg, pcocs );
3755 if ( code ) return code;
3757 return overlay_register( &pcache );
3760 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3761 int init_module(int argc, char *argv[]) {
3762 return pcache_initialize();
3766 #endif /* defined(SLAPD_OVER_PROXYCACHE) */