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 */
76 struct query_template_s *qtemp; /* template of the query */
77 time_t expiry_time; /* time till the query is considered valid */
78 struct cached_query_s *next; /* next query in the template */
79 struct cached_query_s *prev; /* previous query in the template */
80 struct cached_query_s *lru_up; /* previous query in the LRU list */
81 struct cached_query_s *lru_down; /* next query in the LRU list */
87 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
89 * <base> ::= CachedQuery.qbase->base
90 * <scope> ::= CachedQuery.scope
91 * <filter> ::= filter2bv(CachedQuery.filter)
92 * <uuid> ::= CachedQuery.q_uuid
93 * <attrset> ::= CachedQuery.qtemp->attr_set_index
94 * <expiry> ::= CachedQuery.expiry_time
96 * quick hack: parse URI, call add_query() and then fix
97 * CachedQuery.expiry_time and CachedQuery.q_uuid
101 * Represents a set of projected attributes.
105 struct query_template_s *templates;
106 AttributeName* attrs; /* specifies the set */
108 #define PC_CONFIGURED (0x1)
109 #define PC_REFERENCED (0x2)
110 #define PC_GOT_OC (0x4)
111 int count; /* number of attributes */
114 /* struct representing a query template
115 * e.g. template string = &(cn=)(mail=)
117 typedef struct query_template_s {
118 struct query_template_s *qtnext;
119 struct query_template_s *qmnext;
122 CachedQuery* query; /* most recent query cached for the template */
123 CachedQuery* query_last; /* oldest query cached for the template */
124 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
125 struct berval querystr; /* Filter string corresponding to the QT */
127 int attr_set_index; /* determines the projected attributes */
128 int no_of_queries; /* Total number of queries in the template */
129 time_t ttl; /* TTL for the queries of this template */
130 time_t negttl; /* TTL for negative results */
131 time_t limitttl; /* TTL for sizelimit exceeding results */
132 struct attr_set t_attrs; /* filter attrs + attr_set */
140 } pc_caching_reason_t;
142 static const char *pc_caching_reason_str[] = {
151 struct query_manager_s;
153 /* prototypes for functions for 1) query containment
154 * 2) query addition, 3) cache replacement
156 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
157 Query*, QueryTemplate*);
158 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
159 Query*, QueryTemplate*, pc_caching_reason_t);
160 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
162 /* LDAP query cache */
163 typedef struct query_manager_s {
164 struct attr_set* attr_sets; /* possible sets of projected attributes */
165 QueryTemplate* templates; /* cacheable templates */
167 CachedQuery* lru_top; /* top and bottom of LRU list */
168 CachedQuery* lru_bottom;
170 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
172 /* Query cache methods */
173 QCfunc *qcfunc; /* Query containment*/
174 CRfunc *crfunc; /* cache replacement */
175 AddQueryfunc *addfunc; /* add query */
178 /* LDAP query cache manager */
179 typedef struct cache_manager_s {
180 BackendDB db; /* underlying database */
181 unsigned long num_cached_queries; /* total number of cached queries */
182 unsigned long max_queries; /* upper bound on # of cached queries */
183 int save_queries; /* save cached queries across restarts */
184 int numattrsets; /* number of attribute sets */
185 int cur_entries; /* current number of entries cached */
186 int max_entries; /* max number of entries cached */
187 int num_entries_limit; /* max # of entries in a cacheable query */
189 char response_cb; /* install the response callback
190 * at the tail of the callback list */
191 #define PCACHE_RESPONSE_CB_HEAD 0
192 #define PCACHE_RESPONSE_CB_TAIL 1
194 time_t cc_period; /* interval between successive consistency checks (sec) */
198 ldap_pvt_thread_mutex_t cache_mutex;
200 query_manager* qm; /* query cache managed by the cache manager */
203 static int pcache_debug;
205 #ifdef PCACHE_CONTROL_PRIVDB
206 static int privDB_cid;
207 #endif /* PCACHE_CONTROL_PRIVDB */
209 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
212 AttributeDescription **adp;
214 { "( 1.3.6.1.4.1.4203.666.11.9.1.1 "
216 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
217 "EQUALITY octetStringMatch "
218 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
219 "NO-USER-MODIFICATION "
220 "USAGE directoryOperation )",
222 { "( 1.3.6.1.4.1.4203.666.11.9.1.2 "
223 "NAME 'cachedQueryURL' "
224 "DESC 'URI describing a cached query' "
225 "EQUALITY caseExactMatch "
226 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
227 "NO-USER-MODIFICATION "
228 "USAGE directoryOperation )",
229 &ad_cachedQueryURL },
238 AttributeName** filter_attrs,
240 int* filter_got_oc );
247 QueryTemplate *templ,
248 pc_caching_reason_t why );
254 struct berval *query_uuid );
257 * Turn a cached query into its URL representation
260 query2url( Operation *op, CachedQuery *q, struct berval *urlbv )
262 struct berval bv_scope,
264 char attrset_buf[ 32 ],
267 ber_len_t attrset_len,
270 ldap_pvt_scope2bv( q->scope, &bv_scope );
271 filter2bv_x( op, q->filter, &bv_filter );
272 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
273 "%lu", (unsigned long)q->qtemp->attr_set_index );
274 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
275 "%lu", (unsigned long)q->expiry_time );
277 urlbv->bv_len = STRLENOF( "ldap:///" )
278 + q->qbase->base.bv_len
283 + STRLENOF( "?x-uuid=" )
285 + STRLENOF( ",x-attrset=" )
287 + STRLENOF( ",x-expiry=" )
289 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
290 ptr = lutil_strcopy( ptr, "ldap:///" );
291 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
292 ptr = lutil_strcopy( ptr, "??" );
293 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
294 ptr = lutil_strcopy( ptr, "?" );
295 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
296 ptr = lutil_strcopy( ptr, "?x-uuid=" );
297 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
298 ptr = lutil_strcopy( ptr, ",x-attrset=" );
299 ptr = lutil_strcopy( ptr, attrset_buf );
300 ptr = lutil_strcopy( ptr, ",x-expiry=" );
301 ptr = lutil_strcopy( ptr, expiry_buf );
303 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
309 * Turn an URL representing a formerly cached query into a cached query,
310 * and try to cache it
321 LDAPURLDesc *lud = NULL;
323 tempstr = BER_BVNULL,
333 rc = ldap_url_parse( url, &lud );
334 if ( rc != LDAP_URL_SUCCESS ) {
338 /* non-allowed fields */
339 if ( lud->lud_host != NULL ) {
344 if ( lud->lud_attrs != NULL ) {
350 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
355 /* required fields */
356 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
361 switch ( lud->lud_scope ) {
362 case LDAP_SCOPE_BASE:
363 case LDAP_SCOPE_ONELEVEL:
364 case LDAP_SCOPE_SUBTREE:
365 case LDAP_SCOPE_SUBORDINATE:
373 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
378 if ( lud->lud_exts == NULL ) {
383 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
384 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
385 struct berval tmpUUID;
386 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
388 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
389 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
390 if ( rc != LDAP_SUCCESS ) {
395 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
396 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
402 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
405 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
409 expiry_time = (time_t)l;
423 if ( !got_attrset ) {
433 /* ignore expired queries */
434 if ( expiry_time <= slap_get_time()) {
436 SlapReply rs2 = { 0 };
438 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
440 (void)remove_query_data( &op2, &rs2, &uuid );
445 ber_str2bv( lud->lud_dn, 0, 0, &base );
446 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
447 if ( rc != LDAP_SUCCESS ) {
450 query.scope = lud->lud_scope;
451 query.filter = str2filter( lud->lud_filter );
453 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
455 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
456 ch_free( tempstr.bv_val );
461 /* check for query containment */
462 qt = qm->attr_sets[attrset].templates;
463 for ( ; qt; qt = qt->qtnext ) {
464 /* find if template i can potentially answer tempstr */
465 if ( bvmatch( &qt->querystr, &tempstr ) ) {
475 cq = add_query( op, qm, &query, qt, PC_POSITIVE );
477 cq->expiry_time = expiry_time;
480 /* it's now into cq->filter */
490 if ( query.filter != NULL ) filter_free( query.filter );
491 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
492 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
493 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
494 if ( lud != NULL ) ldap_free_urldesc( lud );
499 /* Return 1 for an added entry, else 0 */
504 struct berval* query_uuid )
507 Modifications* modlist = NULL;
508 const char* text = NULL;
510 char textbuf[SLAP_TEXT_BUFLEN];
511 size_t textlen = sizeof(textbuf);
513 SlapReply sreply = {REP_RESULT};
515 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
520 /* add queryId attribute */
521 attr_merge_one( e, ad_queryId, query_uuid, NULL );
523 /* append the attribute list from the fetched entry */
524 e->e_attrs->a_next = attr;
526 op->o_tag = LDAP_REQ_ADD;
527 op->o_protocol = LDAP_VERSION3;
528 op->o_callback = &cb;
529 op->o_time = slap_get_time();
530 op->o_do_not_cache = 1;
533 op->o_req_dn = e->e_name;
534 op->o_req_ndn = e->e_nname;
535 rc = op->o_bd->be_add( op, &sreply );
537 if ( rc != LDAP_SUCCESS ) {
538 if ( rc == LDAP_ALREADY_EXISTS ) {
539 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
540 modlist->sml_op = LDAP_MOD_ADD;
541 op->o_tag = LDAP_REQ_MODIFY;
542 op->orm_modlist = modlist;
543 op->o_bd->be_modify( op, &sreply );
544 slap_mods_free( modlist, 1 );
545 } else if ( rc == LDAP_REFERRAL ||
546 rc == LDAP_NO_SUCH_OBJECT ) {
547 syncrepl_add_glue( op, e );
556 if ( op->ora_e == e )
557 be_entry_release_w( op, e );
564 /* Length-ordered sort on normalized DNs */
565 static int pcache_dn_cmp( const void *v1, const void *v2 )
567 const Qbase *q1 = v1, *q2 = v2;
569 int rc = q1->base.bv_len - q2->base.bv_len;
571 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
575 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
578 dif = bv1->bv_len - bv2->bv_len;
580 if ( dif > 0 ) len -= dif;
581 len = memcmp( bv1->bv_val, bv2->bv_val, len );
587 /* compare the first value in each filter */
588 static int pcache_filter_cmp( const void *v1, const void *v2 )
590 const CachedQuery *q1 = v1, *q2 =v2;
591 int rc, weight1, weight2;
593 switch( q1->first->f_choice ) {
594 case LDAP_FILTER_PRESENT:
597 case LDAP_FILTER_EQUALITY:
605 switch( q2->first->f_choice ) {
606 case LDAP_FILTER_PRESENT:
609 case LDAP_FILTER_EQUALITY:
617 rc = weight1 - weight2;
622 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
625 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
627 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
628 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
629 rc = lex_bvcmp( &q1->first->f_sub_initial,
630 &q2->first->f_sub_initial );
634 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
638 if ( q1->first->f_sub_any ) {
639 if ( q2->first->f_sub_any ) {
640 rc = lex_bvcmp( q1->first->f_sub_any,
641 q2->first->f_sub_any );
645 } else if ( q2->first->f_sub_any ) {
649 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
650 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
651 rc = lex_bvcmp( &q1->first->f_sub_final,
652 &q2->first->f_sub_final );
656 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
660 rc = lex_bvcmp( &q1->first->f_mr_value,
661 &q2->first->f_mr_value );
670 /* add query on top of LRU list */
672 add_query_on_top (query_manager* qm, CachedQuery* qc)
674 CachedQuery* top = qm->lru_top;
685 Debug( pcache_debug, "Base of added query = %s\n",
686 qc->qbase->base.bv_val, 0, 0 );
689 /* remove_query from LRU list */
692 remove_query (query_manager* qm, CachedQuery* qc)
715 qc->lru_up = qc->lru_down = NULL;
718 /* find and remove string2 from string1
719 * from start if position = 1,
720 * from end if position = 3,
721 * from anywhere if position = 2
722 * string1 is overwritten if position = 2.
726 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
737 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
738 ber2->bv_val, ber2->bv_len )) {
740 ber1->bv_val += ber2->bv_len;
741 ber1->bv_len -= ber2->bv_len;
746 ber1->bv_val[ber1->bv_len] = '\0';
747 temp = strstr( ber1->bv_val, ber2->bv_val );
749 strcpy( temp, temp+ber2->bv_len );
750 ber1->bv_len -= ber2->bv_len;
756 if ( ber1->bv_len >= ber2->bv_len &&
757 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
760 ber1->bv_len -= ber2->bv_len;
768 static struct berval*
769 merge_init_final(Operation *op, struct berval* init, struct berval* any,
770 struct berval* final)
772 struct berval* merged, *temp;
773 int i, any_count, count;
775 for (any_count=0; any && any[any_count].bv_val; any_count++)
785 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
790 ber_dupbv_x( temp, init, op->o_tmpmemctx );
794 for (i=0; i<any_count; i++) {
795 ber_dupbv_x( temp, any, op->o_tmpmemctx );
800 ber_dupbv_x( temp, final, op->o_tmpmemctx );
807 /* Each element in stored must be found in incoming. Incoming is overwritten.
810 strings_containment(struct berval* stored, struct berval* incoming)
812 struct berval* element;
816 for ( element=stored; element->bv_val != NULL; element++ ) {
817 for (j = k; incoming[j].bv_val != NULL; j++) {
818 if (find_and_remove(&(incoming[j]), element, 2)) {
835 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
839 struct berval init_incoming;
840 struct berval final_incoming;
841 struct berval *remaining_incoming = NULL;
843 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
844 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
847 init_incoming = incoming->f_sub_initial;
848 final_incoming = incoming->f_sub_final;
850 if (find_and_remove(&init_incoming,
851 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
852 &(stored->f_sub_final), 3))
854 if (stored->f_sub_any == NULL) {
858 remaining_incoming = merge_init_final(op, &init_incoming,
859 incoming->f_sub_any, &final_incoming);
860 rc = strings_containment(stored->f_sub_any, remaining_incoming);
861 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
868 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
870 struct berval incoming_val[2];
873 incoming_val[1] = incoming->f_av_value;
875 if (find_and_remove(incoming_val+1,
876 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
877 &(stored->f_sub_final), 3)) {
878 if (stored->f_sub_any == NULL){
882 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
883 BER_BVZERO( incoming_val+1 );
884 rc = strings_containment(stored->f_sub_any, incoming_val);
885 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
892 filter_first( Filter *f )
894 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
901 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
905 MatchingRule* mrule = NULL;
906 int res=0, eqpass= 0;
914 /* substring matches sort to the end, and we just have to
915 * walk the entire list.
917 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
918 ptr = tavl_end( root, 1 );
921 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
922 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
931 /* an incoming substr query can only be satisfied by a cached
934 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
935 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
938 /* an incoming eq query can be satisfied by a cached eq or substr
941 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
943 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
944 nextpass: eqpass = 1;
945 ptr = tavl_end( root, 1 );
950 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
956 switch (fs->f_choice) {
957 case LDAP_FILTER_EQUALITY:
958 if (fi->f_choice == LDAP_FILTER_EQUALITY)
959 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
965 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
972 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
973 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
974 &(fi->f_ava->aa_value),
975 &(fs->f_ava->aa_value), &text);
976 if (rc != LDAP_SUCCESS) {
979 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
982 switch (fs->f_choice) {
984 case LDAP_FILTER_AND:
989 case LDAP_FILTER_SUBSTRINGS:
990 /* check if the equality query can be
991 * answered with cached substring query */
992 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
993 && substr_containment_equality( op,
996 /* check if the substring query can be
997 * answered with cached substring query */
998 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
999 ) && substr_containment_substr( op,
1005 case LDAP_FILTER_PRESENT:
1010 case LDAP_FILTER_EQUALITY:
1016 case LDAP_FILTER_GE:
1017 if (mrule && ret >= 0)
1022 case LDAP_FILTER_LE:
1023 if (mrule && ret <= 0)
1028 case LDAP_FILTER_NOT:
1034 } while((res) && (fi != NULL) && (fs != NULL));
1038 ptr = tavl_next( ptr, dir );
1043 /* check whether query is contained in any of
1044 * the cached queries in template
1046 static CachedQuery *
1047 query_containment(Operation *op, query_manager *qm,
1049 QueryTemplate *templa)
1052 int depth = 0, tscope;
1053 Qbase qbase, *qbptr = NULL;
1056 if (query->filter != NULL) {
1059 Debug( pcache_debug, "Lock QC index = %p\n",
1060 (void *) templa, 0, 0 );
1061 qbase.base = query->base;
1063 first = filter_first( query->filter );
1065 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1068 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1070 tscope = query->scope;
1071 /* Find a matching scope:
1072 * match at depth 0 OK
1075 * subord at depth > 0 OK
1076 * subtree at any depth OK
1078 * subtree or subord at any depth OK
1080 * subtree or subord at any depth OK
1082 * subord at depth > 0 OK
1083 * subtree at any depth OK
1085 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1086 switch ( query->scope ) {
1087 case LDAP_SCOPE_BASE:
1088 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1089 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1090 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1092 case LDAP_SCOPE_ONE:
1093 if ( tscope == LDAP_SCOPE_BASE )
1094 tscope = LDAP_SCOPE_ONE;
1095 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1096 if ( !depth ) break;
1097 if ( tscope < LDAP_SCOPE_SUBTREE )
1098 tscope = LDAP_SCOPE_SUBTREE;
1100 case LDAP_SCOPE_SUBTREE:
1101 if ( tscope < LDAP_SCOPE_SUBTREE )
1102 tscope = LDAP_SCOPE_SUBTREE;
1103 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1105 case LDAP_SCOPE_CHILDREN:
1106 if ( tscope < LDAP_SCOPE_SUBTREE )
1107 tscope = LDAP_SCOPE_SUBTREE;
1110 if ( !qbptr->scopes[tscope] ) continue;
1113 qc = find_filter( op, qbptr->scopes[tscope],
1114 query->filter, first );
1116 if ( qc->q_sizelimit ) {
1117 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1120 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1121 if (qm->lru_top != qc) {
1122 remove_query(qm, qc);
1123 add_query_on_top(qm, qc);
1125 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1130 if ( be_issuffix( op->o_bd, &qbase.base ))
1133 dnParent( &qbase.base, &pdn );
1138 Debug( pcache_debug,
1139 "Not answerable: Unlock QC index=%p\n",
1140 (void *) templa, 0, 0 );
1141 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1147 free_query (CachedQuery* qc)
1149 free(qc->q_uuid.bv_val);
1150 filter_free(qc->filter);
1155 /* Add query to query cache */
1156 static CachedQuery *
1161 QueryTemplate *templ,
1162 pc_caching_reason_t why )
1164 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1170 new_cached_query->qtemp = templ;
1171 BER_BVZERO( &new_cached_query->q_uuid );
1172 new_cached_query->q_sizelimit = 0;
1180 ttl = templ->negttl;
1184 ttl = templ->limitttl;
1191 new_cached_query->expiry_time = slap_get_time() + ttl;
1192 new_cached_query->lru_up = NULL;
1193 new_cached_query->lru_down = NULL;
1194 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1195 (long) new_cached_query->expiry_time,
1196 pc_caching_reason_str[ why ], 0 );
1198 new_cached_query->scope = query->scope;
1199 new_cached_query->filter = query->filter;
1200 new_cached_query->first = first = filter_first( query->filter );
1202 qb.base = query->base;
1204 /* Adding a query */
1205 Debug( pcache_debug, "Lock AQ index = %p\n",
1206 (void *) templ, 0, 0 );
1207 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1208 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1210 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1211 qbase->base.bv_len = qb.base.bv_len;
1212 qbase->base.bv_val = (char *)(qbase+1);
1213 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1214 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1215 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1217 new_cached_query->next = templ->query;
1218 new_cached_query->prev = NULL;
1219 new_cached_query->qbase = qbase;
1220 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1221 pcache_filter_cmp, avl_dup_error );
1224 if (templ->query == NULL)
1225 templ->query_last = new_cached_query;
1227 templ->query->prev = new_cached_query;
1228 templ->query = new_cached_query;
1229 templ->no_of_queries++;
1231 ch_free( new_cached_query );
1232 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1233 query->filter, first );
1234 filter_free( query->filter );
1236 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1237 (void *) templ, templ->no_of_queries, 0 );
1239 Debug( pcache_debug, "Unlock AQ index = %p \n",
1240 (void *) templ, 0, 0 );
1241 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1243 /* Adding on top of LRU list */
1245 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1246 add_query_on_top(qm, new_cached_query);
1247 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1249 return rc == 0 ? new_cached_query : NULL;
1253 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1255 if (!qc->prev && !qc->next) {
1256 template->query_last = template->query = NULL;
1257 } else if (qc->prev == NULL) {
1258 qc->next->prev = NULL;
1259 template->query = qc->next;
1260 } else if (qc->next == NULL) {
1261 qc->prev->next = NULL;
1262 template->query_last = qc->prev;
1264 qc->next->prev = qc->prev;
1265 qc->prev->next = qc->next;
1267 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1268 qc->qbase->queries--;
1269 if ( qc->qbase->queries == 0 ) {
1270 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1271 ch_free( qc->qbase );
1275 template->no_of_queries--;
1278 /* remove bottom query of LRU list from the query cache */
1280 * NOTE: slight change in functionality.
1282 * - if result->bv_val is NULL, the query at the bottom of the LRU
1284 * - otherwise, the query whose UUID is *result is removed
1285 * - if not found, result->bv_val is zeroed
1288 cache_replacement(query_manager* qm, struct berval *result)
1290 CachedQuery* bottom;
1291 QueryTemplate *temp;
1293 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1294 if ( BER_BVISNULL( result ) ) {
1295 bottom = qm->lru_bottom;
1298 Debug ( pcache_debug,
1299 "Cache replacement invoked without "
1300 "any query in LRU list\n", 0, 0, 0 );
1301 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1306 for ( bottom = qm->lru_bottom;
1308 bottom = bottom->lru_up )
1310 if ( bvmatch( result, &bottom->q_uuid ) ) {
1316 Debug ( pcache_debug,
1317 "Could not find query with uuid=\"%s\""
1318 "in LRU list\n", result->bv_val, 0, 0 );
1319 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1320 BER_BVZERO( result );
1325 temp = bottom->qtemp;
1326 remove_query(qm, bottom);
1327 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1329 *result = bottom->q_uuid;
1330 BER_BVZERO( &bottom->q_uuid );
1332 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1333 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1334 remove_from_template(bottom, temp);
1335 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1336 (void *) temp, temp->no_of_queries, 0 );
1337 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1338 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1343 struct query_info *next;
1355 struct query_info *qi;
1358 if ( rs->sr_type != REP_SEARCH ) return 0;
1360 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1361 if ( attr == NULL ) return 0;
1363 for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1365 assert( count > 0 );
1366 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1367 qi->next = op->o_callback->sc_private;
1368 op->o_callback->sc_private = qi;
1369 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1370 qi->del = ( count == 1 );
1379 struct berval *query_uuid )
1381 struct query_info *qi, *qnext;
1382 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1383 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1384 Filter filter = {LDAP_FILTER_EQUALITY};
1385 SlapReply sreply = {REP_RESULT};
1386 slap_callback cb = { NULL, remove_func, NULL, NULL };
1389 sreply.sr_entry = NULL;
1390 sreply.sr_nentries = 0;
1391 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1392 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1393 filter.f_ava = &ava;
1394 filter.f_av_desc = ad_queryId;
1395 filter.f_av_value = *query_uuid;
1397 op->o_tag = LDAP_REQ_SEARCH;
1398 op->o_protocol = LDAP_VERSION3;
1399 op->o_callback = &cb;
1400 op->o_time = slap_get_time();
1401 op->o_do_not_cache = 1;
1403 op->o_req_dn = op->o_bd->be_suffix[0];
1404 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1405 op->ors_scope = LDAP_SCOPE_SUBTREE;
1406 op->ors_deref = LDAP_DEREF_NEVER;
1407 op->ors_slimit = SLAP_NO_LIMIT;
1408 op->ors_tlimit = SLAP_NO_LIMIT;
1409 op->ors_filter = &filter;
1410 op->ors_filterstr.bv_val = filter_str;
1411 op->ors_filterstr.bv_len = strlen(filter_str);
1412 op->ors_attrs = NULL;
1413 op->ors_attrsonly = 0;
1415 op->o_bd->be_search( op, &sreply );
1417 for ( qi=cb.sc_private; qi; qi=qnext ) {
1420 op->o_req_dn = qi->xdn;
1421 op->o_req_ndn = qi->xdn;
1424 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1425 query_uuid->bv_val, 0, 0 );
1427 op->o_tag = LDAP_REQ_DELETE;
1429 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1435 struct berval vals[2];
1437 vals[0] = *query_uuid;
1438 vals[1].bv_val = NULL;
1440 mod.sml_op = LDAP_MOD_DELETE;
1442 mod.sml_desc = ad_queryId;
1443 mod.sml_type = ad_queryId->ad_cname;
1444 mod.sml_values = vals;
1445 mod.sml_nvalues = NULL;
1446 mod.sml_next = NULL;
1447 Debug( pcache_debug,
1448 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1449 query_uuid->bv_val, 0, 0 );
1451 op->orm_modlist = &mod;
1453 op->o_bd->be_modify( op, &sreply );
1455 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1456 op->o_tmpfree( qi, op->o_tmpmemctx );
1463 AttributeName* attrs,
1472 struct berval *fstr,
1473 AttributeName** filter_attrs,
1475 int* filter_got_oc )
1477 AttributeDescription *ad;
1479 switch ( f->f_choice ) {
1480 case LDAP_FILTER_EQUALITY:
1482 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1483 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1486 case LDAP_FILTER_GE:
1488 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1489 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1492 case LDAP_FILTER_LE:
1494 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1495 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1498 case LDAP_FILTER_APPROX:
1500 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1501 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1504 case LDAP_FILTER_SUBSTRINGS:
1506 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1507 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1510 case LDAP_FILTER_PRESENT:
1512 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1513 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1516 case LDAP_FILTER_AND:
1517 case LDAP_FILTER_OR:
1518 case LDAP_FILTER_NOT: {
1520 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1521 f->f_choice == LDAP_FILTER_AND ? '&' :
1522 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1523 fstr->bv_len += sizeof("(%") - 1;
1525 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1526 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1530 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1531 fstr->bv_len += sizeof(")") - 1;
1537 strcpy( fstr->bv_val, "(?=?)" );
1538 fstr->bv_len += sizeof("(?=?)")-1;
1542 if ( filter_attrs != NULL ) {
1543 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1544 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1546 (*filter_attrs)[*filter_cnt].an_desc = ad;
1547 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1548 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1549 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1550 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1552 if ( ad == slap_schema.si_ad_objectClass )
1559 struct search_info {
1562 QueryTemplate *qtemp;
1563 AttributeName* save_attrs; /* original attributes, saved for response */
1568 int slimit_exceeded;
1569 pc_caching_reason_t caching_reason;
1574 remove_query_and_data(
1578 struct berval *uuid )
1580 query_manager* qm = cm->qm;
1582 qm->crfunc( qm, uuid );
1583 if ( !BER_BVISNULL( uuid ) ) {
1586 Debug( pcache_debug,
1587 "Removing query UUID %s\n",
1588 uuid->bv_val, 0, 0 );
1589 return_val = remove_query_data( op, rs, uuid );
1590 Debug( pcache_debug,
1591 "QUERY REMOVED, SIZE=%d\n",
1593 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1594 cm->cur_entries -= return_val;
1595 cm->num_cached_queries--;
1596 Debug( pcache_debug,
1597 "STORED QUERIES = %lu\n",
1598 cm->num_cached_queries, 0, 0 );
1599 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1600 Debug( pcache_debug,
1601 "QUERY REMOVED, CACHE ="
1603 cm->cur_entries, 0, 0 );
1608 * Callback used to fetch queryId values based on entryUUID;
1609 * used by pcache_remove_entries_from_cache()
1612 fetch_queryId_cb( Operation *op, SlapReply *rs )
1616 /* only care about searchEntry responses */
1617 if ( rs->sr_type != REP_SEARCH ) {
1621 /* allow only one response per entryUUID */
1622 if ( op->o_callback->sc_private != NULL ) {
1628 /* copy all queryId values into callback's private data */
1629 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1631 BerVarray vals = NULL;
1633 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1634 op->o_callback->sc_private = (void *)vals;
1638 /* clear entry if required */
1639 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1640 entry_free( rs->sr_entry );
1641 rs->sr_entry = NULL;
1642 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1649 * Call that allows to remove a set of entries from the cache,
1650 * by forcing the removal of all the related queries.
1653 pcache_remove_entries_from_cache(
1656 BerVarray entryUUIDs )
1658 Connection conn = { 0 };
1659 OperationBuffer opbuf;
1661 slap_callback sc = { 0 };
1662 SlapReply rs = { REP_RESULT };
1664 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1665 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1666 AttributeName attrs[ 2 ] = { 0 };
1670 void *thrctx = ldap_pvt_thread_pool_context();
1672 connection_fake_init( &conn, &opbuf, thrctx );
1680 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1681 op->ors_scope = LDAP_SCOPE_SUBTREE;
1682 op->ors_deref = LDAP_DEREF_NEVER;
1683 f.f_choice = LDAP_FILTER_EQUALITY;
1685 ava.aa_desc = slap_schema.si_ad_entryUUID;
1686 op->ors_filter = &f;
1688 op->ors_tlimit = SLAP_NO_LIMIT;
1689 attrs[ 0 ].an_desc = ad_queryId;
1690 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1691 op->ors_attrs = attrs;
1692 op->ors_attrsonly = 0;
1694 op->o_req_dn = cm->db.be_suffix[ 0 ];
1695 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1697 op->o_tag = LDAP_REQ_SEARCH;
1698 op->o_protocol = LDAP_VERSION3;
1699 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1701 op->o_dn = op->o_bd->be_rootdn;
1702 op->o_ndn = op->o_bd->be_rootndn;
1703 sc.sc_response = fetch_queryId_cb;
1704 op->o_callback = ≻
1706 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1707 BerVarray vals = NULL;
1709 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1710 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1711 op->ors_filterstr.bv_val = filtbuf;
1712 ava.aa_value = entryUUIDs[ s ];
1714 rc = op->o_bd->be_search( op, &rs );
1715 if ( rc != LDAP_SUCCESS ) {
1719 vals = (BerVarray)op->o_callback->sc_private;
1720 if ( vals != NULL ) {
1723 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1724 struct berval val = vals[ i ];
1726 remove_query_and_data( op, &rs, cm, &val );
1728 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1729 ch_free( val.bv_val );
1733 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1734 op->o_callback->sc_private = NULL;
1742 * Call that allows to remove a query from the cache.
1745 pcache_remove_query_from_cache(
1748 struct berval *queryid )
1750 Operation op2 = *op;
1751 SlapReply rs2 = { 0 };
1755 /* remove the selected query */
1756 remove_query_and_data( &op2, &rs2, cm, queryid );
1758 return LDAP_SUCCESS;
1762 * Call that allows to remove a set of queries related to an entry
1763 * from the cache; if queryid is not null, the entry must belong to
1764 * the query indicated by queryid.
1767 pcache_remove_entry_queries_from_cache(
1771 struct berval *queryid )
1773 Connection conn = { 0 };
1774 OperationBuffer opbuf;
1776 slap_callback sc = { 0 };
1777 SlapReply rs = { REP_RESULT };
1779 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1780 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1781 AttributeName attrs[ 2 ] = { 0 };
1784 BerVarray vals = NULL;
1787 void *thrctx = ldap_pvt_thread_pool_context();
1789 connection_fake_init( &conn, &opbuf, thrctx );
1797 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1798 op->ors_scope = LDAP_SCOPE_BASE;
1799 op->ors_deref = LDAP_DEREF_NEVER;
1800 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1801 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1802 f.f_choice = LDAP_FILTER_PRESENT;
1803 f.f_desc = slap_schema.si_ad_objectClass;
1806 op->ors_filterstr.bv_len = snprintf( filter_str,
1807 sizeof( filter_str ), "(%s=%s)",
1808 ad_queryId->ad_cname.bv_val, queryid->bv_val );
1809 f.f_choice = LDAP_FILTER_EQUALITY;
1811 f.f_av_desc = ad_queryId;
1812 f.f_av_value = *queryid;
1814 op->ors_filter = &f;
1816 op->ors_tlimit = SLAP_NO_LIMIT;
1817 attrs[ 0 ].an_desc = ad_queryId;
1818 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1819 op->ors_attrs = attrs;
1820 op->ors_attrsonly = 0;
1822 op->o_req_dn = *ndn;
1823 op->o_req_ndn = *ndn;
1825 op->o_tag = LDAP_REQ_SEARCH;
1826 op->o_protocol = LDAP_VERSION3;
1827 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1829 op->o_dn = op->o_bd->be_rootdn;
1830 op->o_ndn = op->o_bd->be_rootndn;
1831 sc.sc_response = fetch_queryId_cb;
1832 op->o_callback = ≻
1834 rc = op->o_bd->be_search( op, &rs );
1835 if ( rc != LDAP_SUCCESS ) {
1839 vals = (BerVarray)op->o_callback->sc_private;
1840 if ( vals != NULL ) {
1843 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1844 struct berval val = vals[ i ];
1846 remove_query_and_data( op, &rs, cm, &val );
1848 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1849 ch_free( val.bv_val );
1853 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1856 return LDAP_SUCCESS;
1863 struct berval *query_uuid )
1865 struct search_info *si = op->o_callback->sc_private;
1866 slap_overinst *on = si->on;
1867 cache_manager *cm = on->on_bi.bi_private;
1870 struct berval crp_uuid;
1871 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1872 Operation op_tmp = *op;
1874 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1875 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1877 op_tmp.o_bd = &cm->db;
1878 op_tmp.o_dn = cm->db.be_rootdn;
1879 op_tmp.o_ndn = cm->db.be_rootndn;
1881 Debug( pcache_debug, "UUID for query being added = %s\n",
1884 for ( e=si->head; e; e=si->head ) {
1885 si->head = e->e_private;
1886 e->e_private = NULL;
1887 while ( cm->cur_entries > (cm->max_entries) ) {
1888 BER_BVZERO( &crp_uuid );
1889 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1892 return_val = merge_entry(&op_tmp, e, query_uuid);
1893 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1894 cm->cur_entries += return_val;
1895 Debug( pcache_debug,
1896 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1897 cm->cur_entries, 0, 0 );
1899 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1906 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1907 slap_callback *cb = op->o_callback;
1908 struct search_info *si = cb->sc_private;
1909 slap_overinst *on = si->on;
1910 cache_manager *cm = on->on_bi.bi_private;
1911 query_manager* qm = cm->qm;
1913 if ( rs->sr_type == REP_SEARCH ) {
1916 /* don't return more entries than requested by the client */
1917 if ( si->slimit && rs->sr_nentries >= si->slimit ) {
1918 si->slimit_exceeded = 1;
1921 /* If we haven't exceeded the limit for this query,
1922 * build a chain of answers to store. If we hit the
1923 * limit, empty the chain and ignore the rest.
1926 if ( si->count < si->max ) {
1928 e = entry_dup( rs->sr_entry );
1929 if ( !si->head ) si->head = e;
1930 if ( si->tail ) si->tail->e_private = e;
1936 for (;si->head; si->head=e) {
1937 e = si->head->e_private;
1938 si->head->e_private = NULL;
1939 entry_free(si->head);
1947 if ( rs->sr_type == REP_RESULT ||
1948 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
1950 if ( si->save_attrs != NULL ) {
1951 rs->sr_attrs = si->save_attrs;
1952 op->ors_attrs = si->save_attrs;
1954 if ( op->o_abandon || rs->sr_err == SLAPD_ABANDON ) {
1955 filter_free( si->query.filter );
1957 /* duplicate query, free it */
1959 for (;si->head; si->head=e) {
1960 e = si->head->e_private;
1961 si->head->e_private = NULL;
1962 entry_free(si->head);
1965 op->o_callback = op->o_callback->sc_next;
1966 op->o_tmpfree( cb, op->o_tmpmemctx );
1967 } else if ( si->caching_reason != PC_IGNORE ) {
1968 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
1969 si->qtemp, si->caching_reason );
1972 switch ( si->caching_reason ) {
1974 cache_entries( op, rs, &qc->q_uuid );
1978 qc->q_sizelimit = rs->sr_nentries;
1981 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1982 cm->num_cached_queries++;
1983 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1984 cm->num_cached_queries, 0, 0 );
1985 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1987 /* If the consistency checker suspended itself,
1990 if ( cm->cc_paused ) {
1991 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1992 if ( cm->cc_paused ) {
1994 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1996 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1999 } else if ( si->count ) {
2000 /* duplicate query, free it */
2002 for (;si->head; si->head=e) {
2003 e = si->head->e_private;
2004 si->head->e_private = NULL;
2005 entry_free(si->head);
2010 filter_free( si->query.filter );
2014 return SLAP_CB_CONTINUE;
2022 struct search_info *si = op->o_callback->sc_private;
2024 if ( si->save_attrs != NULL ) {
2025 rs->sr_attrs = si->save_attrs;
2026 op->ors_attrs = si->save_attrs;
2029 if ( rs->sr_type == REP_SEARCH ) {
2030 /* don't return more entries than requested by the client */
2031 if ( si->slimit_exceeded ) {
2035 } else if ( rs->sr_type == REP_RESULT ) {
2038 if ( rs->sr_err == LDAP_SUCCESS ) {
2039 si->caching_reason = PC_POSITIVE;
2041 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2042 && si->qtemp->limitttl )
2044 si->caching_reason = PC_SIZELIMIT;
2047 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2048 rs->sr_err == LDAP_SUCCESS )
2050 si->caching_reason = PC_NEGATIVE;
2054 if ( si->slimit_exceeded ) {
2055 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2059 return SLAP_CB_CONTINUE;
2065 AttributeName** new_attrs,
2066 struct attr_set *attrs,
2067 AttributeName* filter_attrs,
2077 /* duplicate attrs */
2078 count = attrs->count + fattr_cnt;
2079 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2084 *new_attrs = (AttributeName*)ch_calloc( count + 1,
2085 sizeof(AttributeName) );
2086 for (i=0; i<attrs->count; i++) {
2087 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2088 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2090 BER_BVZERO( &(*new_attrs)[i].an_name );
2091 alluser = an_find(*new_attrs, &AllUser);
2092 allop = an_find(*new_attrs, &AllOper);
2095 for ( i=0; i<fattr_cnt; i++ ) {
2096 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2099 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2103 } else if ( alluser ) {
2106 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2107 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2108 (*new_attrs)[j].an_oc = NULL;
2109 (*new_attrs)[j].an_oc_exclude = 0;
2113 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2114 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2115 (*new_attrs)[j].an_oc = NULL;
2116 (*new_attrs)[j].an_oc_exclude = 0;
2119 BER_BVZERO( &(*new_attrs)[j].an_name );
2124 /* NOTE: this is a quick workaround to let pcache minimally interact
2125 * with pagedResults. A more articulated solutions would be to
2126 * perform the remote query without control and cache all results,
2127 * performing the pagedResults search only within the client
2128 * and the proxy. This requires pcache to understand pagedResults. */
2130 pcache_chk_controls(
2134 const char *non = "";
2135 const char *stripped = "";
2137 switch( op->o_pagedresults ) {
2138 case SLAP_CONTROL_NONCRITICAL:
2140 stripped = "; stripped";
2143 case SLAP_CONTROL_CRITICAL:
2144 Debug( pcache_debug, "%s: "
2145 "%scritical pagedResults control "
2146 "disabled with proxy cache%s.\n",
2147 op->o_log_prefix, non, stripped );
2149 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2153 rs->sr_err = SLAP_CB_CONTINUE;
2160 #ifdef PCACHE_CONTROL_PRIVDB
2166 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2167 cache_manager *cm = on->on_bi.bi_private;
2168 slap_callback *save_cb;
2171 /* skip if control is unset */
2172 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2173 return SLAP_CB_CONTINUE;
2176 /* FIXME: might be a little bit exaggerated... */
2177 if ( !be_isroot( op ) ) {
2178 save_cb = op->o_callback;
2179 op->o_callback = NULL;
2180 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2181 "pcachePrivDB: operation not allowed" );
2182 op->o_callback = save_cb;
2187 /* map tag to operation */
2188 type = slap_req2op( op->o_tag );
2189 if ( type != SLAP_OP_LAST ) {
2193 /* execute, if possible */
2194 func = &cm->db.be_bind;
2195 if ( func[ type ] != NULL ) {
2196 Operation op2 = *op;
2200 rc = func[ type ]( &op2, rs );
2201 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2202 op->o_conn->c_authz_cookie = cm->db.be_private;
2207 /* otherwise fall back to error */
2208 save_cb = op->o_callback;
2209 op->o_callback = NULL;
2210 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2211 "operation not supported with pcachePrivDB control" );
2212 op->o_callback = save_cb;
2216 #endif /* PCACHE_CONTROL_PRIVDB */
2223 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2224 cache_manager *cm = on->on_bi.bi_private;
2225 query_manager* qm = cm->qm;
2229 AttributeName *filter_attrs = NULL;
2232 QueryTemplate *qtemp = NULL;
2235 CachedQuery *answerable = NULL;
2238 int fattr_got_oc = 0;
2240 struct berval tempstr;
2242 #ifdef PCACHE_CONTROL_PRIVDB
2243 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2244 return pcache_op_privdb( op, rs );
2246 #endif /* PCACHE_CONTROL_PRIVDB */
2248 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2250 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2251 &fattr_cnt, &fattr_got_oc )) {
2252 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2253 return SLAP_CB_CONTINUE;
2256 Debug( pcache_debug, "query template of incoming query = %s\n",
2257 tempstr.bv_val, 0, 0 );
2259 /* FIXME: cannot cache/answer requests with pagedResults control */
2262 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2264 query.filter = op->ors_filter;
2265 query.base = op->o_req_ndn;
2266 query.scope = op->ors_scope;
2268 /* check for query containment */
2269 if (attr_set > -1) {
2270 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2271 for (; qt; qt = qt->qtnext ) {
2272 /* find if template i can potentially answer tempstr */
2273 if (qt->querystr.bv_len != tempstr.bv_len ||
2274 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2278 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2279 op->ors_filterstr.bv_val, 0, 0 );
2280 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2286 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2289 /* Need to clear the callbacks of the original operation,
2290 * in case there are other overlays */
2291 BackendDB *save_bd = op->o_bd;
2292 slap_callback *save_cb = op->o_callback;
2294 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2295 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2296 if ( BER_BVISNULL( &answerable->q_uuid )) {
2297 /* No entries cached, just an empty result set */
2299 send_ldap_result( op, rs );
2302 op->o_callback = NULL;
2303 i = cm->db.bd_info->bi_op_search( op, rs );
2305 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2307 op->o_callback = save_cb;
2311 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2313 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2314 if (cm->num_cached_queries >= cm->max_queries) {
2317 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2319 if (op->ors_attrsonly)
2324 struct search_info *si;
2326 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2327 query.filter = filter_dup(op->ors_filter, NULL);
2328 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2329 if ( !qtemp->t_attrs.count ) {
2330 qtemp->t_attrs.count = add_filter_attrs(op,
2331 &qtemp->t_attrs.attrs,
2332 &qm->attr_sets[attr_set],
2333 filter_attrs, fattr_cnt, fattr_got_oc);
2335 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2337 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2338 cb->sc_response = pcache_response;
2339 cb->sc_cleanup = pcache_op_cleanup;
2340 cb->sc_private = (cb+1);
2341 si = cb->sc_private;
2345 si->max = cm->num_entries_limit ;
2349 si->slimit_exceeded = 0;
2350 si->caching_reason = PC_IGNORE;
2351 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2352 si->slimit = op->ors_slimit;
2353 op->ors_slimit = cm->num_entries_limit;
2357 si->save_attrs = op->ors_attrs;
2359 op->ors_attrs = qtemp->t_attrs.attrs;
2361 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2362 cb->sc_next = op->o_callback;
2363 op->o_callback = cb;
2366 slap_callback **pcb;
2368 /* need to move the callback at the end, in case other
2369 * overlays are present, so that the final entry is
2370 * actually cached */
2372 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2377 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2381 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2383 return SLAP_CB_CONTINUE;
2388 AttributeName* attrs,
2396 for ( ; attrs[count].an_name.bv_val; count++ );
2399 /* recognize a single "*" or a "1.1" */
2402 attrs = slap_anlist_all_user_attributes;
2404 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2409 for ( i = 0; i < num; i++ ) {
2413 if ( count > qm->attr_sets[i].count ) {
2418 if ( !qm->attr_sets[i].count ) {
2424 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2425 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2448 struct re_s *rtask = arg;
2449 slap_overinst *on = rtask->arg;
2450 cache_manager *cm = on->on_bi.bi_private;
2451 query_manager *qm = cm->qm;
2452 Connection conn = {0};
2453 OperationBuffer opbuf;
2456 SlapReply rs = {REP_RESULT};
2458 int return_val, pause = 1;
2459 QueryTemplate* templ;
2461 connection_fake_init( &conn, &opbuf, ctx );
2465 op->o_dn = cm->db.be_rootdn;
2466 op->o_ndn = cm->db.be_rootndn;
2470 for (templ = qm->templates; templ; templ=templ->qmnext) {
2471 query = templ->query_last;
2472 if ( query ) pause = 0;
2473 op->o_time = slap_get_time();
2474 while (query && (query->expiry_time < op->o_time)) {
2476 Debug( pcache_debug, "Lock CR index = %p\n",
2477 (void *) templ, 0, 0 );
2478 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2479 if ( query == templ->query_last ) {
2481 remove_from_template(query, templ);
2482 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2483 (void *) templ, templ->no_of_queries, 0 );
2484 Debug( pcache_debug, "Unlock CR index = %p\n",
2485 (void *) templ, 0, 0 );
2487 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2489 query = templ->query_last;
2492 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2493 remove_query(qm, query);
2494 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2495 if ( BER_BVISNULL( &query->q_uuid ))
2498 return_val = remove_query_data(op, &rs, &query->q_uuid);
2499 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2501 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2502 cm->cur_entries -= return_val;
2503 cm->num_cached_queries--;
2504 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2505 cm->num_cached_queries, 0, 0 );
2506 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2507 Debug( pcache_debug,
2508 "STALE QUERY REMOVED, CACHE ="
2510 cm->cur_entries, 0, 0 );
2512 query = templ->query_last;
2515 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2516 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2517 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2519 /* If there were no queries, defer processing for a while */
2520 cm->cc_paused = pause;
2521 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2523 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2528 #define MAX_ATTR_SETS 500
2538 static ConfigDriver pc_cf_gen;
2539 static ConfigLDAPadd pc_ldadd;
2540 static ConfigCfAdd pc_cfadd;
2542 static ConfigTable pccfg[] = {
2543 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2545 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2546 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2547 "DESC 'ProxyCache basic parameters' "
2548 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2549 { "proxyattrset", "index> <attributes...",
2550 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2551 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2552 "DESC 'A set of attributes to cache' "
2553 "SYNTAX OMsDirectoryString )", NULL, NULL },
2554 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2555 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2556 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2557 "DESC 'Filter template, attrset, cache TTL, "
2558 "optional negative TTL, optional sizelimit TTL' "
2559 "SYNTAX OMsDirectoryString )", NULL, NULL },
2560 { "response-callback", "head|tail(default)",
2561 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2562 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2563 "DESC 'Response callback position in overlay stack' "
2564 "SYNTAX OMsDirectoryString )", NULL, NULL },
2565 { "proxyCacheQueries", "queries",
2566 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2567 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2568 "DESC 'Maximum number of queries to cache' "
2569 "SYNTAX OMsInteger )", NULL, NULL },
2570 { "proxySaveQueries", "TRUE|FALSE",
2571 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2572 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2573 "DESC 'Save cached queries for hot restart' "
2574 "SYNTAX OMsBoolean )", NULL, NULL },
2576 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2579 static ConfigOCs pcocs[] = {
2580 { "( OLcfgOvOc:2.1 "
2581 "NAME 'olcPcacheConfig' "
2582 "DESC 'ProxyCache configuration' "
2583 "SUP olcOverlayConfig "
2584 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2585 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2586 Cft_Overlay, pccfg, NULL, pc_cfadd },
2587 { "( OLcfgOvOc:2.2 "
2588 "NAME 'olcPcacheDatabase' "
2589 "DESC 'Cache database configuration' "
2590 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2595 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2600 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2601 p->ce_bi->bi_cf_ocs != pcocs )
2602 return LDAP_CONSTRAINT_VIOLATION;
2604 on = (slap_overinst *)p->ce_bi;
2605 cm = on->on_bi.bi_private;
2607 return LDAP_SUCCESS;
2611 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2613 CfEntryInfo *pe = p->e_private;
2614 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2615 cache_manager *cm = on->on_bi.bi_private;
2618 /* FIXME: should not hardcode "olcDatabase" here */
2619 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2620 bv.bv_val = ca->cr_msg;
2623 /* We can only create this entry if the database is table-driven
2625 if ( cm->db.bd_info->bi_cf_ocs )
2626 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2633 pc_cf_gen( ConfigArgs *c )
2635 slap_overinst *on = (slap_overinst *)c->bi;
2636 cache_manager* cm = on->on_bi.bi_private;
2637 query_manager* qm = cm->qm;
2638 QueryTemplate* temp;
2639 AttributeName* attr_name;
2640 AttributeName* attrarray;
2641 const char* text=NULL;
2646 if ( c->op == SLAP_CONFIG_EMIT ) {
2650 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2651 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2652 cm->num_entries_limit, cm->cc_period );
2653 bv.bv_val = c->cr_msg;
2654 value_add_one( &c->rvalue_vals, &bv );
2657 for (i=0; i<cm->numattrsets; i++) {
2658 if ( !qm->attr_sets[i].count ) continue;
2660 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2662 /* count the attr length */
2663 for ( attr_name = qm->attr_sets[i].attrs;
2664 attr_name->an_name.bv_val; attr_name++ )
2665 bv.bv_len += attr_name->an_name.bv_len + 1;
2667 bv.bv_val = ch_malloc( bv.bv_len+1 );
2668 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2669 for ( attr_name = qm->attr_sets[i].attrs;
2670 attr_name->an_name.bv_val; attr_name++ ) {
2672 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2674 ber_bvarray_add( &c->rvalue_vals, &bv );
2676 if ( !c->rvalue_vals )
2680 for (temp=qm->templates; temp; temp=temp->qmnext) {
2681 /* HEADS-UP: always print all;
2682 * if optional == 0, ignore */
2683 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2685 temp->attr_set_index,
2689 bv.bv_len += temp->querystr.bv_len + 2;
2690 bv.bv_val = ch_malloc( bv.bv_len+1 );
2693 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2695 strcpy( ptr, c->cr_msg );
2696 ber_bvarray_add( &c->rvalue_vals, &bv );
2698 if ( !c->rvalue_vals )
2702 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2703 BER_BVSTR( &bv, "head" );
2705 BER_BVSTR( &bv, "tail" );
2707 value_add_one( &c->rvalue_vals, &bv );
2710 c->value_int = cm->max_queries;
2714 } else if ( c->op == LDAP_MOD_DELETE ) {
2715 return 1; /* FIXME */
2727 if ( cm->numattrsets > 0 ) {
2728 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2729 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2733 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2734 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2736 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2739 if ( cm->numattrsets <= 0 ) {
2740 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2741 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2744 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2745 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2746 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2750 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2751 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2752 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2756 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2757 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2759 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2762 if ( cm->max_entries <= 0 ) {
2763 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2764 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2768 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2769 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2771 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2774 if ( cm->num_entries_limit <= 0 ) {
2775 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2776 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2779 if ( cm->num_entries_limit > cm->max_entries ) {
2780 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2781 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2785 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2786 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2788 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2791 cm->cc_period = (time_t)t;
2792 Debug( pcache_debug,
2793 "Total # of attribute sets to be cached = %d.\n",
2794 cm->numattrsets, 0, 0 );
2795 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2796 sizeof( struct attr_set ) );
2799 if ( cm->numattrsets == 0 ) {
2800 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2801 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2804 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2805 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2807 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2811 if ( num < 0 || num >= cm->numattrsets ) {
2812 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2813 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2814 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2817 qm->attr_sets[num].flags |= PC_CONFIGURED;
2818 if ( c->argc == 2 ) {
2820 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2821 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2822 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2825 } else if ( c->argc == 3 ) {
2826 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2827 qm->attr_sets[num].count = 1;
2828 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2829 sizeof( AttributeName ) );
2830 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2833 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2834 qm->attr_sets[num].count = 1;
2835 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2836 sizeof( AttributeName ) );
2837 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2840 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2843 /* else: fallthru */
2845 } else if ( c->argc == 4 ) {
2846 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2847 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2849 qm->attr_sets[num].count = 2;
2850 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2851 sizeof( AttributeName ) );
2852 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2853 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2856 /* else: fallthru */
2859 if ( c->argc > 2 ) {
2860 int all_user = 0, all_op = 0;
2862 qm->attr_sets[num].count = c->argc - 2;
2863 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2864 sizeof( AttributeName ) );
2865 attr_name = qm->attr_sets[num].attrs;
2866 for ( i = 2; i < c->argc; i++ ) {
2867 attr_name->an_desc = NULL;
2868 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2869 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2870 "invalid attr #%d \"%s\" in attrlist",
2871 i - 2, c->argv[i] );
2872 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2873 ch_free( qm->attr_sets[num].attrs );
2874 qm->attr_sets[num].attrs = NULL;
2875 qm->attr_sets[num].count = 0;
2878 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2880 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2881 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2883 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2885 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2886 strcpy( c->cr_msg, text );
2887 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2888 ch_free( qm->attr_sets[num].attrs );
2889 qm->attr_sets[num].attrs = NULL;
2890 qm->attr_sets[num].count = 0;
2893 attr_name->an_name = attr_name->an_desc->ad_cname;
2895 attr_name->an_oc = NULL;
2896 attr_name->an_oc_exclude = 0;
2897 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2898 qm->attr_sets[num].flags |= PC_GOT_OC;
2900 BER_BVZERO( &attr_name->an_name );
2903 /* warn if list contains both "*" and "+" */
2904 if ( i > 4 && all_user && all_op ) {
2905 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2906 "warning: attribute list contains \"*\" and \"+\"" );
2907 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2912 if ( cm->numattrsets == 0 ) {
2913 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2914 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2917 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2918 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2920 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2924 if ( i < 0 || i >= cm->numattrsets ||
2925 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2926 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2927 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2928 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2931 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2932 temp->qmnext = qm->templates;
2933 qm->templates = temp;
2934 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2935 temp->query = temp->query_last = NULL;
2936 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2937 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2938 "unable to parse template ttl=\"%s\"",
2940 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2943 temp->ttl = (time_t)t;
2944 temp->negttl = (time_t)0;
2945 temp->limitttl = (time_t)0;
2946 switch ( c->argc ) {
2948 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2949 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2950 "unable to parse template sizelimit ttl=\"%s\"",
2952 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2955 temp->limitttl = (time_t)t;
2959 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2960 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2961 "unable to parse template negative ttl=\"%s\"",
2963 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2966 temp->negttl = (time_t)t;
2970 temp->no_of_queries = 0;
2972 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2973 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2974 Debug( pcache_debug, " query template: %s\n",
2975 temp->querystr.bv_val, 0, 0 );
2976 temp->attr_set_index = i;
2977 qm->attr_sets[i].flags |= PC_REFERENCED;
2978 temp->qtnext = qm->attr_sets[i].templates;
2979 qm->attr_sets[i].templates = temp;
2980 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2981 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2982 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2983 Debug( pcache_debug, "\t%s\n",
2984 attrarray[i].an_name.bv_val, 0, 0 );
2988 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2989 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2991 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2992 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2995 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2996 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3001 if ( c->value_int <= 0 ) {
3002 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3003 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3006 cm->max_queries = c->value_int;
3021 slap_overinst *on = (slap_overinst *)be->bd_info;
3022 cache_manager* cm = on->on_bi.bi_private;
3024 /* Something for the cache database? */
3025 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3026 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3028 return SLAP_CONF_UNKNOWN;
3036 slap_overinst *on = (slap_overinst *)be->bd_info;
3040 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3041 on->on_bi.bi_private = cm;
3043 qm = (query_manager*)ch_malloc(sizeof(query_manager));
3046 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3047 cm->db.be_private = NULL;
3048 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
3050 cm->numattrsets = 0;
3051 cm->num_entries_limit = 5;
3052 cm->num_cached_queries = 0;
3053 cm->max_entries = 0;
3054 cm->cur_entries = 0;
3055 cm->max_queries = 10000;
3056 cm->save_queries = 0;
3057 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3058 cm->cc_period = 1000;
3061 qm->attr_sets = NULL;
3062 qm->templates = NULL;
3064 qm->lru_bottom = NULL;
3066 qm->qcfunc = query_containment;
3067 qm->crfunc = cache_replacement;
3068 qm->addfunc = add_query;
3069 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3071 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3076 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3078 assert( op->o_tag == LDAP_REQ_SEARCH );
3080 if ( rs->sr_type == REP_SEARCH ) {
3083 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3087 assert( a->a_nvals != NULL );
3089 valsp = op->o_callback->sc_private;
3090 assert( *valsp == NULL );
3092 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3100 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3102 assert( op->o_tag == LDAP_REQ_SEARCH );
3104 if ( rs->sr_type == REP_SEARCH ) {
3105 int *countp = (int *)op->o_callback->sc_private;
3118 slap_overinst *on = (slap_overinst *)be->bd_info;
3119 cache_manager *cm = on->on_bi.bi_private;
3120 query_manager* qm = cm->qm;
3121 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3123 /* check attr sets */
3124 for ( i = 0; i < cm->numattrsets; i++) {
3125 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3126 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3127 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3131 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3135 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3136 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3141 if ( ncf || rf || nrf ) {
3142 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3143 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3144 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3151 /* need to inherit something from the original database... */
3152 cm->db.be_def_limit = be->be_def_limit;
3153 cm->db.be_limits = be->be_limits;
3154 cm->db.be_acl = be->be_acl;
3155 cm->db.be_dfltaccess = be->be_dfltaccess;
3157 if ( SLAP_DBMONITORING( be ) ) {
3158 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3161 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3164 rc = backend_startup_one( &cm->db, NULL );
3166 /* There is no runqueue in TOOL mode */
3167 if ( slapMode & SLAP_SERVER_MODE ) {
3168 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3169 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3170 consistency_check, on,
3171 "pcache_consistency", be->be_suffix[0].bv_val );
3172 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3174 /* Cached database must have the rootdn */
3175 if ( BER_BVISNULL( &cm->db.be_rootndn )
3176 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3178 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3179 "underlying database of type \"%s\"\n"
3180 " serving naming context \"%s\"\n"
3181 " has no \"rootdn\", required by \"proxycache\".\n",
3182 on->on_info->oi_orig->bi_type,
3183 cm->db.be_suffix[0].bv_val, 0 );
3187 if ( cm->save_queries ) {
3188 void *thrctx = ldap_pvt_thread_pool_context();
3189 Connection conn = { 0 };
3190 OperationBuffer opbuf;
3192 slap_callback cb = { 0 };
3193 SlapReply rs = { 0 };
3194 BerVarray vals = NULL;
3195 Filter f = { 0 }, f2 = { 0 };
3196 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3197 AttributeName attrs[ 2 ] = { 0 };
3199 connection_fake_init( &conn, &opbuf, thrctx );
3204 op->o_tag = LDAP_REQ_SEARCH;
3205 op->o_protocol = LDAP_VERSION3;
3206 cb.sc_response = pcache_cachedquery_open_cb;
3207 cb.sc_private = &vals;
3208 op->o_callback = &cb;
3209 op->o_time = slap_get_time();
3210 op->o_do_not_cache = 1;
3211 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3213 op->o_dn = cm->db.be_rootdn;
3214 op->o_ndn = cm->db.be_rootndn;
3215 op->o_req_dn = cm->db.be_suffix[ 0 ];
3216 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3218 op->ors_scope = LDAP_SCOPE_BASE;
3219 op->ors_deref = LDAP_DEREF_NEVER;
3221 op->ors_tlimit = SLAP_NO_LIMIT;
3222 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3223 f.f_choice = LDAP_FILTER_PRESENT;
3224 f.f_desc = ad_cachedQueryURL;
3225 op->ors_filter = &f;
3226 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3227 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3228 op->ors_attrs = attrs;
3229 op->ors_attrsonly = 0;
3231 rc = op->o_bd->be_search( op, &rs );
3232 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3235 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3236 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3237 cm->num_cached_queries++;
3241 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3244 /* count cached entries */
3245 f.f_choice = LDAP_FILTER_NOT;
3247 f2.f_choice = LDAP_FILTER_EQUALITY;
3249 f2.f_av_desc = slap_schema.si_ad_objectClass;
3250 BER_BVSTR( &f2.f_av_value, "glue" );
3251 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3253 op->ors_slimit = SLAP_NO_LIMIT;
3254 op->ors_scope = LDAP_SCOPE_SUBTREE;
3255 op->ors_attrs = slap_anlist_no_attrs;
3257 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3259 op->o_callback->sc_private = &rs.sr_nentries;
3261 rc = op->o_bd->be_search( op, &rs );
3263 cm->cur_entries = rs.sr_nentries;
3274 pcache_free_qbase( void *v )
3280 tavl_free( qb->scopes[i], NULL );
3290 slap_overinst *on = (slap_overinst *)be->bd_info;
3291 cache_manager *cm = on->on_bi.bi_private;
3292 query_manager *qm = cm->qm;
3296 if ( cm->save_queries ) {
3298 BerVarray vals = NULL;
3301 Connection conn = { 0 };
3302 OperationBuffer opbuf;
3304 slap_callback cb = { 0 };
3306 SlapReply rs = { REP_RESULT };
3307 Modifications mod = { 0 };
3309 thrctx = ldap_pvt_thread_pool_context();
3311 connection_fake_init( &conn, &opbuf, thrctx );
3314 if ( qm->templates != NULL ) {
3315 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3316 for ( qc = tm->query; qc; qc = qc->next ) {
3319 if ( query2url( op, qc, &bv ) == 0 ) {
3320 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3327 op->o_dn = cm->db.be_rootdn;
3328 op->o_ndn = cm->db.be_rootndn;
3330 op->o_tag = LDAP_REQ_MODIFY;
3331 op->o_protocol = LDAP_VERSION3;
3332 cb.sc_response = slap_null_cb;
3333 op->o_callback = &cb;
3334 op->o_time = slap_get_time();
3335 op->o_do_not_cache = 1;
3336 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3338 op->o_req_dn = op->o_bd->be_suffix[0];
3339 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3341 mod.sml_op = LDAP_MOD_REPLACE;
3343 mod.sml_desc = ad_cachedQueryURL;
3344 mod.sml_type = ad_cachedQueryURL->ad_cname;
3345 mod.sml_values = vals;
3346 mod.sml_nvalues = NULL;
3347 mod.sml_next = NULL;
3348 Debug( pcache_debug,
3349 "%sSETTING CACHED QUERY URLS\n",
3350 vals == NULL ? "RE" : "", 0, 0 );
3352 op->orm_modlist = &mod;
3354 op->o_bd->be_modify( op, &rs );
3356 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3359 /* cleanup stuff inherited from the original database... */
3360 cm->db.be_limits = NULL;
3361 cm->db.be_acl = NULL;
3363 /* stop the thread ... */
3365 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3366 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3367 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3369 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3370 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3373 if ( cm->db.bd_info->bi_db_close ) {
3374 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3376 while ( (tm = qm->templates) != NULL ) {
3377 CachedQuery *qc, *qn;
3378 qm->templates = tm->qmnext;
3379 for ( qc = tm->query; qc; qc = qn ) {
3383 avl_free( tm->qbase, pcache_free_qbase );
3384 free( tm->querystr.bv_val );
3385 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3386 free( tm->t_attrs.attrs );
3390 for ( i=0; i<cm->numattrsets; i++ ) {
3391 free( qm->attr_sets[i].attrs );
3393 free( qm->attr_sets );
3394 qm->attr_sets = NULL;
3405 slap_overinst *on = (slap_overinst *)be->bd_info;
3406 cache_manager *cm = on->on_bi.bi_private;
3407 query_manager *qm = cm->qm;
3409 if ( cm->db.be_private != NULL ) {
3410 backend_stopdown_one( &cm->db );
3413 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3414 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3421 #ifdef PCACHE_CONTROL_PRIVDB
3423 Control ::= SEQUENCE {
3424 controlType LDAPOID,
3425 criticality BOOLEAN DEFAULT FALSE,
3426 controlValue OCTET STRING OPTIONAL }
3428 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3430 * criticality must be TRUE; controlValue must be absent.
3438 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3439 rs->sr_text = "privateDB control specified multiple times";
3440 return LDAP_PROTOCOL_ERROR;
3443 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3444 rs->sr_text = "privateDB control value not absent";
3445 return LDAP_PROTOCOL_ERROR;
3448 if ( !ctrl->ldctl_iscritical ) {
3449 rs->sr_text = "privateDB control criticality required";
3450 return LDAP_PROTOCOL_ERROR;
3453 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3455 return LDAP_SUCCESS;
3458 static char *extops[] = {
3459 LDAP_EXOP_MODIFY_PASSWD,
3462 #endif /* PCACHE_CONTROL_PRIVDB */
3464 #ifdef PCACHE_EXOP_QUERY_DELETE
3465 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3467 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3468 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3469 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3472 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3473 requestName [0] LDAPOID,
3474 requestValue [1] OCTET STRING OPTIONAL }
3476 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3478 requestValue ::= SEQUENCE { CHOICE {
3480 entryDN [1] LDAPDN },
3481 queryID [2] OCTET STRING (SIZE(16))
3482 -- constrained to UUID }
3484 * Either baseDN or entryDN must be present, to allow database selection.
3486 * 1. if baseDN and queryID are present, then the query corresponding
3487 * to queryID is deleted;
3488 * 2. if baseDN is present and queryID is absent, then all queries
3490 * 3. if entryDN is present and queryID is absent, then all queries
3491 * corresponding to the queryID values present in entryDN are deleted;
3492 * 4. if entryDN and queryID are present, then all queries
3493 * corresponding to the queryID values present in entryDN are deleted,
3494 * but only if the value of queryID is contained in the entry;
3496 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3497 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3498 * or by removing the database files.
3500 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3501 COMPONENTS OF LDAPResult,
3502 responseName [10] LDAPOID OPTIONAL,
3503 responseValue [11] OCTET STRING OPTIONAL }
3505 * responseName and responseValue must be absent.
3509 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3510 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3511 * - if ndn != NULL, it is set to the normalized DN in the request
3512 * corresponding to either the baseDN or the entryDN, according
3513 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3514 * be freed by the caller.
3515 * - if uuid != NULL, it is set to point to the normalized UUID;
3516 * memory is malloc'ed on the Operation's slab, and must
3517 * be freed by the caller.
3520 pcache_parse_query_delete(
3524 struct berval *uuid,
3528 int rc = LDAP_SUCCESS;
3531 BerElementBuffer berbuf;
3532 BerElement *ber = (BerElement *)&berbuf;
3533 struct berval reqdata = BER_BVNULL;
3545 if ( in == NULL || in->bv_len == 0 ) {
3546 *text = "empty request data field in queryDelete exop";
3547 return LDAP_PROTOCOL_ERROR;
3550 ber_dupbv_x( &reqdata, in, ctx );
3552 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3553 ber_init2( ber, &reqdata, 0 );
3555 tag = ber_scanf( ber, "{" /*}*/ );
3557 if ( tag == LBER_ERROR ) {
3558 Debug( LDAP_DEBUG_TRACE,
3559 "pcache_parse_query_delete: decoding error.\n",
3561 goto decoding_error;
3564 tag = ber_peek_tag( ber, &len );
3565 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3566 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3570 if ( ndn != NULL ) {
3573 tag = ber_scanf( ber, "m", &dn );
3574 if ( tag == LBER_ERROR ) {
3575 Debug( LDAP_DEBUG_TRACE,
3576 "pcache_parse_query_delete: DN parse failed.\n",
3578 goto decoding_error;
3581 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3582 if ( rc != LDAP_SUCCESS ) {
3583 *text = "invalid DN in queryDelete exop request data";
3588 tag = ber_scanf( ber, "x" /* "m" */ );
3589 if ( tag == LBER_DEFAULT ) {
3590 goto decoding_error;
3594 tag = ber_peek_tag( ber, &len );
3597 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3598 if ( uuid != NULL ) {
3600 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3602 tag = ber_scanf( ber, "m", &bv );
3603 if ( tag == LBER_ERROR ) {
3604 Debug( LDAP_DEBUG_TRACE,
3605 "pcache_parse_query_delete: UUID parse failed.\n",
3607 goto decoding_error;
3610 if ( bv.bv_len != 16 ) {
3611 Debug( LDAP_DEBUG_TRACE,
3612 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3613 (unsigned long)bv.bv_len, 0, 0 );
3614 goto decoding_error;
3617 rc = lutil_uuidstr_from_normalized(
3618 bv.bv_val, bv.bv_len,
3619 uuidbuf, sizeof( uuidbuf ) );
3621 goto decoding_error;
3623 ber_str2bv( uuidbuf, rc, 1, uuid );
3627 tag = ber_skip_tag( ber, &len );
3628 if ( tag == LBER_DEFAULT ) {
3629 goto decoding_error;
3633 Debug( LDAP_DEBUG_TRACE,
3634 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3635 (unsigned long)len, 0, 0 );
3636 goto decoding_error;
3640 tag = ber_peek_tag( ber, &len );
3643 if ( tag != LBER_DEFAULT || len != 0 ) {
3645 Debug( LDAP_DEBUG_TRACE,
3646 "pcache_parse_query_delete: decoding error\n",
3648 rc = LDAP_PROTOCOL_ERROR;
3649 *text = "queryDelete data decoding error";
3652 if ( ndn && !BER_BVISNULL( ndn ) ) {
3653 slap_sl_free( ndn->bv_val, ctx );
3657 if ( uuid && !BER_BVISNULL( uuid ) ) {
3658 slap_sl_free( uuid->bv_val, ctx );
3663 if ( !BER_BVISNULL( &reqdata ) ) {
3664 ber_memfree_x( reqdata.bv_val, ctx );
3671 pcache_exop_query_delete(
3675 BackendDB *bd = op->o_bd;
3677 struct berval uuid = BER_BVNULL,
3679 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3681 ber_tag_t tag = LBER_DEFAULT;
3683 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3687 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3688 &tag, &op->o_req_ndn, uuidp,
3689 &rs->sr_text, op->o_tmpmemctx );
3690 if ( rs->sr_err != LDAP_SUCCESS ) {
3694 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3695 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3696 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3698 if ( !BER_BVISNULL( &uuid ) ) {
3699 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3702 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3703 op->o_log_prefix, buf, 0 );
3705 op->o_req_dn = op->o_req_ndn;
3707 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3708 rs->sr_err = backend_check_restrictions( op, rs,
3709 (struct berval *)&pcache_exop_QUERY_DELETE );
3710 if ( rs->sr_err != LDAP_SUCCESS ) {
3714 if ( op->o_bd->be_extended == NULL ) {
3715 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3716 "backend does not support extended operations" );
3720 op->o_bd->be_extended( op, rs );
3723 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3724 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3725 BER_BVZERO( &op->o_req_ndn );
3726 BER_BVZERO( &op->o_req_dn );
3729 if ( !BER_BVISNULL( &uuid ) ) {
3730 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3739 pcache_op_extended( Operation *op, SlapReply *rs )
3741 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3742 cache_manager *cm = on->on_bi.bi_private;
3744 #ifdef PCACHE_CONTROL_PRIVDB
3745 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3746 return pcache_op_privdb( op, rs );
3748 #endif /* PCACHE_CONTROL_PRIVDB */
3750 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3751 struct berval uuid = BER_BVNULL;
3752 ber_tag_t tag = LBER_DEFAULT;
3754 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3755 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3756 assert( rs->sr_err == LDAP_SUCCESS );
3758 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3759 /* remove all queries related to the selected entry */
3760 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3761 cm, &op->o_req_ndn, &uuid );
3763 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3764 if ( !BER_BVISNULL( &uuid ) ) {
3765 /* remove the selected query */
3766 rs->sr_err = pcache_remove_query_from_cache( op,
3770 /* TODO: remove all queries */
3771 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3772 rs->sr_text = "deletion of all queries not implemented";
3776 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3781 #endif /* PCACHE_EXOP_QUERY_DELETE */
3783 static slap_overinst pcache;
3785 static char *obsolete_names[] = {
3790 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3792 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3797 struct berval debugbv = BER_BVC("pcache");
3799 code = slap_loglevel_get( &debugbv, &pcache_debug );
3804 #ifdef PCACHE_CONTROL_PRIVDB
3805 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3806 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3807 parse_privdb_ctrl, &privDB_cid );
3808 if ( code != LDAP_SUCCESS ) {
3809 Debug( LDAP_DEBUG_ANY,
3810 "pcache_initialize: failed to register control %s (%d)\n",
3811 PCACHE_CONTROL_PRIVDB, code, 0 );
3814 #endif /* PCACHE_CONTROL_PRIVDB */
3816 #ifdef PCACHE_EXOP_QUERY_DELETE
3817 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3818 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3820 if ( code != LDAP_SUCCESS ) {
3821 Debug( LDAP_DEBUG_ANY,
3822 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3826 #endif /* PCACHE_EXOP_QUERY_DELETE */
3828 for ( i = 0; as[i].desc != NULL; i++ ) {
3829 code = register_at( as[i].desc, as[i].adp, 0 );
3831 Debug( LDAP_DEBUG_ANY,
3832 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3835 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3838 pcache.on_bi.bi_type = "pcache";
3839 pcache.on_bi.bi_obsolete_names = obsolete_names;
3840 pcache.on_bi.bi_db_init = pcache_db_init;
3841 pcache.on_bi.bi_db_config = pcache_db_config;
3842 pcache.on_bi.bi_db_open = pcache_db_open;
3843 pcache.on_bi.bi_db_close = pcache_db_close;
3844 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3846 pcache.on_bi.bi_op_search = pcache_op_search;
3847 #ifdef PCACHE_CONTROL_PRIVDB
3848 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3849 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3850 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3851 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3852 pcache.on_bi.bi_op_add = pcache_op_privdb;
3853 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3854 #endif /* PCACHE_CONTROL_PRIVDB */
3855 #ifdef PCACHE_EXOP_QUERY_DELETE
3856 pcache.on_bi.bi_extended = pcache_op_extended;
3857 #elif defined( PCACHE_CONTROL_PRIVDB )
3858 pcache.on_bi.bi_extended = pcache_op_privdb;
3861 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3863 pcache.on_bi.bi_cf_ocs = pcocs;
3865 code = config_register_schema( pccfg, pcocs );
3866 if ( code ) return code;
3868 return overlay_register( &pcache );
3871 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3872 int init_module(int argc, char *argv[]) {
3873 return pcache_initialize();
3877 #endif /* defined(SLAPD_OVER_PROXYCACHE) */