2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2013 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003-2009 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>
36 #include "../back-monitor/back-monitor.h"
41 * Control that allows to access the private DB
42 * instead of the public one
44 #define PCACHE_CONTROL_PRIVDB "1.3.6.1.4.1.4203.666.11.9.5.1"
47 * Extended Operation that allows to remove a query from the cache
49 #define PCACHE_EXOP_QUERY_DELETE "1.3.6.1.4.1.4203.666.11.9.6.1"
54 #define PCACHE_MONITOR
56 /* query cache structs */
59 typedef struct Query_s {
60 Filter* filter; /* Search Filter */
61 struct berval base; /* Search Base */
62 int scope; /* Search scope */
65 struct query_template_s;
67 typedef struct Qbase_s {
68 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
73 /* struct representing a cached query */
74 typedef struct cached_query_s {
79 struct berval q_uuid; /* query identifier */
81 struct query_template_s *qtemp; /* template of the query */
82 time_t expiry_time; /* time till the query is considered invalid */
83 time_t refresh_time; /* time till the query is refreshed */
84 time_t bindref_time; /* time till the bind is refreshed */
85 int bind_refcnt; /* number of bind operation referencing this query */
86 unsigned long answerable_cnt; /* how many times it was answerable */
87 int refcnt; /* references since last refresh */
88 ldap_pvt_thread_mutex_t answerable_cnt_mutex;
89 struct cached_query_s *next; /* next query in the template */
90 struct cached_query_s *prev; /* previous query in the template */
91 struct cached_query_s *lru_up; /* previous query in the LRU list */
92 struct cached_query_s *lru_down; /* next query in the LRU list */
93 ldap_pvt_thread_rdwr_t rwlock;
99 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>,x-refresh=<refresh>
101 * <base> ::= CachedQuery.qbase->base
102 * <scope> ::= CachedQuery.scope
103 * <filter> ::= filter2bv(CachedQuery.filter)
104 * <uuid> ::= CachedQuery.q_uuid
105 * <attrset> ::= CachedQuery.qtemp->attr_set_index
106 * <expiry> ::= CachedQuery.expiry_time
107 * <refresh> ::= CachedQuery.refresh_time
109 * quick hack: parse URI, call add_query() and then fix
110 * CachedQuery.expiry_time and CachedQuery.q_uuid
112 * NOTE: if the <attrset> changes, all stored URLs will be invalidated.
116 * Represents a set of projected attributes.
120 struct query_template_s *templates;
121 AttributeName* attrs; /* specifies the set */
123 #define PC_CONFIGURED (0x1)
124 #define PC_REFERENCED (0x2)
125 #define PC_GOT_OC (0x4)
126 int count; /* number of attributes */
129 /* struct representing a query template
130 * e.g. template string = &(cn=)(mail=)
132 typedef struct query_template_s {
133 struct query_template_s *qtnext;
134 struct query_template_s *qmnext;
137 CachedQuery* query; /* most recent query cached for the template */
138 CachedQuery* query_last; /* oldest query cached for the template */
139 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
140 struct berval querystr; /* Filter string corresponding to the QT */
141 struct berval bindbase; /* base DN for Bind request */
142 struct berval bindfilterstr; /* Filter string for Bind request */
143 struct berval bindftemp; /* bind filter template */
145 AttributeDescription **bindfattrs; /* attrs to substitute in ftemp */
147 int bindnattrs; /* number of bindfattrs */
149 int attr_set_index; /* determines the projected attributes */
150 int no_of_queries; /* Total number of queries in the template */
151 time_t ttl; /* TTL for the queries of this template */
152 time_t negttl; /* TTL for negative results */
153 time_t limitttl; /* TTL for sizelimit exceeding results */
154 time_t ttr; /* time to refresh */
155 time_t bindttr; /* TTR for cached binds */
156 struct attr_set t_attrs; /* filter attrs + attr_set */
164 } pc_caching_reason_t;
166 static const char *pc_caching_reason_str[] = {
175 struct query_manager_s;
177 /* prototypes for functions for 1) query containment
178 * 2) query addition, 3) cache replacement
180 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
181 Query*, QueryTemplate*);
182 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
183 Query*, QueryTemplate*, pc_caching_reason_t, int wlock);
184 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
186 /* LDAP query cache */
187 typedef struct query_manager_s {
188 struct attr_set* attr_sets; /* possible sets of projected attributes */
189 QueryTemplate* templates; /* cacheable templates */
191 CachedQuery* lru_top; /* top and bottom of LRU list */
192 CachedQuery* lru_bottom;
194 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
196 /* Query cache methods */
197 QCfunc *qcfunc; /* Query containment*/
198 CRfunc *crfunc; /* cache replacement */
199 AddQueryfunc *addfunc; /* add query */
202 /* LDAP query cache manager */
203 typedef struct cache_manager_s {
204 BackendDB db; /* underlying database */
205 unsigned long num_cached_queries; /* total number of cached queries */
206 unsigned long max_queries; /* upper bound on # of cached queries */
207 int save_queries; /* save cached queries across restarts */
208 int check_cacheability; /* check whether a query is cacheable */
209 int numattrsets; /* number of attribute sets */
210 int cur_entries; /* current number of entries cached */
211 int max_entries; /* max number of entries cached */
212 int num_entries_limit; /* max # of entries in a cacheable query */
214 char response_cb; /* install the response callback
215 * at the tail of the callback list */
216 #define PCACHE_RESPONSE_CB_HEAD 0
217 #define PCACHE_RESPONSE_CB_TAIL 1
218 char defer_db_open; /* defer open for online add */
219 char cache_binds; /* cache binds or just passthru */
221 time_t cc_period; /* interval between successive consistency checks (sec) */
222 #define PCACHE_CC_PAUSED 1
223 #define PCACHE_CC_OFFLINE 2
227 ldap_pvt_thread_mutex_t cache_mutex;
229 query_manager* qm; /* query cache managed by the cache manager */
231 #ifdef PCACHE_MONITOR
233 struct berval monitor_ndn;
234 #endif /* PCACHE_MONITOR */
237 #ifdef PCACHE_MONITOR
238 static int pcache_monitor_db_init( BackendDB *be );
239 static int pcache_monitor_db_open( BackendDB *be );
240 static int pcache_monitor_db_close( BackendDB *be );
241 static int pcache_monitor_db_destroy( BackendDB *be );
242 #endif /* PCACHE_MONITOR */
244 static int pcache_debug;
246 #ifdef PCACHE_CONTROL_PRIVDB
247 static int privDB_cid;
248 #endif /* PCACHE_CONTROL_PRIVDB */
250 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
252 #ifdef PCACHE_MONITOR
253 static AttributeDescription *ad_numQueries, *ad_numEntries;
254 static ObjectClass *oc_olmPCache;
255 #endif /* PCACHE_MONITOR */
261 { "PCacheOID", "1.3.6.1.4.1.4203.666.11.9.1" },
262 { "PCacheAttributes", "PCacheOID:1" },
263 { "PCacheObjectClasses", "PCacheOID:2" },
270 AttributeDescription **adp;
272 { "( PCacheAttributes:1 "
273 "NAME 'pcacheQueryID' "
274 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
275 "EQUALITY octetStringMatch "
276 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
277 "NO-USER-MODIFICATION "
278 "USAGE directoryOperation )",
280 { "( PCacheAttributes:2 "
281 "NAME 'pcacheQueryURL' "
282 "DESC 'URI describing a cached query' "
283 "EQUALITY caseExactMatch "
284 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
285 "NO-USER-MODIFICATION "
286 "USAGE directoryOperation )",
287 &ad_cachedQueryURL },
288 #ifdef PCACHE_MONITOR
289 { "( PCacheAttributes:3 "
290 "NAME 'pcacheNumQueries' "
291 "DESC 'Number of cached queries' "
292 "EQUALITY integerMatch "
293 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
294 "NO-USER-MODIFICATION "
295 "USAGE directoryOperation )",
297 { "( PCacheAttributes:4 "
298 "NAME 'pcacheNumEntries' "
299 "DESC 'Number of cached entries' "
300 "EQUALITY integerMatch "
301 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
302 "NO-USER-MODIFICATION "
303 "USAGE directoryOperation )",
305 #endif /* PCACHE_MONITOR */
314 #ifdef PCACHE_MONITOR
315 /* augments an existing object, so it must be AUXILIARY */
316 { "( PCacheObjectClasses:1 "
317 "NAME ( 'olmPCache' ) "
321 "$ pcacheNumQueries "
322 "$ pcacheNumEntries "
325 #endif /* PCACHE_MONITOR */
334 struct berval *fstr );
341 QueryTemplate *templ,
342 pc_caching_reason_t why,
348 struct berval *query_uuid );
351 * Turn a cached query into its URL representation
354 query2url( Operation *op, CachedQuery *q, struct berval *urlbv, int dolock )
356 struct berval bv_scope,
358 char attrset_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
359 expiry_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
360 refresh_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
361 answerable_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
363 ber_len_t attrset_len,
369 ldap_pvt_thread_rdwr_rlock( &q->rwlock );
372 ldap_pvt_scope2bv( q->scope, &bv_scope );
373 filter2bv_x( op, q->filter, &bv_filter );
374 attrset_len = sprintf( attrset_buf,
375 "%lu", (unsigned long)q->qtemp->attr_set_index );
376 expiry_len = sprintf( expiry_buf,
377 "%lu", (unsigned long)q->expiry_time );
378 answerable_len = snprintf( answerable_buf, sizeof( answerable_buf ),
379 "%lu", q->answerable_cnt );
380 if ( q->refresh_time )
381 refresh_len = sprintf( refresh_buf,
382 "%lu", (unsigned long)q->refresh_time );
386 urlbv->bv_len = STRLENOF( "ldap:///" )
387 + q->qbase->base.bv_len
392 + STRLENOF( "?x-uuid=" )
394 + STRLENOF( ",x-attrset=" )
396 + STRLENOF( ",x-expiry=" )
398 + STRLENOF( ",x-answerable=" )
401 urlbv->bv_len += STRLENOF( ",x-refresh=" )
404 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
405 ptr = lutil_strcopy( ptr, "ldap:///" );
406 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
407 ptr = lutil_strcopy( ptr, "??" );
408 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
409 ptr = lutil_strcopy( ptr, "?" );
410 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
411 ptr = lutil_strcopy( ptr, "?x-uuid=" );
412 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
413 ptr = lutil_strcopy( ptr, ",x-attrset=" );
414 ptr = lutil_strcopy( ptr, attrset_buf );
415 ptr = lutil_strcopy( ptr, ",x-expiry=" );
416 ptr = lutil_strcopy( ptr, expiry_buf );
417 ptr = lutil_strcopy( ptr, ",x-answerable=" );
418 ptr = lutil_strcopy( ptr, answerable_buf );
420 ptr = lutil_strcopy( ptr, ",x-refresh=" );
421 ptr = lutil_strcopy( ptr, refresh_buf );
424 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
427 ldap_pvt_thread_rdwr_runlock( &q->rwlock );
433 /* Find and record the empty filter clauses */
436 ftemp_attrs( struct berval *ftemp, struct berval *template,
437 AttributeDescription ***ret, const char **text )
443 AttributeDescription *ad;
444 AttributeDescription **descs = NULL;
447 temp2 = ch_malloc( ftemp->bv_len + 1 );
454 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' )
457 p2 = strchr( p1, '=' );
461 AC_MEMCPY( t1, p1, i );
465 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
469 i = slap_bv2ad( &bv, &ad, text );
474 if ( *p2 == '<' || *p2 == '>' ) p2++;
475 if ( p2[1] != ')' ) {
477 while ( *p2 != ')' ) p2++;
482 descs = (AttributeDescription **)ch_realloc(descs,
483 (attr_cnt + 2)*sizeof(AttributeDescription *));
485 descs[attr_cnt++] = ad;
490 descs[attr_cnt] = NULL;
492 template->bv_val = temp2;
493 template->bv_len = t1 - temp2;
498 template_attrs( char *template, struct attr_set *set, AttributeName **ret,
509 AttributeDescription *ad;
510 AttributeName *attrs;
516 attrs = ch_calloc( set->count + 1, sizeof(AttributeName) );
517 for ( i=0; i < set->count; i++ )
518 attrs[i] = set->attrs[i];
520 alluser = an_find( attrs, slap_bv_all_user_attrs );
521 allop = an_find( attrs, slap_bv_all_operational_attrs );
524 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' ) p1++;
525 p2 = strchr( p1, '=' );
528 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
532 i = slap_bv2ad( &bv, &ad, text );
539 if ( ad == slap_schema.si_ad_objectClass )
542 if ( is_at_operational(ad->ad_type)) {
546 } else if ( alluser ) {
549 if ( !ad_inlist( ad, attrs )) {
550 attrs = (AttributeName *)ch_realloc(attrs,
551 (attr_cnt + 2)*sizeof(AttributeName));
553 attrs[attr_cnt].an_desc = ad;
554 attrs[attr_cnt].an_name = ad->ad_cname;
555 attrs[attr_cnt].an_oc = NULL;
556 attrs[attr_cnt].an_flags = 0;
557 BER_BVZERO( &attrs[attr_cnt+1].an_name );
565 *text = "couldn't parse template";
568 if ( !got_oc && !( set->flags & PC_GOT_OC )) {
569 attrs = (AttributeName *)ch_realloc(attrs,
570 (attr_cnt + 2)*sizeof(AttributeName));
572 ad = slap_schema.si_ad_objectClass;
573 attrs[attr_cnt].an_desc = ad;
574 attrs[attr_cnt].an_name = ad->ad_cname;
575 attrs[attr_cnt].an_oc = NULL;
576 attrs[attr_cnt].an_flags = 0;
577 BER_BVZERO( &attrs[attr_cnt+1].an_name );
585 * Turn an URL representing a formerly cached query into a cached query,
586 * and try to cache it
597 LDAPURLDesc *lud = NULL;
599 tempstr = BER_BVNULL,
604 unsigned long answerable_cnt;
607 #define GOT_UUID 0x1U
608 #define GOT_ATTRSET 0x2U
609 #define GOT_EXPIRY 0x4U
610 #define GOT_ANSWERABLE 0x8U
611 #define GOT_REFRESH 0x10U
612 #define GOT_ALL (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
615 rc = ldap_url_parse( url, &lud );
616 if ( rc != LDAP_URL_SUCCESS ) {
620 /* non-allowed fields */
621 if ( lud->lud_host != NULL ) {
626 if ( lud->lud_attrs != NULL ) {
632 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
637 /* required fields */
638 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
643 switch ( lud->lud_scope ) {
644 case LDAP_SCOPE_BASE:
645 case LDAP_SCOPE_ONELEVEL:
646 case LDAP_SCOPE_SUBTREE:
647 case LDAP_SCOPE_SUBORDINATE:
655 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
660 if ( lud->lud_exts == NULL ) {
665 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
666 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
667 struct berval tmpUUID;
668 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
670 if ( got & GOT_UUID ) {
675 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
676 if ( !BER_BVISEMPTY( &tmpUUID ) ) {
677 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
678 if ( rc != LDAP_SUCCESS ) {
684 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
685 if ( got & GOT_ATTRSET ) {
690 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
696 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
699 if ( got & GOT_EXPIRY ) {
704 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
708 expiry_time = (time_t)l;
711 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
712 if ( got & GOT_ANSWERABLE ) {
717 rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
721 got |= GOT_ANSWERABLE;
723 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
726 if ( got & GOT_REFRESH ) {
731 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
735 refresh_time = (time_t)l;
744 if ( got != GOT_ALL ) {
749 if ( !(got & GOT_REFRESH ))
752 /* ignore expired queries */
753 if ( expiry_time <= slap_get_time()) {
756 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
758 (void)remove_query_data( &op2, &uuid );
763 ber_str2bv( lud->lud_dn, 0, 0, &base );
764 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
765 if ( rc != LDAP_SUCCESS ) {
768 query.scope = lud->lud_scope;
769 query.filter = str2filter( lud->lud_filter );
770 if ( query.filter == NULL ) {
775 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
777 if ( filter2template( op, query.filter, &tempstr ) ) {
778 ch_free( tempstr.bv_val );
783 /* check for query containment */
784 qt = qm->attr_sets[attrset].templates;
785 for ( ; qt; qt = qt->qtnext ) {
786 /* find if template i can potentially answer tempstr */
787 if ( bvmatch( &qt->querystr, &tempstr ) ) {
797 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
799 cq->expiry_time = expiry_time;
800 cq->refresh_time = refresh_time;
802 cq->answerable_cnt = answerable_cnt;
805 /* it's now into cq->filter */
815 if ( query.filter != NULL ) filter_free( query.filter );
816 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
817 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
818 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
819 if ( lud != NULL ) ldap_free_urldesc( lud );
824 /* Return 1 for an added entry, else 0 */
830 struct berval* query_uuid )
833 Modifications* modlist = NULL;
834 const char* text = NULL;
836 char textbuf[SLAP_TEXT_BUFLEN];
837 size_t textlen = sizeof(textbuf);
839 SlapReply sreply = {REP_RESULT};
841 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
848 /* add queryId attribute */
849 attr_merge_one( e, ad_queryId, query_uuid, NULL );
851 /* append the attribute list from the fetched entry */
852 e->e_attrs->a_next = attr;
854 op->o_tag = LDAP_REQ_ADD;
855 op->o_protocol = LDAP_VERSION3;
856 op->o_callback = &cb;
857 op->o_time = slap_get_time();
858 op->o_do_not_cache = 1;
861 op->o_req_dn = e->e_name;
862 op->o_req_ndn = e->e_nname;
863 rc = op->o_bd->be_add( op, &sreply );
865 if ( rc != LDAP_SUCCESS ) {
866 if ( rc == LDAP_ALREADY_EXISTS ) {
867 rs_reinit( &sreply, REP_RESULT );
868 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
869 modlist->sml_op = LDAP_MOD_ADD;
870 op->o_tag = LDAP_REQ_MODIFY;
871 op->orm_modlist = modlist;
872 op->o_managedsait = SLAP_CONTROL_CRITICAL;
873 op->o_bd->be_modify( op, &sreply );
874 slap_mods_free( modlist, 1 );
875 } else if ( rc == LDAP_REFERRAL ||
876 rc == LDAP_NO_SUCH_OBJECT ) {
877 syncrepl_add_glue( op, e );
886 if ( op->ora_e == e )
894 /* Length-ordered sort on normalized DNs */
895 static int pcache_dn_cmp( const void *v1, const void *v2 )
897 const Qbase *q1 = v1, *q2 = v2;
899 int rc = q1->base.bv_len - q2->base.bv_len;
901 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
905 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
908 dif = bv1->bv_len - bv2->bv_len;
910 if ( dif > 0 ) len -= dif;
911 len = memcmp( bv1->bv_val, bv2->bv_val, len );
917 /* compare the current value in each filter */
918 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
920 int rc, weight1, weight2;
922 switch( f1->f_choice ) {
923 case LDAP_FILTER_AND:
927 case LDAP_FILTER_PRESENT:
930 case LDAP_FILTER_EQUALITY:
938 switch( f2->f_choice ) {
939 case LDAP_FILTER_AND:
943 case LDAP_FILTER_PRESENT:
946 case LDAP_FILTER_EQUALITY:
954 rc = weight1 - weight2;
958 rc = pcache_filter_cmp( f1->f_and, f2->f_and );
963 rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
966 if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
968 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
969 if ( !BER_BVISNULL( &f2->f_sub_initial )) {
970 rc = lex_bvcmp( &f1->f_sub_initial,
971 &f2->f_sub_initial );
975 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
979 if ( f1->f_sub_any ) {
980 if ( f2->f_sub_any ) {
981 rc = lex_bvcmp( f1->f_sub_any,
986 } else if ( f2->f_sub_any ) {
990 if ( !BER_BVISNULL( &f1->f_sub_final )) {
991 if ( !BER_BVISNULL( &f2->f_sub_final )) {
992 rc = lex_bvcmp( &f1->f_sub_final,
997 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
1001 rc = lex_bvcmp( &f1->f_mr_value,
1015 rc = pcache_filter_cmp( f1, f2 );
1025 /* compare filters in each query */
1026 static int pcache_query_cmp( const void *v1, const void *v2 )
1028 const CachedQuery *q1 = v1, *q2 =v2;
1029 return pcache_filter_cmp( q1->filter, q2->filter );
1032 /* add query on top of LRU list */
1034 add_query_on_top (query_manager* qm, CachedQuery* qc)
1036 CachedQuery* top = qm->lru_top;
1043 qm->lru_bottom = qc;
1047 Debug( pcache_debug, "Base of added query = %s\n",
1048 qc->qbase->base.bv_val, 0, 0 );
1051 /* remove_query from LRU list */
1054 remove_query (query_manager* qm, CachedQuery* qc)
1063 down = qc->lru_down;
1069 qm->lru_bottom = up;
1075 up->lru_down = down;
1077 qc->lru_up = qc->lru_down = NULL;
1080 /* find and remove string2 from string1
1081 * from start if position = 1,
1082 * from end if position = 3,
1083 * from anywhere if position = 2
1084 * string1 is overwritten if position = 2.
1088 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
1092 if ( !ber2->bv_val )
1094 if ( !ber1->bv_val )
1097 switch( position ) {
1099 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
1100 ber2->bv_val, ber2->bv_len )) {
1102 ber1->bv_val += ber2->bv_len;
1103 ber1->bv_len -= ber2->bv_len;
1108 ber1->bv_val[ber1->bv_len] = '\0';
1109 temp = strstr( ber1->bv_val, ber2->bv_val );
1111 strcpy( temp, temp+ber2->bv_len );
1112 ber1->bv_len -= ber2->bv_len;
1118 if ( ber1->bv_len >= ber2->bv_len &&
1119 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
1122 ber1->bv_len -= ber2->bv_len;
1130 static struct berval*
1131 merge_init_final(Operation *op, struct berval* init, struct berval* any,
1132 struct berval* final)
1134 struct berval* merged, *temp;
1135 int i, any_count, count;
1137 for (any_count=0; any && any[any_count].bv_val; any_count++)
1147 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
1152 ber_dupbv_x( temp, init, op->o_tmpmemctx );
1156 for (i=0; i<any_count; i++) {
1157 ber_dupbv_x( temp, any, op->o_tmpmemctx );
1162 ber_dupbv_x( temp, final, op->o_tmpmemctx );
1169 /* Each element in stored must be found in incoming. Incoming is overwritten.
1172 strings_containment(struct berval* stored, struct berval* incoming)
1174 struct berval* element;
1178 for ( element=stored; element->bv_val != NULL; element++ ) {
1179 for (j = k; incoming[j].bv_val != NULL; j++) {
1180 if (find_and_remove(&(incoming[j]), element, 2)) {
1197 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
1201 struct berval init_incoming;
1202 struct berval final_incoming;
1203 struct berval *remaining_incoming = NULL;
1205 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
1206 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
1209 init_incoming = incoming->f_sub_initial;
1210 final_incoming = incoming->f_sub_final;
1212 if (find_and_remove(&init_incoming,
1213 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
1214 &(stored->f_sub_final), 3))
1216 if (stored->f_sub_any == NULL) {
1220 remaining_incoming = merge_init_final(op, &init_incoming,
1221 incoming->f_sub_any, &final_incoming);
1222 rc = strings_containment(stored->f_sub_any, remaining_incoming);
1223 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
1230 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
1232 struct berval incoming_val[2];
1235 incoming_val[1] = incoming->f_av_value;
1237 if (find_and_remove(incoming_val+1,
1238 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
1239 &(stored->f_sub_final), 3)) {
1240 if (stored->f_sub_any == NULL){
1244 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
1245 BER_BVZERO( incoming_val+1 );
1246 rc = strings_containment(stored->f_sub_any, incoming_val);
1247 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1254 filter_first( Filter *f )
1256 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1261 typedef struct fstack {
1262 struct fstack *fs_next;
1267 static CachedQuery *
1268 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
1272 MatchingRule* mrule = NULL;
1273 int res=0, eqpass= 0;
1276 CachedQuery cq, *qc;
1277 fstack *stack = NULL, *fsp;
1282 /* substring matches sort to the end, and we just have to
1283 * walk the entire list.
1285 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1286 ptr = tavl_end( root, 1 );
1287 dir = TAVL_DIR_LEFT;
1289 ptr = tavl_find3( root, &cq, pcache_query_cmp, &ret );
1290 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1299 /* an incoming substr query can only be satisfied by a cached
1302 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1303 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1306 /* an incoming eq query can be satisfied by a cached eq or substr
1309 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1310 if ( eqpass == 0 ) {
1311 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1312 nextpass: eqpass = 1;
1313 ptr = tavl_end( root, 1 );
1314 dir = TAVL_DIR_LEFT;
1318 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1324 switch (fs->f_choice) {
1325 case LDAP_FILTER_EQUALITY:
1326 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1327 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1331 case LDAP_FILTER_GE:
1332 case LDAP_FILTER_LE:
1333 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1340 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1341 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1342 &(fi->f_ava->aa_value),
1343 &(fs->f_ava->aa_value), &text);
1344 if (rc != LDAP_SUCCESS) {
1347 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1350 switch (fs->f_choice) {
1351 case LDAP_FILTER_OR:
1352 case LDAP_FILTER_AND:
1354 /* save our stack position */
1355 fsp = op->o_tmpalloc(sizeof(fstack), op->o_tmpmemctx);
1356 fsp->fs_next = stack;
1357 fsp->fs_fs = fs->f_next;
1358 fsp->fs_fi = fi->f_next;
1365 case LDAP_FILTER_SUBSTRINGS:
1366 /* check if the equality query can be
1367 * answered with cached substring query */
1368 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1369 && substr_containment_equality( op,
1372 /* check if the substring query can be
1373 * answered with cached substring query */
1374 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1375 ) && substr_containment_substr( op,
1381 case LDAP_FILTER_PRESENT:
1386 case LDAP_FILTER_EQUALITY:
1392 case LDAP_FILTER_GE:
1393 if (mrule && ret >= 0)
1398 case LDAP_FILTER_LE:
1399 if (mrule && ret <= 0)
1404 case LDAP_FILTER_NOT:
1410 if (!fs && !fi && stack) {
1413 stack = fsp->fs_next;
1416 op->o_tmpfree(fsp, op->o_tmpmemctx);
1418 } while((res) && (fi != NULL) && (fs != NULL));
1422 ptr = tavl_next( ptr, dir );
1427 /* check whether query is contained in any of
1428 * the cached queries in template
1430 static CachedQuery *
1431 query_containment(Operation *op, query_manager *qm,
1433 QueryTemplate *templa)
1436 int depth = 0, tscope;
1437 Qbase qbase, *qbptr = NULL;
1440 if (query->filter != NULL) {
1443 Debug( pcache_debug, "Lock QC index = %p\n",
1444 (void *) templa, 0, 0 );
1445 qbase.base = query->base;
1447 first = filter_first( query->filter );
1449 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1452 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1454 tscope = query->scope;
1455 /* Find a matching scope:
1456 * match at depth 0 OK
1459 * subord at depth > 0 OK
1460 * subtree at any depth OK
1462 * subtree or subord at any depth OK
1464 * subtree or subord at any depth OK
1466 * subord at depth > 0 OK
1467 * subtree at any depth OK
1469 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1470 switch ( query->scope ) {
1471 case LDAP_SCOPE_BASE:
1472 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1473 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1474 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1476 case LDAP_SCOPE_ONE:
1477 if ( tscope == LDAP_SCOPE_BASE )
1478 tscope = LDAP_SCOPE_ONE;
1479 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1480 if ( !depth ) break;
1481 if ( tscope < LDAP_SCOPE_SUBTREE )
1482 tscope = LDAP_SCOPE_SUBTREE;
1484 case LDAP_SCOPE_SUBTREE:
1485 if ( tscope < LDAP_SCOPE_SUBTREE )
1486 tscope = LDAP_SCOPE_SUBTREE;
1487 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1489 case LDAP_SCOPE_CHILDREN:
1490 if ( tscope < LDAP_SCOPE_SUBTREE )
1491 tscope = LDAP_SCOPE_SUBTREE;
1494 if ( !qbptr->scopes[tscope] ) continue;
1497 qc = find_filter( op, qbptr->scopes[tscope],
1498 query->filter, first );
1500 if ( qc->q_sizelimit ) {
1501 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1504 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1505 if (qm->lru_top != qc) {
1506 remove_query(qm, qc);
1507 add_query_on_top(qm, qc);
1509 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1514 if ( be_issuffix( op->o_bd, &qbase.base ))
1517 dnParent( &qbase.base, &pdn );
1522 Debug( pcache_debug,
1523 "Not answerable: Unlock QC index=%p\n",
1524 (void *) templa, 0, 0 );
1525 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1531 free_query (CachedQuery* qc)
1533 free(qc->q_uuid.bv_val);
1534 filter_free(qc->filter);
1535 ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1536 ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1537 memset(qc, 0, sizeof(*qc));
1542 /* Add query to query cache, the returned Query is locked for writing */
1543 static CachedQuery *
1548 QueryTemplate *templ,
1549 pc_caching_reason_t why,
1552 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1556 time_t ttl = 0, ttr = 0;
1559 new_cached_query->qtemp = templ;
1560 BER_BVZERO( &new_cached_query->q_uuid );
1561 new_cached_query->q_sizelimit = 0;
1563 now = slap_get_time();
1568 ttr = now + templ->ttr;
1572 ttl = templ->negttl;
1576 ttl = templ->limitttl;
1583 new_cached_query->expiry_time = now + ttl;
1584 new_cached_query->refresh_time = ttr;
1585 new_cached_query->bindref_time = 0;
1587 new_cached_query->bind_refcnt = 0;
1588 new_cached_query->answerable_cnt = 0;
1589 new_cached_query->refcnt = 1;
1590 ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1592 new_cached_query->lru_up = NULL;
1593 new_cached_query->lru_down = NULL;
1594 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1595 (long) new_cached_query->expiry_time,
1596 pc_caching_reason_str[ why ], 0 );
1598 new_cached_query->scope = query->scope;
1599 new_cached_query->filter = query->filter;
1600 new_cached_query->first = first = filter_first( query->filter );
1602 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1604 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1606 qb.base = query->base;
1608 /* Adding a query */
1609 Debug( pcache_debug, "Lock AQ index = %p\n",
1610 (void *) templ, 0, 0 );
1611 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1612 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1614 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1615 qbase->base.bv_len = qb.base.bv_len;
1616 qbase->base.bv_val = (char *)(qbase+1);
1617 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1618 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1619 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1621 new_cached_query->next = templ->query;
1622 new_cached_query->prev = NULL;
1623 new_cached_query->qbase = qbase;
1624 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1625 pcache_query_cmp, avl_dup_error );
1628 if (templ->query == NULL)
1629 templ->query_last = new_cached_query;
1631 templ->query->prev = new_cached_query;
1632 templ->query = new_cached_query;
1633 templ->no_of_queries++;
1635 ldap_pvt_thread_mutex_destroy(&new_cached_query->answerable_cnt_mutex);
1637 ldap_pvt_thread_rdwr_wunlock(&new_cached_query->rwlock);
1638 ldap_pvt_thread_rdwr_destroy( &new_cached_query->rwlock );
1639 ch_free( new_cached_query );
1640 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1641 query->filter, first );
1642 filter_free( query->filter );
1643 query->filter = NULL;
1645 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1646 (void *) templ, templ->no_of_queries, 0 );
1648 /* Adding on top of LRU list */
1650 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1651 add_query_on_top(qm, new_cached_query);
1652 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1654 Debug( pcache_debug, "Unlock AQ index = %p \n",
1655 (void *) templ, 0, 0 );
1656 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1658 return rc == 0 ? new_cached_query : NULL;
1662 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1664 if (!qc->prev && !qc->next) {
1665 template->query_last = template->query = NULL;
1666 } else if (qc->prev == NULL) {
1667 qc->next->prev = NULL;
1668 template->query = qc->next;
1669 } else if (qc->next == NULL) {
1670 qc->prev->next = NULL;
1671 template->query_last = qc->prev;
1673 qc->next->prev = qc->prev;
1674 qc->prev->next = qc->next;
1676 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1677 qc->qbase->queries--;
1678 if ( qc->qbase->queries == 0 ) {
1679 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1680 ch_free( qc->qbase );
1684 template->no_of_queries--;
1687 /* remove bottom query of LRU list from the query cache */
1689 * NOTE: slight change in functionality.
1691 * - if result->bv_val is NULL, the query at the bottom of the LRU
1693 * - otherwise, the query whose UUID is *result is removed
1694 * - if not found, result->bv_val is zeroed
1697 cache_replacement(query_manager* qm, struct berval *result)
1699 CachedQuery* bottom;
1700 QueryTemplate *temp;
1702 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1703 if ( BER_BVISNULL( result ) ) {
1704 bottom = qm->lru_bottom;
1707 Debug ( pcache_debug,
1708 "Cache replacement invoked without "
1709 "any query in LRU list\n", 0, 0, 0 );
1710 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1715 for ( bottom = qm->lru_bottom;
1717 bottom = bottom->lru_up )
1719 if ( bvmatch( result, &bottom->q_uuid ) ) {
1725 Debug ( pcache_debug,
1726 "Could not find query with uuid=\"%s\""
1727 "in LRU list\n", result->bv_val, 0, 0 );
1728 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1729 BER_BVZERO( result );
1734 temp = bottom->qtemp;
1735 remove_query(qm, bottom);
1736 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1738 *result = bottom->q_uuid;
1739 BER_BVZERO( &bottom->q_uuid );
1741 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1742 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1743 remove_from_template(bottom, temp);
1744 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1745 (void *) temp, temp->no_of_queries, 0 );
1746 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1747 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1752 struct query_info *next;
1764 struct query_info *qi;
1767 if ( rs->sr_type != REP_SEARCH ) return 0;
1769 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1770 if ( attr == NULL ) return 0;
1772 count = attr->a_numvals;
1773 assert( count > 0 );
1774 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1775 qi->next = op->o_callback->sc_private;
1776 op->o_callback->sc_private = qi;
1777 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1778 qi->del = ( count == 1 );
1786 struct berval *query_uuid )
1788 struct query_info *qi, *qnext;
1789 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
1790 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1791 Filter filter = {LDAP_FILTER_EQUALITY};
1792 SlapReply sreply = {REP_RESULT};
1793 slap_callback cb = { NULL, remove_func, NULL, NULL };
1796 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1797 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1798 filter.f_ava = &ava;
1799 filter.f_av_desc = ad_queryId;
1800 filter.f_av_value = *query_uuid;
1802 op->o_tag = LDAP_REQ_SEARCH;
1803 op->o_protocol = LDAP_VERSION3;
1804 op->o_callback = &cb;
1805 op->o_time = slap_get_time();
1806 op->o_do_not_cache = 1;
1808 op->o_req_dn = op->o_bd->be_suffix[0];
1809 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1810 op->ors_scope = LDAP_SCOPE_SUBTREE;
1811 op->ors_deref = LDAP_DEREF_NEVER;
1812 op->ors_slimit = SLAP_NO_LIMIT;
1813 op->ors_tlimit = SLAP_NO_LIMIT;
1814 op->ors_limit = NULL;
1815 op->ors_filter = &filter;
1816 op->ors_filterstr.bv_val = filter_str;
1817 op->ors_filterstr.bv_len = strlen(filter_str);
1818 op->ors_attrs = NULL;
1819 op->ors_attrsonly = 0;
1821 op->o_bd->be_search( op, &sreply );
1823 for ( qi=cb.sc_private; qi; qi=qnext ) {
1826 op->o_req_dn = qi->xdn;
1827 op->o_req_ndn = qi->xdn;
1828 rs_reinit( &sreply, REP_RESULT );
1831 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1832 query_uuid->bv_val, 0, 0 );
1834 op->o_tag = LDAP_REQ_DELETE;
1836 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1842 struct berval vals[2];
1844 vals[0] = *query_uuid;
1845 vals[1].bv_val = NULL;
1847 mod.sml_op = LDAP_MOD_DELETE;
1849 mod.sml_desc = ad_queryId;
1850 mod.sml_type = ad_queryId->ad_cname;
1851 mod.sml_values = vals;
1852 mod.sml_nvalues = NULL;
1853 mod.sml_numvals = 1;
1854 mod.sml_next = NULL;
1855 Debug( pcache_debug,
1856 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1857 query_uuid->bv_val, 0, 0 );
1859 op->orm_modlist = &mod;
1861 op->o_bd->be_modify( op, &sreply );
1863 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1864 op->o_tmpfree( qi, op->o_tmpmemctx );
1871 AttributeName* attrs,
1880 struct berval *fstr )
1882 AttributeDescription *ad;
1885 switch ( f->f_choice ) {
1886 case LDAP_FILTER_EQUALITY:
1888 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1889 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1890 assert( ret == len );
1891 fstr->bv_len += len;
1894 case LDAP_FILTER_GE:
1896 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1897 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1898 assert( ret == len );
1899 fstr->bv_len += len;
1902 case LDAP_FILTER_LE:
1904 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1905 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1906 assert( ret == len );
1907 fstr->bv_len += len;
1910 case LDAP_FILTER_APPROX:
1912 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1913 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1914 assert( ret == len );
1915 fstr->bv_len += len;
1918 case LDAP_FILTER_SUBSTRINGS:
1920 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1921 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1922 assert( ret == len );
1923 fstr->bv_len += len;
1926 case LDAP_FILTER_PRESENT:
1928 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1929 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1930 assert( ret == len );
1931 fstr->bv_len += len;
1934 case LDAP_FILTER_AND:
1935 case LDAP_FILTER_OR:
1936 case LDAP_FILTER_NOT: {
1938 fstr->bv_val[fstr->bv_len++] = '(';
1939 switch ( f->f_choice ) {
1940 case LDAP_FILTER_AND:
1941 fstr->bv_val[fstr->bv_len] = '&';
1943 case LDAP_FILTER_OR:
1944 fstr->bv_val[fstr->bv_len] = '|';
1946 case LDAP_FILTER_NOT:
1947 fstr->bv_val[fstr->bv_len] = '!';
1952 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1953 rc = filter2template( op, f, fstr );
1956 fstr->bv_val[fstr->bv_len++] = ')';
1957 fstr->bv_val[fstr->bv_len] = '\0';
1963 /* a filter should at least have room for "()",
1964 * an "=" and for a 1-char attr */
1965 strcpy( fstr->bv_val, "(?=)" );
1966 fstr->bv_len += STRLENOF("(?=)");
1973 #define BI_HASHED 0x01
1974 #define BI_DIDCB 0x02
1975 #define BI_LOOKUP 0x04
1979 typedef struct bindinfo {
1980 cache_manager *bi_cm;
1982 QueryTemplate *bi_templ;
1983 struct search_info *bi_si;
1985 slap_callback bi_cb;
1988 struct search_info {
1991 QueryTemplate *qtemp;
1992 AttributeName* save_attrs; /* original attributes, saved for response */
1993 int swap_saved_attrs;
1998 int slimit_exceeded;
1999 pc_caching_reason_t caching_reason;
2005 remove_query_and_data(
2008 struct berval *uuid )
2010 query_manager* qm = cm->qm;
2012 qm->crfunc( qm, uuid );
2013 if ( !BER_BVISNULL( uuid ) ) {
2016 Debug( pcache_debug,
2017 "Removing query UUID %s\n",
2018 uuid->bv_val, 0, 0 );
2019 return_val = remove_query_data( op, uuid );
2020 Debug( pcache_debug,
2021 "QUERY REMOVED, SIZE=%d\n",
2023 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
2024 cm->cur_entries -= return_val;
2025 cm->num_cached_queries--;
2026 Debug( pcache_debug,
2027 "STORED QUERIES = %lu\n",
2028 cm->num_cached_queries, 0, 0 );
2029 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
2030 Debug( pcache_debug,
2031 "QUERY REMOVED, CACHE ="
2033 cm->cur_entries, 0, 0 );
2038 * Callback used to fetch queryId values based on entryUUID;
2039 * used by pcache_remove_entries_from_cache()
2042 fetch_queryId_cb( Operation *op, SlapReply *rs )
2046 /* only care about searchEntry responses */
2047 if ( rs->sr_type != REP_SEARCH ) {
2051 /* allow only one response per entryUUID */
2052 if ( op->o_callback->sc_private != NULL ) {
2058 /* copy all queryId values into callback's private data */
2059 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2061 BerVarray vals = NULL;
2063 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
2064 op->o_callback->sc_private = (void *)vals;
2068 /* clear entry if required */
2069 rs_flush_entry( op, rs, (slap_overinst *) op->o_bd->bd_info );
2075 * Call that allows to remove a set of entries from the cache,
2076 * by forcing the removal of all the related queries.
2079 pcache_remove_entries_from_cache(
2082 BerVarray entryUUIDs )
2084 Connection conn = { 0 };
2085 OperationBuffer opbuf;
2087 slap_callback sc = { 0 };
2089 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
2090 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2091 AttributeName attrs[ 2 ] = {{{ 0 }}};
2095 void *thrctx = ldap_pvt_thread_pool_context();
2097 connection_fake_init( &conn, &opbuf, thrctx );
2105 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2106 op->ors_scope = LDAP_SCOPE_SUBTREE;
2107 op->ors_deref = LDAP_DEREF_NEVER;
2108 f.f_choice = LDAP_FILTER_EQUALITY;
2110 ava.aa_desc = slap_schema.si_ad_entryUUID;
2111 op->ors_filter = &f;
2113 op->ors_tlimit = SLAP_NO_LIMIT;
2114 op->ors_limit = NULL;
2115 attrs[ 0 ].an_desc = ad_queryId;
2116 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2117 op->ors_attrs = attrs;
2118 op->ors_attrsonly = 0;
2120 op->o_req_dn = cm->db.be_suffix[ 0 ];
2121 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2123 op->o_tag = LDAP_REQ_SEARCH;
2124 op->o_protocol = LDAP_VERSION3;
2125 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2127 op->o_dn = op->o_bd->be_rootdn;
2128 op->o_ndn = op->o_bd->be_rootndn;
2129 sc.sc_response = fetch_queryId_cb;
2130 op->o_callback = ≻
2132 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
2133 BerVarray vals = NULL;
2134 SlapReply rs = { REP_RESULT };
2136 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
2137 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
2138 op->ors_filterstr.bv_val = filtbuf;
2139 ava.aa_value = entryUUIDs[ s ];
2141 rc = op->o_bd->be_search( op, &rs );
2142 if ( rc != LDAP_SUCCESS ) {
2146 vals = (BerVarray)op->o_callback->sc_private;
2147 if ( vals != NULL ) {
2150 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2151 struct berval val = vals[ i ];
2153 remove_query_and_data( op, cm, &val );
2155 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2156 ch_free( val.bv_val );
2160 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2161 op->o_callback->sc_private = NULL;
2169 * Call that allows to remove a query from the cache.
2172 pcache_remove_query_from_cache(
2175 struct berval *queryid )
2177 Operation op2 = *op;
2181 /* remove the selected query */
2182 remove_query_and_data( &op2, cm, queryid );
2184 return LDAP_SUCCESS;
2188 * Call that allows to remove a set of queries related to an entry
2189 * from the cache; if queryid is not null, the entry must belong to
2190 * the query indicated by queryid.
2193 pcache_remove_entry_queries_from_cache(
2197 struct berval *queryid )
2199 Connection conn = { 0 };
2200 OperationBuffer opbuf;
2202 slap_callback sc = { 0 };
2203 SlapReply rs = { REP_RESULT };
2205 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
2206 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2207 AttributeName attrs[ 2 ] = {{{ 0 }}};
2210 BerVarray vals = NULL;
2213 void *thrctx = ldap_pvt_thread_pool_context();
2215 connection_fake_init( &conn, &opbuf, thrctx );
2223 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2224 op->ors_scope = LDAP_SCOPE_BASE;
2225 op->ors_deref = LDAP_DEREF_NEVER;
2226 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
2227 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
2228 f.f_choice = LDAP_FILTER_PRESENT;
2229 f.f_desc = slap_schema.si_ad_objectClass;
2232 op->ors_filterstr.bv_len = snprintf( filter_str,
2233 sizeof( filter_str ), "(%s=%s)",
2234 ad_queryId->ad_cname.bv_val, queryid->bv_val );
2235 f.f_choice = LDAP_FILTER_EQUALITY;
2237 f.f_av_desc = ad_queryId;
2238 f.f_av_value = *queryid;
2240 op->ors_filter = &f;
2242 op->ors_tlimit = SLAP_NO_LIMIT;
2243 op->ors_limit = NULL;
2244 attrs[ 0 ].an_desc = ad_queryId;
2245 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2246 op->ors_attrs = attrs;
2247 op->ors_attrsonly = 0;
2249 op->o_req_dn = *ndn;
2250 op->o_req_ndn = *ndn;
2252 op->o_tag = LDAP_REQ_SEARCH;
2253 op->o_protocol = LDAP_VERSION3;
2254 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2256 op->o_dn = op->o_bd->be_rootdn;
2257 op->o_ndn = op->o_bd->be_rootndn;
2258 sc.sc_response = fetch_queryId_cb;
2259 op->o_callback = ≻
2261 rc = op->o_bd->be_search( op, &rs );
2262 if ( rc != LDAP_SUCCESS ) {
2266 vals = (BerVarray)op->o_callback->sc_private;
2267 if ( vals != NULL ) {
2270 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2271 struct berval val = vals[ i ];
2273 remove_query_and_data( op, cm, &val );
2275 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2276 ch_free( val.bv_val );
2280 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2283 return LDAP_SUCCESS;
2289 struct berval *query_uuid )
2291 struct search_info *si = op->o_callback->sc_private;
2292 slap_overinst *on = si->on;
2293 cache_manager *cm = on->on_bi.bi_private;
2296 struct berval crp_uuid;
2297 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2299 Connection conn = {0};
2300 OperationBuffer opbuf;
2301 void *thrctx = ldap_pvt_thread_pool_context();
2303 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2304 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2306 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2307 op_tmp = &opbuf.ob_op;
2308 op_tmp->o_bd = &cm->db;
2309 op_tmp->o_dn = cm->db.be_rootdn;
2310 op_tmp->o_ndn = cm->db.be_rootndn;
2312 Debug( pcache_debug, "UUID for query being added = %s\n",
2315 for ( e=si->head; e; e=si->head ) {
2316 si->head = e->e_private;
2317 e->e_private = NULL;
2318 while ( cm->cur_entries > (cm->max_entries) ) {
2319 BER_BVZERO( &crp_uuid );
2320 remove_query_and_data( op_tmp, cm, &crp_uuid );
2323 return_val = merge_entry(op_tmp, e, 0, query_uuid);
2324 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2325 cm->cur_entries += return_val;
2326 Debug( pcache_debug,
2327 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2328 cm->cur_entries, 0, 0 );
2330 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2337 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2338 slap_callback *cb = op->o_callback;
2339 struct search_info *si = cb->sc_private;
2340 slap_overinst *on = si->on;
2341 cache_manager *cm = on->on_bi.bi_private;
2342 query_manager* qm = cm->qm;
2344 if ( rs->sr_type == REP_RESULT ||
2345 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2347 if ( si->swap_saved_attrs ) {
2348 rs->sr_attrs = si->save_attrs;
2349 op->ors_attrs = si->save_attrs;
2351 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) &&
2352 si->caching_reason == PC_IGNORE )
2354 filter_free( si->query.filter );
2356 /* duplicate query, free it */
2358 for (;si->head; si->head=e) {
2359 e = si->head->e_private;
2360 si->head->e_private = NULL;
2361 entry_free(si->head);
2365 } else if ( si->caching_reason != PC_IGNORE ) {
2366 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2367 si->qtemp, si->caching_reason, 1 );
2370 switch ( si->caching_reason ) {
2372 cache_entries( op, &qc->q_uuid );
2375 si->pbi->bi_cq = qc;
2380 qc->q_sizelimit = rs->sr_nentries;
2390 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2391 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2392 cm->num_cached_queries++;
2393 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2394 cm->num_cached_queries, 0, 0 );
2395 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2397 /* If the consistency checker suspended itself,
2400 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2401 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2402 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2404 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2406 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2409 } else if ( si->count ) {
2410 /* duplicate query, free it */
2412 for (;si->head; si->head=e) {
2413 e = si->head->e_private;
2414 si->head->e_private = NULL;
2415 entry_free(si->head);
2420 filter_free( si->query.filter );
2423 op->o_callback = op->o_callback->sc_next;
2424 op->o_tmpfree( cb, op->o_tmpmemctx );
2427 return SLAP_CB_CONTINUE;
2435 struct search_info *si = op->o_callback->sc_private;
2437 if ( si->swap_saved_attrs ) {
2438 rs->sr_attrs = si->save_attrs;
2439 rs->sr_attr_flags = slap_attr_flags( si->save_attrs );
2440 op->ors_attrs = si->save_attrs;
2443 if ( rs->sr_type == REP_SEARCH ) {
2446 /* don't return more entries than requested by the client */
2447 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2448 si->slimit_exceeded = 1;
2451 /* If we haven't exceeded the limit for this query,
2452 * build a chain of answers to store. If we hit the
2453 * limit, empty the chain and ignore the rest.
2456 slap_overinst *on = si->on;
2457 cache_manager *cm = on->on_bi.bi_private;
2459 /* check if the entry contains undefined
2460 * attributes/objectClasses (ITS#5680) */
2461 if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2462 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2463 op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
2467 /* check for malformed entries: attrs with no values */
2469 Attribute *a = rs->sr_entry->e_attrs;
2470 for (; a; a=a->a_next) {
2471 if ( !a->a_numvals ) {
2472 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2473 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2474 a->a_desc->ad_cname.bv_val );
2480 if ( si->count < si->max ) {
2482 e = entry_dup( rs->sr_entry );
2483 if ( !si->head ) si->head = e;
2484 if ( si->tail ) si->tail->e_private = e;
2491 for (;si->head; si->head=e) {
2492 e = si->head->e_private;
2493 si->head->e_private = NULL;
2494 entry_free(si->head);
2499 if ( si->slimit_exceeded ) {
2502 } else if ( rs->sr_type == REP_RESULT ) {
2505 if ( rs->sr_err == LDAP_SUCCESS ) {
2506 si->caching_reason = PC_POSITIVE;
2508 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2509 && si->qtemp->limitttl )
2513 si->caching_reason = PC_SIZELIMIT;
2514 for (;si->head; si->head=e) {
2515 e = si->head->e_private;
2516 si->head->e_private = NULL;
2517 entry_free(si->head);
2521 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2522 rs->sr_err == LDAP_SUCCESS )
2524 si->caching_reason = PC_NEGATIVE;
2528 if ( si->slimit_exceeded ) {
2529 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2533 return SLAP_CB_CONTINUE;
2536 /* NOTE: this is a quick workaround to let pcache minimally interact
2537 * with pagedResults. A more articulated solutions would be to
2538 * perform the remote query without control and cache all results,
2539 * performing the pagedResults search only within the client
2540 * and the proxy. This requires pcache to understand pagedResults. */
2542 pcache_chk_controls(
2546 const char *non = "";
2547 const char *stripped = "";
2549 switch( op->o_pagedresults ) {
2550 case SLAP_CONTROL_NONCRITICAL:
2552 stripped = "; stripped";
2555 case SLAP_CONTROL_CRITICAL:
2556 Debug( pcache_debug, "%s: "
2557 "%scritical pagedResults control "
2558 "disabled with proxy cache%s.\n",
2559 op->o_log_prefix, non, stripped );
2561 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2565 rs->sr_err = SLAP_CB_CONTINUE;
2573 pc_setpw( Operation *op, struct berval *pwd, cache_manager *cm )
2575 struct berval vals[2];
2578 const char *text = NULL;
2579 BER_BVZERO( &vals[0] );
2580 slap_passwd_hash( pwd, &vals[0], &text );
2581 if ( BER_BVISEMPTY( &vals[0] )) {
2582 Debug( pcache_debug, "pc_setpw: hash failed %s\n",
2588 BER_BVZERO( &vals[1] );
2592 SlapReply sr = { REP_RESULT };
2593 slap_callback cb = { 0, slap_null_cb, 0, 0 };
2596 mod.sml_op = LDAP_MOD_REPLACE;
2598 mod.sml_desc = slap_schema.si_ad_userPassword;
2599 mod.sml_type = mod.sml_desc->ad_cname;
2600 mod.sml_values = vals;
2601 mod.sml_nvalues = NULL;
2602 mod.sml_numvals = 1;
2603 mod.sml_next = NULL;
2605 op->o_tag = LDAP_REQ_MODIFY;
2606 op->orm_modlist = &mod;
2608 op->o_dn = op->o_bd->be_rootdn;
2609 op->o_ndn = op->o_bd->be_rootndn;
2610 op->o_callback = &cb;
2611 Debug( pcache_debug, "pc_setpw: CACHING BIND for %s\n",
2612 op->o_req_dn.bv_val, 0, 0 );
2613 rc = op->o_bd->be_modify( op, &sr );
2614 ch_free( vals[0].bv_val );
2619 typedef struct bindcacheinfo {
2625 pc_bind_save( Operation *op, SlapReply *rs )
2627 if ( rs->sr_err == LDAP_SUCCESS ) {
2628 bindcacheinfo *bci = op->o_callback->sc_private;
2629 slap_overinst *on = bci->on;
2630 cache_manager *cm = on->on_bi.bi_private;
2631 CachedQuery *qc = bci->qc;
2634 ldap_pvt_thread_rdwr_wlock( &qc->rwlock );
2635 if ( qc->bind_refcnt-- ) {
2636 Operation op2 = *op;
2637 if ( pc_setpw( &op2, &op->orb_cred, cm ) == LDAP_SUCCESS )
2638 bci->qc->bindref_time = op->o_time + bci->qc->qtemp->bindttr;
2643 ldap_pvt_thread_rdwr_wunlock( &qc->rwlock );
2644 if ( delete ) free_query(qc);
2646 return SLAP_CB_CONTINUE;
2650 pc_bind_attrs( Operation *op, Entry *e, QueryTemplate *temp,
2651 struct berval *fbv )
2654 struct berval *vals, pres = BER_BVC("*");
2658 vals = op->o_tmpalloc( temp->bindnattrs * sizeof( struct berval ),
2661 for ( i=0; i<temp->bindnattrs; i++ ) {
2662 a = attr_find( e->e_attrs, temp->bindfattrs[i] );
2663 if ( a && a->a_vals ) {
2664 vals[i] = a->a_vals[0];
2665 len += a->a_vals[0].bv_len;
2670 fbv->bv_len = len + temp->bindftemp.bv_len;
2671 fbv->bv_val = op->o_tmpalloc( fbv->bv_len + 1, op->o_tmpmemctx );
2673 p1 = temp->bindftemp.bv_val;
2678 if ( p1[0] == '=' && p1[1] == ')' ) {
2679 AC_MEMCPY( p2, vals[i].bv_val, vals[i].bv_len );
2680 p2 += vals[i].bv_len;
2686 op->o_tmpfree( vals, op->o_tmpmemctx );
2688 /* FIXME: are we sure str2filter_x can't fail?
2689 * caller needs to check */
2691 Filter *f = str2filter_x( op, fbv->bv_val );
2692 assert( f != NULL );
2697 /* Check if the requested entry is from the cache and has a valid
2698 * ttr and password hash
2701 pc_bind_search( Operation *op, SlapReply *rs )
2703 if ( rs->sr_type == REP_SEARCH ) {
2704 bindinfo *pbi = op->o_callback->sc_private;
2706 /* We only care if this is an already cached result and we're
2707 * below the refresh time, or we're offline.
2710 if (( pbi->bi_cm->cc_paused & PCACHE_CC_OFFLINE ) ||
2711 op->o_time < pbi->bi_cq->bindref_time ) {
2714 /* See if a recognized password is hashed here */
2715 a = attr_find( rs->sr_entry->e_attrs,
2716 slap_schema.si_ad_userPassword );
2717 if ( a && a->a_vals[0].bv_val[0] == '{' &&
2718 lutil_passwd_scheme( a->a_vals[0].bv_val ))
2719 pbi->bi_flags |= BI_HASHED;
2721 Debug( pcache_debug, "pc_bind_search: cache is stale, "
2722 "reftime: %ld, current time: %ld\n",
2723 pbi->bi_cq->bindref_time, op->o_time, 0 );
2725 } else if ( pbi->bi_si ) {
2726 /* This search result is going into the cache */
2730 filter_free( pbi->bi_si->query.filter );
2731 f = pc_bind_attrs( op, rs->sr_entry, pbi->bi_templ, &fbv );
2732 op->o_tmpfree( fbv.bv_val, op->o_tmpmemctx );
2733 pbi->bi_si->query.filter = filter_dup( f, NULL );
2734 filter_free_x( op, f, 1 );
2740 /* We always want pc_bind_search to run after the search handlers */
2742 pc_bind_resp( Operation *op, SlapReply *rs )
2744 bindinfo *pbi = op->o_callback->sc_private;
2745 if ( !( pbi->bi_flags & BI_DIDCB )) {
2746 slap_callback *sc = op->o_callback;
2747 while ( sc && sc->sc_response != pcache_response )
2750 sc = op->o_callback;
2751 pbi->bi_cb.sc_next = sc->sc_next;
2752 sc->sc_next = &pbi->bi_cb;
2753 pbi->bi_flags |= BI_DIDCB;
2755 return SLAP_CB_CONTINUE;
2758 #ifdef PCACHE_CONTROL_PRIVDB
2764 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2765 cache_manager *cm = on->on_bi.bi_private;
2766 slap_callback *save_cb;
2769 /* skip if control is unset */
2770 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2771 return SLAP_CB_CONTINUE;
2774 /* The cache DB isn't open yet */
2775 if ( cm->defer_db_open ) {
2776 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2777 "pcachePrivDB: cacheDB not available" );
2781 /* FIXME: might be a little bit exaggerated... */
2782 if ( !be_isroot( op ) ) {
2783 save_cb = op->o_callback;
2784 op->o_callback = NULL;
2785 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2786 "pcachePrivDB: operation not allowed" );
2787 op->o_callback = save_cb;
2792 /* map tag to operation */
2793 type = slap_req2op( op->o_tag );
2794 if ( type != SLAP_OP_LAST ) {
2798 /* execute, if possible */
2799 func = &cm->db.be_bind;
2800 if ( func[ type ] != NULL ) {
2801 Operation op2 = *op;
2805 rc = func[ type ]( &op2, rs );
2806 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2807 op->o_conn->c_authz_cookie = cm->db.be_private;
2814 /* otherwise fall back to error */
2815 save_cb = op->o_callback;
2816 op->o_callback = NULL;
2817 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2818 "operation not supported with pcachePrivDB control" );
2819 op->o_callback = save_cb;
2823 #endif /* PCACHE_CONTROL_PRIVDB */
2830 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2831 cache_manager *cm = on->on_bi.bi_private;
2832 QueryTemplate *temp;
2834 slap_callback cb = { 0 }, *sc;
2840 #ifdef PCACHE_CONTROL_PRIVDB
2841 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL )
2842 return pcache_op_privdb( op, rs );
2843 #endif /* PCACHE_CONTROL_PRIVDB */
2845 /* Skip if we're not configured for Binds, or cache DB isn't open yet */
2846 if ( !cm->cache_binds || cm->defer_db_open )
2847 return SLAP_CB_CONTINUE;
2849 /* First find a matching template with Bind info */
2850 for ( temp=cm->qm->templates; temp; temp=temp->qmnext ) {
2851 if ( temp->bindttr && dnIsSuffix( &op->o_req_ndn, &temp->bindbase ))
2854 /* Didn't find a suitable template, just passthru */
2856 return SLAP_CB_CONTINUE;
2858 /* See if the entry is already locally cached. If so, we can
2859 * populate the query filter to retrieve the cached query. We
2860 * need to check the bindrefresh time in the query.
2863 op2.o_dn = op->o_bd->be_rootdn;
2864 op2.o_ndn = op->o_bd->be_rootndn;
2869 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL, NULL, 0, &e );
2870 if ( rc == LDAP_SUCCESS && e ) {
2871 bi.bi_flags |= BI_LOOKUP;
2872 op2.ors_filter = pc_bind_attrs( op, e, temp, &op2.ors_filterstr );
2873 be_entry_release_r( &op2, e );
2875 op2.ors_filter = temp->bindfilter;
2876 op2.ors_filterstr = temp->bindfilterstr;
2879 op2.o_bd = op->o_bd;
2880 op2.o_tag = LDAP_REQ_SEARCH;
2881 op2.ors_scope = LDAP_SCOPE_BASE;
2882 op2.ors_deref = LDAP_DEREF_NEVER;
2884 op2.ors_tlimit = SLAP_NO_LIMIT;
2885 op2.ors_limit = NULL;
2886 op2.ors_attrs = cm->qm->attr_sets[temp->attr_set_index].attrs;
2887 op2.ors_attrsonly = 0;
2889 /* We want to invoke search at the same level of the stack
2890 * as we're already at...
2897 bi.bi_cb.sc_response = pc_bind_search;
2898 bi.bi_cb.sc_cleanup = NULL;
2899 bi.bi_cb.sc_private = &bi;
2900 cb.sc_private = &bi;
2901 cb.sc_response = pc_bind_resp;
2902 op2.o_callback = &cb;
2903 overlay_op_walk( &op2, rs, op_search, on->on_info, on );
2905 /* OK, just bind locally */
2906 if ( bi.bi_flags & BI_HASHED ) {
2908 BackendDB *be = op->o_bd;
2911 Debug( pcache_debug, "pcache_op_bind: CACHED BIND for %s\n",
2912 op->o_req_dn.bv_val, 0, 0 );
2914 if ( op->o_bd->be_bind( op, rs ) == LDAP_SUCCESS ) {
2915 op->o_conn->c_authz_cookie = cm->db.be_private;
2918 ldap_pvt_thread_rdwr_wlock( &bi.bi_cq->rwlock );
2919 if ( !bi.bi_cq->bind_refcnt-- ) {
2922 ldap_pvt_thread_rdwr_wunlock( &bi.bi_cq->rwlock );
2923 if ( delete ) free_query( bi.bi_cq );
2927 /* We have a cached query to work with */
2929 sc = op->o_tmpalloc( sizeof(slap_callback) + sizeof(bindcacheinfo),
2931 sc->sc_response = pc_bind_save;
2932 sc->sc_cleanup = NULL;
2933 sc->sc_private = sc+1;
2934 bci = sc->sc_private;
2935 sc->sc_next = op->o_callback;
2936 op->o_callback = sc;
2940 return SLAP_CB_CONTINUE;
2943 static slap_response refresh_merge;
2950 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2951 cache_manager *cm = on->on_bi.bi_private;
2952 query_manager* qm = cm->qm;
2957 QueryTemplate *qtemp = NULL;
2958 bindinfo *pbi = NULL;
2961 CachedQuery *answerable = NULL;
2964 struct berval tempstr;
2966 #ifdef PCACHE_CONTROL_PRIVDB
2967 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2968 return pcache_op_privdb( op, rs );
2970 #endif /* PCACHE_CONTROL_PRIVDB */
2972 /* The cache DB isn't open yet */
2973 if ( cm->defer_db_open ) {
2974 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2975 "pcachePrivDB: cacheDB not available" );
2979 /* pickup runtime ACL changes */
2980 cm->db.be_acl = op->o_bd->be_acl;
2983 /* See if we're processing a Bind request
2984 * or a cache refresh */
2985 slap_callback *cb = op->o_callback;
2987 for ( ; cb; cb=cb->sc_next ) {
2988 if ( cb->sc_response == pc_bind_resp ) {
2989 pbi = cb->sc_private;
2992 if ( cb->sc_response == refresh_merge ) {
2993 /* This is a refresh, do not search the cache */
2994 return SLAP_CB_CONTINUE;
2999 /* FIXME: cannot cache/answer requests with pagedResults control */
3001 query.filter = op->ors_filter;
3004 query.base = pbi->bi_templ->bindbase;
3005 query.scope = pbi->bi_templ->bindscope;
3006 attr_set = pbi->bi_templ->attr_set_index;
3008 qtemp = pbi->bi_templ;
3009 if ( pbi->bi_flags & BI_LOOKUP )
3010 answerable = qm->qcfunc(op, qm, &query, qtemp);
3013 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1,
3016 if ( filter2template( op, op->ors_filter, &tempstr ))
3018 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3019 return SLAP_CB_CONTINUE;
3022 Debug( pcache_debug, "query template of incoming query = %s\n",
3023 tempstr.bv_val, 0, 0 );
3026 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
3028 query.base = op->o_req_ndn;
3029 query.scope = op->ors_scope;
3031 /* check for query containment */
3032 if (attr_set > -1) {
3033 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
3034 for (; qt; qt = qt->qtnext ) {
3035 /* find if template i can potentially answer tempstr */
3036 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
3040 Debug( pcache_debug, "Entering QC, querystr = %s\n",
3041 op->ors_filterstr.bv_val, 0, 0 );
3042 answerable = qm->qcfunc(op, qm, &query, qt);
3044 /* if != NULL, rlocks qtemp->t_rwlock */
3049 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3053 BackendDB *save_bd = op->o_bd;
3055 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
3056 answerable->answerable_cnt++;
3057 /* we only care about refcnts if we're refreshing */
3058 if ( answerable->refresh_time )
3059 answerable->refcnt++;
3060 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
3061 answerable->answerable_cnt, 0, 0 );
3062 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
3064 ldap_pvt_thread_rdwr_wlock(&answerable->rwlock);
3065 if ( BER_BVISNULL( &answerable->q_uuid )) {
3066 /* No entries cached, just an empty result set */
3068 send_ldap_result( op, rs );
3070 /* Let Bind know we used a cached query */
3072 answerable->bind_refcnt++;
3073 pbi->bi_cq = answerable;
3077 if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
3079 /* The cached entry was already processed by any
3080 * other overlays, so don't let it get processed again.
3082 * This loop removes over_back_response from the stack.
3084 if ( overlay_callback_after_backover( op, &cb, 0) == 0 ) {
3085 slap_callback **scp;
3086 for ( scp = &op->o_callback; *scp != NULL;
3087 scp = &(*scp)->sc_next ) {
3088 if ( (*scp)->sc_next == &cb ) {
3095 i = cm->db.bd_info->bi_op_search( op, rs );
3097 ldap_pvt_thread_rdwr_wunlock(&answerable->rwlock);
3098 /* locked by qtemp->qcfunc (query_containment) */
3099 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
3104 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
3106 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3107 if (cm->num_cached_queries >= cm->max_queries) {
3110 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3112 if (op->ors_attrsonly)
3117 struct search_info *si;
3119 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
3120 query.filter = filter_dup(op->ors_filter, NULL);
3122 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
3123 cb->sc_response = pcache_response;
3124 cb->sc_cleanup = pcache_op_cleanup;
3125 cb->sc_private = (cb+1);
3126 si = cb->sc_private;
3130 si->max = cm->num_entries_limit ;
3134 si->slimit_exceeded = 0;
3135 si->caching_reason = PC_IGNORE;
3136 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
3137 si->slimit = op->ors_slimit;
3138 op->ors_slimit = cm->num_entries_limit;
3142 si->swap_saved_attrs = 1;
3143 si->save_attrs = op->ors_attrs;
3148 op->ors_attrs = qtemp->t_attrs.attrs;
3150 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3151 cb->sc_next = op->o_callback;
3152 op->o_callback = cb;
3155 slap_callback **pcb;
3157 /* need to move the callback at the end, in case other
3158 * overlays are present, so that the final entry is
3159 * actually cached */
3161 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
3166 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
3170 return SLAP_CB_CONTINUE;
3175 AttributeName* attrs,
3183 for ( ; attrs[i].an_name.bv_val; i++ ) {
3184 /* only count valid attribute names
3185 * (searches ignore others, this overlay does the same) */
3186 if ( attrs[i].an_desc ) {
3192 /* recognize default or explicit single "*" */
3194 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_all_user_attrs ) ) )
3197 attrs = slap_anlist_all_user_attributes;
3199 /* recognize implicit (no valid attributes) or explicit single "1.1" */
3200 } else if ( count == 0 ||
3201 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) )
3207 for ( i = 0; i < num; i++ ) {
3211 if ( count > qm->attr_sets[i].count ) {
3212 if ( qm->attr_sets[i].count &&
3213 bvmatch( &qm->attr_sets[i].attrs[0].an_name, slap_bv_all_user_attrs )) {
3220 if ( !qm->attr_sets[i].count ) {
3226 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
3227 if ( !a2->an_desc && !bvmatch( &a2->an_name, slap_bv_all_user_attrs ) ) continue;
3229 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
3247 /* Refresh a cached query:
3248 * 1: Replay the query on the remote DB and merge each entry into
3249 * the local DB. Remember the DNs of each remote entry.
3250 * 2: Search the local DB for all entries matching this queryID.
3251 * Delete any entry whose DN is not in the list from (1).
3253 typedef struct dnlist {
3254 struct dnlist *next;
3259 typedef struct refresh_info {
3267 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
3269 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
3271 dn->dn.bv_len = bvdn->bv_len;
3272 dn->dn.bv_val = (char *)(dn+1);
3273 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
3274 dn->dn.bv_val[dn->dn.bv_len] = '\0';
3279 refresh_merge( Operation *op, SlapReply *rs )
3281 if ( rs->sr_type == REP_SEARCH ) {
3282 refresh_info *ri = op->o_callback->sc_private;
3288 ocb = op->o_callback;
3289 /* Find local entry, merge */
3290 op->o_bd = ri->ri_be;
3291 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
3292 if ( rc != LDAP_SUCCESS || e == NULL ) {
3293 /* No local entry, just add it. FIXME: we are not checking
3294 * the cache entry limit here
3296 merge_entry( op, rs->sr_entry, 1, &ri->ri_q->q_uuid );
3298 /* Entry exists, update it */
3301 Modifications *modlist, *mods = NULL;
3302 const char* text = NULL;
3303 char textbuf[SLAP_TEXT_BUFLEN];
3304 size_t textlen = sizeof(textbuf);
3305 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
3309 /* Get a copy of only the attrs we requested */
3310 for ( a=e->e_attrs; a; a=a->a_next ) {
3311 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
3312 *b = attr_alloc( a->a_desc );
3314 /* The actual values still belong to e */
3315 (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
3316 SLAP_ATTR_DONT_FREE_DATA;
3317 b = &((*b)->a_next);
3321 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
3322 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
3323 &mods, &modlist, 0 );
3324 be_entry_release_r( op, e );
3325 attrs_free( ne.e_attrs );
3326 slap_mods_free( modlist, 1 );
3327 /* mods is NULL if there are no changes */
3329 SlapReply rs2 = { REP_RESULT };
3330 struct berval dn = op->o_req_dn;
3331 struct berval ndn = op->o_req_ndn;
3332 op->o_tag = LDAP_REQ_MODIFY;
3333 op->orm_modlist = mods;
3334 op->o_req_dn = rs->sr_entry->e_name;
3335 op->o_req_ndn = rs->sr_entry->e_nname;
3336 op->o_callback = &cb;
3337 op->o_bd->be_modify( op, &rs2 );
3338 rs->sr_err = rs2.sr_err;
3339 rs_assert_done( &rs2 );
3340 slap_mods_free( mods, 1 );
3342 op->o_req_ndn = ndn;
3346 /* Add DN to list */
3347 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3349 if ( ri->ri_tail ) {
3350 ri->ri_tail->next = dnl;
3355 op->o_callback = ocb;
3361 refresh_purge( Operation *op, SlapReply *rs )
3363 if ( rs->sr_type == REP_SEARCH ) {
3364 refresh_info *ri = op->o_callback->sc_private;
3368 /* Did the entry exist on the remote? */
3369 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
3370 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
3371 dnlist *dnext = (*dn)->next;
3372 op->o_tmpfree( *dn, op->o_tmpmemctx );
3378 /* No, so put it on the list to delete */
3381 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3382 dnl->next = ri->ri_dels;
3384 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
3385 /* If ours is the only queryId, delete entry */
3386 dnl->delete = ( a->a_numvals == 1 );
3393 refresh_query( Operation *op, CachedQuery *query, slap_overinst *on )
3395 SlapReply rs = {REP_RESULT};
3396 slap_callback cb = { 0 };
3397 refresh_info ri = { 0 };
3398 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
3399 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3400 Filter filter = {LDAP_FILTER_EQUALITY};
3401 AttributeName attrs[ 2 ] = {{{ 0 }}};
3405 ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
3407 ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
3409 cb.sc_response = refresh_merge;
3410 cb.sc_private = &ri;
3413 ri.ri_be = op->o_bd;
3416 op->o_tag = LDAP_REQ_SEARCH;
3417 op->o_protocol = LDAP_VERSION3;
3418 op->o_callback = &cb;
3419 op->o_do_not_cache = 1;
3421 op->o_req_dn = query->qbase->base;
3422 op->o_req_ndn = query->qbase->base;
3423 op->ors_scope = query->scope;
3424 op->ors_deref = LDAP_DEREF_NEVER;
3425 op->ors_slimit = SLAP_NO_LIMIT;
3426 op->ors_tlimit = SLAP_NO_LIMIT;
3427 op->ors_limit = NULL;
3428 op->ors_filter = query->filter;
3429 filter2bv_x( op, query->filter, &op->ors_filterstr );
3430 op->ors_attrs = query->qtemp->t_attrs.attrs;
3431 op->ors_attrsonly = 0;
3433 op->o_bd = on->on_info->oi_origdb;
3434 rc = op->o_bd->be_search( op, &rs );
3436 op->o_bd = ri.ri_be;
3440 /* Get the DNs of all entries matching this query */
3441 cb.sc_response = refresh_purge;
3443 op->o_bd = ri.ri_be;
3444 op->o_req_dn = op->o_bd->be_suffix[0];
3445 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3446 op->ors_scope = LDAP_SCOPE_SUBTREE;
3447 op->ors_deref = LDAP_DEREF_NEVER;
3448 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
3449 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
3450 filter.f_ava = &ava;
3451 filter.f_av_desc = ad_queryId;
3452 filter.f_av_value = query->q_uuid;
3453 attrs[ 0 ].an_desc = ad_queryId;
3454 attrs[ 0 ].an_name = ad_queryId->ad_cname;
3455 op->ors_attrs = attrs;
3456 op->ors_attrsonly = 0;
3457 rs_reinit( &rs, REP_RESULT );
3458 rc = op->o_bd->be_search( op, &rs );
3459 if ( rc ) goto leave;
3461 while (( dn = ri.ri_dels )) {
3462 op->o_req_dn = dn->dn;
3463 op->o_req_ndn = dn->dn;
3464 rs_reinit( &rs, REP_RESULT );
3466 op->o_tag = LDAP_REQ_DELETE;
3467 op->o_bd->be_delete( op, &rs );
3470 struct berval vals[2];
3472 vals[0] = query->q_uuid;
3473 BER_BVZERO( &vals[1] );
3474 mod.sml_op = LDAP_MOD_DELETE;
3476 mod.sml_desc = ad_queryId;
3477 mod.sml_type = ad_queryId->ad_cname;
3478 mod.sml_values = vals;
3479 mod.sml_nvalues = NULL;
3480 mod.sml_numvals = 1;
3481 mod.sml_next = NULL;
3483 op->o_tag = LDAP_REQ_MODIFY;
3484 op->orm_modlist = &mod;
3485 op->o_bd->be_modify( op, &rs );
3487 ri.ri_dels = dn->next;
3488 op->o_tmpfree( dn, op->o_tmpmemctx );
3492 /* reset our local heap, we're done with it */
3493 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
3502 struct re_s *rtask = arg;
3503 slap_overinst *on = rtask->arg;
3504 cache_manager *cm = on->on_bi.bi_private;
3505 query_manager *qm = cm->qm;
3506 Connection conn = {0};
3507 OperationBuffer opbuf;
3510 CachedQuery *query, *qprev;
3511 int return_val, pause = PCACHE_CC_PAUSED;
3512 QueryTemplate *templ;
3514 /* Don't expire anything when we're offline */
3515 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
3516 pause = PCACHE_CC_OFFLINE;
3520 connection_fake_init( &conn, &opbuf, ctx );
3524 op->o_dn = cm->db.be_rootdn;
3525 op->o_ndn = cm->db.be_rootndn;
3529 for (templ = qm->templates; templ; templ=templ->qmnext) {
3531 if ( !templ->query_last ) continue;
3533 op->o_time = slap_get_time();
3534 if ( !templ->ttr ) {
3536 if ( templ->negttl && templ->negttl < ttl )
3537 ttl = templ->negttl;
3538 if ( templ->limitttl && templ->limitttl < ttl )
3539 ttl = templ->limitttl;
3540 /* The oldest timestamp that needs expiration checking */
3544 for ( query=templ->query_last; query; query=qprev ) {
3545 qprev = query->prev;
3546 if ( query->refresh_time && query->refresh_time < op->o_time ) {
3547 /* A refresh will extend the expiry if the query has been
3548 * referenced, but not if it's unreferenced. If the
3549 * expiration has been hit, then skip the refresh since
3550 * we're just going to discard the result anyway.
3552 if ( query->refcnt )
3553 query->expiry_time = op->o_time + templ->ttl;
3554 if ( query->expiry_time > op->o_time ) {
3555 refresh_query( op, query, on );
3560 if (query->expiry_time < op->o_time) {
3562 Debug( pcache_debug, "Lock CR index = %p\n",
3563 (void *) templ, 0, 0 );
3564 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
3565 if ( query == templ->query_last ) {
3567 remove_from_template(query, templ);
3568 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
3569 (void *) templ, templ->no_of_queries, 0 );
3570 Debug( pcache_debug, "Unlock CR index = %p\n",
3571 (void *) templ, 0, 0 );
3574 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3577 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
3578 remove_query(qm, query);
3579 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
3580 if ( BER_BVISNULL( &query->q_uuid ))
3583 return_val = remove_query_data(op, &query->q_uuid);
3584 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3586 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3587 cm->cur_entries -= return_val;
3588 cm->num_cached_queries--;
3589 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3590 cm->num_cached_queries, 0, 0 );
3591 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3592 Debug( pcache_debug,
3593 "STALE QUERY REMOVED, CACHE ="
3595 cm->cur_entries, 0, 0 );
3596 ldap_pvt_thread_rdwr_wlock( &query->rwlock );
3597 if ( query->bind_refcnt-- ) {
3602 ldap_pvt_thread_rdwr_wunlock( &query->rwlock );
3603 if ( rem ) free_query(query);
3604 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3605 } else if ( !templ->ttr && query->expiry_time > ttl ) {
3606 /* We don't need to check for refreshes, and this
3607 * query's expiry is too new, and all subsequent queries
3608 * will be newer yet. So stop looking.
3610 * If we have refreshes, then we always have to walk the
3611 * entire query list.
3619 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3620 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3621 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3623 /* If there were no queries, defer processing for a while */
3624 if ( cm->cc_paused != pause )
3625 cm->cc_paused = pause;
3626 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3628 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3633 #define MAX_ATTR_SETS 500
3646 static ConfigDriver pc_cf_gen;
3647 static ConfigLDAPadd pc_ldadd;
3648 static ConfigCfAdd pc_cfadd;
3650 static ConfigTable pccfg[] = {
3651 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3653 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3654 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3655 "DESC 'Proxy Cache basic parameters' "
3656 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3657 { "pcacheAttrset", "index> <attributes...",
3658 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3659 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3660 "DESC 'A set of attributes to cache' "
3661 "EQUALITY caseIgnoreMatch "
3662 "SYNTAX OMsDirectoryString )", NULL, NULL },
3663 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3665 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3666 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3667 "DESC 'Filter template, attrset, cache TTL, "
3668 "optional negative TTL, optional sizelimit TTL, "
3670 "EQUALITY caseIgnoreMatch "
3671 "SYNTAX OMsDirectoryString )", NULL, NULL },
3672 { "pcachePosition", "head|tail(default)",
3673 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3674 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3675 "DESC 'Response callback position in overlay stack' "
3676 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3677 { "pcacheMaxQueries", "queries",
3678 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3679 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3680 "DESC 'Maximum number of queries to cache' "
3681 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
3682 { "pcachePersist", "TRUE|FALSE",
3683 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3684 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3685 "DESC 'Save cached queries for hot restart' "
3686 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3687 { "pcacheValidate", "TRUE|FALSE",
3688 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3689 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3690 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3691 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3692 { "pcacheOffline", "TRUE|FALSE",
3693 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3694 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3695 "DESC 'Set cache to offline mode and disable expiration' "
3696 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3697 { "pcacheBind", "filter> <attrset-index> <TTR> <scope> <base",
3698 6, 6, 0, ARG_MAGIC|PC_BIND, pc_cf_gen,
3699 "( OLcfgOvAt:2.9 NAME 'olcPcacheBind' "
3700 "DESC 'Parameters for caching Binds' "
3701 "EQUALITY caseIgnoreMatch "
3702 "SYNTAX OMsDirectoryString )", NULL, NULL },
3703 { "pcache-", "private database args",
3704 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3707 /* Legacy keywords */
3708 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3710 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3712 { "proxyattrset", "index> <attributes...",
3713 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3715 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3716 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3718 { "response-callback", "head|tail(default)",
3719 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3721 { "proxyCacheQueries", "queries",
3722 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3724 { "proxySaveQueries", "TRUE|FALSE",
3725 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3727 { "proxyCheckCacheability", "TRUE|FALSE",
3728 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3731 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3734 static ConfigOCs pcocs[] = {
3735 { "( OLcfgOvOc:2.1 "
3736 "NAME 'olcPcacheConfig' "
3737 "DESC 'ProxyCache configuration' "
3738 "SUP olcOverlayConfig "
3739 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3740 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3741 "olcPcacheValidate $ olcPcacheOffline $ olcPcacheBind ) )",
3742 Cft_Overlay, pccfg, NULL, pc_cfadd },
3743 { "( OLcfgOvOc:2.2 "
3744 "NAME 'olcPcacheDatabase' "
3745 "DESC 'Cache database configuration' "
3746 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3750 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3753 pc_ldadd_cleanup( ConfigArgs *c )
3755 slap_overinst *on = c->ca_private;
3756 return pcache_db_open2( on, &c->reply );
3760 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3765 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3766 p->ce_bi->bi_cf_ocs != pcocs )
3767 return LDAP_CONSTRAINT_VIOLATION;
3769 on = (slap_overinst *)p->ce_bi;
3770 cm = on->on_bi.bi_private;
3772 /* Defer open if this is an LDAPadd */
3773 if ( CONFIG_ONLINE_ADD( ca ))
3774 ca->cleanup = pc_ldadd_cleanup;
3776 cm->defer_db_open = 0;
3777 ca->ca_private = on;
3778 return LDAP_SUCCESS;
3782 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3784 CfEntryInfo *pe = p->e_private;
3785 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3786 cache_manager *cm = on->on_bi.bi_private;
3789 /* FIXME: should not hardcode "olcDatabase" here */
3790 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3791 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3792 0, cm->db.bd_info->bi_type );
3793 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3796 bv.bv_val = ca->cr_msg;
3798 cm->defer_db_open = 0;
3800 /* We can only create this entry if the database is table-driven
3802 if ( cm->db.bd_info->bi_cf_ocs )
3803 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3810 pc_cf_gen( ConfigArgs *c )
3812 slap_overinst *on = (slap_overinst *)c->bi;
3813 cache_manager* cm = on->on_bi.bi_private;
3814 query_manager* qm = cm->qm;
3815 QueryTemplate* temp;
3816 AttributeName* attr_name;
3817 AttributeName* attrarray;
3818 const char* text=NULL;
3823 if ( c->op == SLAP_CONFIG_EMIT ) {
3827 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3828 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3829 cm->num_entries_limit, cm->cc_period );
3830 bv.bv_val = c->cr_msg;
3831 value_add_one( &c->rvalue_vals, &bv );
3834 for (i=0; i<cm->numattrsets; i++) {
3835 if ( !qm->attr_sets[i].count ) continue;
3837 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3839 /* count the attr length */
3840 for ( attr_name = qm->attr_sets[i].attrs;
3841 attr_name->an_name.bv_val; attr_name++ )
3843 bv.bv_len += attr_name->an_name.bv_len + 1;
3844 if ( attr_name->an_desc &&
3845 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3846 bv.bv_len += STRLENOF("undef:");
3850 bv.bv_val = ch_malloc( bv.bv_len+1 );
3851 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3852 for ( attr_name = qm->attr_sets[i].attrs;
3853 attr_name->an_name.bv_val; attr_name++ ) {
3855 if ( attr_name->an_desc &&
3856 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3857 ptr = lutil_strcopy( ptr, "undef:" );
3859 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3861 ber_bvarray_add( &c->rvalue_vals, &bv );
3863 if ( !c->rvalue_vals )
3867 for (temp=qm->templates; temp; temp=temp->qmnext) {
3868 /* HEADS-UP: always print all;
3869 * if optional == 0, ignore */
3870 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3871 " %d %ld %ld %ld %ld",
3872 temp->attr_set_index,
3877 bv.bv_len += temp->querystr.bv_len + 2;
3878 bv.bv_val = ch_malloc( bv.bv_len+1 );
3881 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3883 strcpy( ptr, c->cr_msg );
3884 ber_bvarray_add( &c->rvalue_vals, &bv );
3886 if ( !c->rvalue_vals )
3890 for (temp=qm->templates; temp; temp=temp->qmnext) {
3891 if ( !temp->bindttr ) continue;
3892 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3894 temp->attr_set_index,
3896 ldap_pvt_scope2str( temp->bindscope ));
3897 bv.bv_len += temp->bindbase.bv_len + temp->bindftemp.bv_len + 4;
3898 bv.bv_val = ch_malloc( bv.bv_len + 1 );
3901 ptr = lutil_strcopy( ptr, temp->bindftemp.bv_val );
3903 ptr = lutil_strcopy( ptr, c->cr_msg );
3905 ptr = lutil_strcopy( ptr, temp->bindbase.bv_val );
3908 ber_bvarray_add( &c->rvalue_vals, &bv );
3910 if ( !c->rvalue_vals )
3914 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3915 BER_BVSTR( &bv, "head" );
3917 BER_BVSTR( &bv, "tail" );
3919 value_add_one( &c->rvalue_vals, &bv );
3922 c->value_int = cm->max_queries;
3925 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3929 } else if ( c->op == LDAP_MOD_DELETE ) {
3932 case PC_ATTR: /* FIXME */
3937 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3938 /* If there were cached queries when we went offline,
3939 * restart the checker now.
3941 if ( cm->num_cached_queries ) {
3942 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3944 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3945 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3955 if ( cm->numattrsets > 0 ) {
3956 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive already provided" );
3957 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3961 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3962 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3964 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3967 if ( cm->numattrsets <= 0 ) {
3968 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3969 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3972 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3973 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3974 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3978 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3979 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3980 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3984 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3985 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3987 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3990 if ( cm->max_entries <= 0 ) {
3991 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3992 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
3996 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
3997 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
3999 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4002 if ( cm->num_entries_limit <= 0 ) {
4003 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
4004 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4007 if ( cm->num_entries_limit > cm->max_entries ) {
4008 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
4009 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4013 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4014 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
4016 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4020 cm->cc_period = (time_t)t;
4021 Debug( pcache_debug,
4022 "Total # of attribute sets to be cached = %d.\n",
4023 cm->numattrsets, 0, 0 );
4024 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
4025 sizeof( struct attr_set ) );
4028 if ( cm->numattrsets == 0 ) {
4029 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4030 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4033 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
4034 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
4036 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4040 if ( num < 0 || num >= cm->numattrsets ) {
4041 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
4042 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4043 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4046 qm->attr_sets[num].flags |= PC_CONFIGURED;
4047 if ( c->argc == 2 ) {
4049 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4050 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
4051 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4054 } else if ( c->argc == 3 ) {
4055 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4056 qm->attr_sets[num].count = 1;
4057 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4058 sizeof( AttributeName ) );
4059 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4062 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4063 qm->attr_sets[num].count = 1;
4064 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4065 sizeof( AttributeName ) );
4066 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4069 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
4072 /* else: fallthru */
4074 } else if ( c->argc == 4 ) {
4075 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
4076 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
4078 qm->attr_sets[num].count = 2;
4079 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
4080 sizeof( AttributeName ) );
4081 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4082 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4085 /* else: fallthru */
4088 if ( c->argc > 2 ) {
4089 int all_user = 0, all_op = 0;
4091 qm->attr_sets[num].count = c->argc - 2;
4092 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
4093 sizeof( AttributeName ) );
4094 attr_name = qm->attr_sets[num].attrs;
4095 for ( i = 2; i < c->argc; i++ ) {
4096 attr_name->an_desc = NULL;
4097 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
4098 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4099 "invalid attr #%d \"%s\" in attrlist",
4100 i - 2, c->argv[i] );
4101 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4102 ch_free( qm->attr_sets[num].attrs );
4103 qm->attr_sets[num].attrs = NULL;
4104 qm->attr_sets[num].count = 0;
4107 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4109 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
4110 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4112 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4114 if ( strncasecmp( c->argv[i], "undef:", STRLENOF("undef:") ) == 0 ) {
4116 ber_str2bv( c->argv[i] + STRLENOF("undef:"), 0, 0, &bv );
4117 attr_name->an_desc = slap_bv2tmp_ad( &bv, NULL );
4119 } else if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
4120 strcpy( c->cr_msg, text );
4121 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4122 ch_free( qm->attr_sets[num].attrs );
4123 qm->attr_sets[num].attrs = NULL;
4124 qm->attr_sets[num].count = 0;
4127 attr_name->an_name = attr_name->an_desc->ad_cname;
4129 attr_name->an_oc = NULL;
4130 attr_name->an_flags = 0;
4131 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
4132 qm->attr_sets[num].flags |= PC_GOT_OC;
4134 BER_BVZERO( &attr_name->an_name );
4137 /* warn if list contains both "*" and "+" */
4138 if ( i > 4 && all_user && all_op ) {
4139 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4140 "warning: attribute list contains \"*\" and \"+\"" );
4141 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4146 if ( cm->numattrsets == 0 ) {
4147 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4148 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4151 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4152 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
4154 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4158 if ( i < 0 || i >= cm->numattrsets ||
4159 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4160 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
4161 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4162 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4166 AttributeName *attrs;
4168 cnt = template_attrs( c->argv[1], &qm->attr_sets[i], &attrs, &text );
4170 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4172 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4175 temp = ch_calloc( 1, sizeof( QueryTemplate ));
4176 temp->qmnext = qm->templates;
4177 qm->templates = temp;
4178 temp->t_attrs.attrs = attrs;
4179 temp->t_attrs.count = cnt;
4181 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
4182 temp->query = temp->query_last = NULL;
4183 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4184 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4185 "unable to parse template ttl=\"%s\"",
4187 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4189 ch_free( temp->t_attrs.attrs );
4193 temp->ttl = (time_t)t;
4194 temp->negttl = (time_t)0;
4195 temp->limitttl = (time_t)0;
4196 temp->ttr = (time_t)0;
4197 switch ( c->argc ) {
4199 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
4200 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4201 "unable to parse template ttr=\"%s\"",
4203 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4206 temp->ttr = (time_t)t;
4210 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4211 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4212 "unable to parse template sizelimit ttl=\"%s\"",
4214 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4217 temp->limitttl = (time_t)t;
4221 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
4222 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4223 "unable to parse template negative ttl=\"%s\"",
4225 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4228 temp->negttl = (time_t)t;
4232 temp->no_of_queries = 0;
4234 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
4235 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
4236 Debug( pcache_debug, " query template: %s\n",
4237 temp->querystr.bv_val, 0, 0 );
4238 temp->attr_set_index = i;
4239 qm->attr_sets[i].flags |= PC_REFERENCED;
4240 temp->qtnext = qm->attr_sets[i].templates;
4241 qm->attr_sets[i].templates = temp;
4242 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
4243 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
4244 for ( i=0; attrarray[i].an_name.bv_val; i++ )
4245 Debug( pcache_debug, "\t%s\n",
4246 attrarray[i].an_name.bv_val, 0, 0 );
4250 if ( !qm->templates ) {
4251 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcacheTemplate\" directive not provided yet" );
4252 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4255 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4256 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse Bind index #=\"%s\"",
4258 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4262 if ( i < 0 || i >= cm->numattrsets ||
4263 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4264 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind index %d invalid (%s%d)",
4265 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4266 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4269 { struct berval bv, tempbv;
4270 AttributeDescription **descs;
4272 ber_str2bv( c->argv[1], 0, 0, &bv );
4273 ndescs = ftemp_attrs( &bv, &tempbv, &descs, &text );
4275 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4277 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4280 for ( temp = qm->templates; temp; temp=temp->qmnext ) {
4281 if ( temp->attr_set_index == i && bvmatch( &tempbv,
4285 ch_free( tempbv.bv_val );
4288 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind template %s %d invalid",
4290 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4293 ber_dupbv( &temp->bindftemp, &bv );
4294 temp->bindfattrs = descs;
4295 temp->bindnattrs = ndescs;
4297 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4298 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4299 "unable to parse bind ttr=\"%s\"",
4301 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4303 ch_free( temp->bindfattrs );
4304 temp->bindfattrs = NULL;
4305 ch_free( temp->bindftemp.bv_val );
4306 BER_BVZERO( &temp->bindftemp );
4309 num = ldap_pvt_str2scope( c->argv[4] );
4311 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4312 "unable to parse bind scope=\"%s\"",
4314 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4318 struct berval dn, ndn;
4319 ber_str2bv( c->argv[5], 0, 0, &dn );
4320 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
4322 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4323 "invalid bind baseDN=\"%s\"",
4325 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4328 if ( temp->bindbase.bv_val )
4329 ch_free( temp->bindbase.bv_val );
4330 temp->bindbase = ndn;
4333 /* convert the template into dummy filter */
4335 char *eq = temp->bindftemp.bv_val, *e2;
4338 while ((eq = strchr(eq, '=' ))) {
4343 bv.bv_len = temp->bindftemp.bv_len + i;
4344 bv.bv_val = ch_malloc( bv.bv_len + 1 );
4345 for ( e2 = bv.bv_val, eq = temp->bindftemp.bv_val;
4356 f = str2filter( bv.bv_val );
4358 ch_free( bv.bv_val );
4359 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4360 "unable to parse bindfilter=\"%s\"", bv.bv_val );
4361 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4362 ch_free( temp->bindbase.bv_val );
4363 BER_BVZERO( &temp->bindbase );
4366 if ( temp->bindfilter )
4367 filter_free( temp->bindfilter );
4368 if ( temp->bindfilterstr.bv_val )
4369 ch_free( temp->bindfilterstr.bv_val );
4370 temp->bindfilterstr = bv;
4371 temp->bindfilter = f;
4373 temp->bindttr = (time_t)t;
4374 temp->bindscope = num;
4375 cm->cache_binds = 1;
4379 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
4380 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
4382 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
4383 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4386 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
4387 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4392 if ( c->value_int <= 0 ) {
4393 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
4394 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4397 cm->max_queries = c->value_int;
4401 cm->cc_paused |= PCACHE_CC_OFFLINE;
4403 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
4406 if ( cm->db.be_private == NULL ) {
4407 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4408 "private database must be defined before setting database specific options" );
4409 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4413 if ( cm->db.bd_info->bi_cf_ocs ) {
4416 char *argv0 = c->argv[ 0 ];
4418 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4420 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
4422 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4423 "private database does not recognize specific option '%s'",
4425 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4429 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
4431 c->bi = c->be->bd_info;
4433 rc = config_add_vals( ct, c );
4437 c->table = c2.table;
4440 c->argv[ 0 ] = argv0;
4442 } else if ( cm->db.be_config != NULL ) {
4443 char *argv0 = c->argv[ 0 ];
4445 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4446 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
4447 c->argv[ 0 ] = argv0;
4450 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4451 "no means to set private database specific options" );
4452 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4457 rc = SLAP_CONF_UNKNOWN;
4473 slap_overinst *on = (slap_overinst *)be->bd_info;
4474 cache_manager* cm = on->on_bi.bi_private;
4476 /* Something for the cache database? */
4477 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
4478 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
4480 return SLAP_CONF_UNKNOWN;
4488 slap_overinst *on = (slap_overinst *)be->bd_info;
4492 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
4493 on->on_bi.bi_private = cm;
4495 qm = (query_manager*)ch_malloc(sizeof(query_manager));
4498 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
4499 cm->db.be_private = NULL;
4500 cm->db.bd_self = &cm->db;
4502 cm->numattrsets = 0;
4503 cm->num_entries_limit = 5;
4504 cm->num_cached_queries = 0;
4505 cm->max_entries = 0;
4506 cm->cur_entries = 0;
4507 cm->max_queries = 10000;
4508 cm->save_queries = 0;
4509 cm->check_cacheability = 0;
4510 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4511 cm->defer_db_open = 1;
4512 cm->cache_binds = 0;
4513 cm->cc_period = 1000;
4516 #ifdef PCACHE_MONITOR
4517 cm->monitor_cb = NULL;
4518 #endif /* PCACHE_MONITOR */
4520 qm->attr_sets = NULL;
4521 qm->templates = NULL;
4523 qm->lru_bottom = NULL;
4525 qm->qcfunc = query_containment;
4526 qm->crfunc = cache_replacement;
4527 qm->addfunc = add_query;
4528 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
4530 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
4532 #ifndef PCACHE_MONITOR
4534 #else /* PCACHE_MONITOR */
4535 return pcache_monitor_db_init( be );
4536 #endif /* PCACHE_MONITOR */
4540 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
4542 assert( op->o_tag == LDAP_REQ_SEARCH );
4544 if ( rs->sr_type == REP_SEARCH ) {
4547 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
4551 assert( a->a_nvals != NULL );
4553 valsp = op->o_callback->sc_private;
4554 assert( *valsp == NULL );
4556 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
4564 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
4566 assert( op->o_tag == LDAP_REQ_SEARCH );
4568 if ( rs->sr_type == REP_SEARCH ) {
4569 int *countp = (int *)op->o_callback->sc_private;
4582 cache_manager *cm = on->on_bi.bi_private;
4583 query_manager* qm = cm->qm;
4586 rc = backend_startup_one( &cm->db, cr );
4588 cm->defer_db_open = 0;
4591 /* There is no runqueue in TOOL mode */
4592 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
4593 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4594 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
4595 consistency_check, on,
4596 "pcache_consistency", cm->db.be_suffix[0].bv_val );
4597 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4599 /* Cached database must have the rootdn */
4600 if ( BER_BVISNULL( &cm->db.be_rootndn )
4601 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
4603 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
4604 "underlying database of type \"%s\"\n"
4605 " serving naming context \"%s\"\n"
4606 " has no \"rootdn\", required by \"pcache\".\n",
4607 on->on_info->oi_orig->bi_type,
4608 cm->db.be_suffix[0].bv_val, 0 );
4612 if ( cm->save_queries ) {
4613 void *thrctx = ldap_pvt_thread_pool_context();
4614 Connection conn = { 0 };
4615 OperationBuffer opbuf;
4617 slap_callback cb = { 0 };
4618 SlapReply rs = { REP_RESULT };
4619 BerVarray vals = NULL;
4620 Filter f = { 0 }, f2 = { 0 };
4621 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
4622 AttributeName attrs[ 2 ] = {{{ 0 }}};
4624 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4629 op->o_tag = LDAP_REQ_SEARCH;
4630 op->o_protocol = LDAP_VERSION3;
4631 cb.sc_response = pcache_cachedquery_open_cb;
4632 cb.sc_private = &vals;
4633 op->o_callback = &cb;
4634 op->o_time = slap_get_time();
4635 op->o_do_not_cache = 1;
4636 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4638 op->o_dn = cm->db.be_rootdn;
4639 op->o_ndn = cm->db.be_rootndn;
4640 op->o_req_dn = cm->db.be_suffix[ 0 ];
4641 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
4643 op->ors_scope = LDAP_SCOPE_BASE;
4644 op->ors_deref = LDAP_DEREF_NEVER;
4646 op->ors_tlimit = SLAP_NO_LIMIT;
4647 op->ors_limit = NULL;
4648 ber_str2bv( "(pcacheQueryURL=*)", 0, 0, &op->ors_filterstr );
4649 f.f_choice = LDAP_FILTER_PRESENT;
4650 f.f_desc = ad_cachedQueryURL;
4651 op->ors_filter = &f;
4652 attrs[ 0 ].an_desc = ad_cachedQueryURL;
4653 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
4654 op->ors_attrs = attrs;
4655 op->ors_attrsonly = 0;
4657 rc = op->o_bd->be_search( op, &rs );
4658 if ( rc == LDAP_SUCCESS && vals != NULL ) {
4661 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
4662 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
4663 cm->num_cached_queries++;
4667 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4670 /* count cached entries */
4671 f.f_choice = LDAP_FILTER_NOT;
4673 f2.f_choice = LDAP_FILTER_EQUALITY;
4675 f2.f_av_desc = slap_schema.si_ad_objectClass;
4676 BER_BVSTR( &f2.f_av_value, "glue" );
4677 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
4679 op->ors_slimit = SLAP_NO_LIMIT;
4680 op->ors_scope = LDAP_SCOPE_SUBTREE;
4681 op->ors_attrs = slap_anlist_no_attrs;
4683 rs_reinit( &rs, REP_RESULT );
4684 op->o_callback->sc_response = pcache_cachedquery_count_cb;
4685 op->o_callback->sc_private = &rs.sr_nentries;
4687 rc = op->o_bd->be_search( op, &rs );
4689 cm->cur_entries = rs.sr_nentries;
4703 slap_overinst *on = (slap_overinst *)be->bd_info;
4704 cache_manager *cm = on->on_bi.bi_private;
4705 query_manager* qm = cm->qm;
4706 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
4708 /* check attr sets */
4709 for ( i = 0; i < cm->numattrsets; i++) {
4710 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
4711 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
4712 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
4716 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
4720 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
4721 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
4726 if ( ncf || rf || nrf ) {
4727 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
4728 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
4729 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
4736 /* need to inherit something from the original database... */
4737 cm->db.be_def_limit = be->be_def_limit;
4738 cm->db.be_limits = be->be_limits;
4739 cm->db.be_acl = be->be_acl;
4740 cm->db.be_dfltaccess = be->be_dfltaccess;
4742 if ( SLAP_DBMONITORING( be ) ) {
4743 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
4746 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
4749 if ( !cm->defer_db_open ) {
4750 rc = pcache_db_open2( on, cr );
4753 #ifdef PCACHE_MONITOR
4754 if ( rc == LDAP_SUCCESS ) {
4755 rc = pcache_monitor_db_open( be );
4757 #endif /* PCACHE_MONITOR */
4763 pcache_free_qbase( void *v )
4769 tavl_free( qb->scopes[i], NULL );
4779 slap_overinst *on = (slap_overinst *)be->bd_info;
4780 cache_manager *cm = on->on_bi.bi_private;
4781 query_manager *qm = cm->qm;
4785 /* stop the thread ... */
4787 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4788 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4789 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4791 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4792 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4795 if ( cm->save_queries ) {
4797 BerVarray vals = NULL;
4800 Connection conn = { 0 };
4801 OperationBuffer opbuf;
4803 slap_callback cb = { 0 };
4805 SlapReply rs = { REP_RESULT };
4806 Modifications mod = {{ 0 }};
4808 thrctx = ldap_pvt_thread_pool_context();
4810 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4813 mod.sml_numvals = 0;
4814 if ( qm->templates != NULL ) {
4815 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4816 for ( qc = tm->query; qc; qc = qc->next ) {
4819 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4820 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4828 op->o_dn = cm->db.be_rootdn;
4829 op->o_ndn = cm->db.be_rootndn;
4831 op->o_tag = LDAP_REQ_MODIFY;
4832 op->o_protocol = LDAP_VERSION3;
4833 cb.sc_response = slap_null_cb;
4834 op->o_callback = &cb;
4835 op->o_time = slap_get_time();
4836 op->o_do_not_cache = 1;
4837 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4839 op->o_req_dn = op->o_bd->be_suffix[0];
4840 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4842 mod.sml_op = LDAP_MOD_REPLACE;
4844 mod.sml_desc = ad_cachedQueryURL;
4845 mod.sml_type = ad_cachedQueryURL->ad_cname;
4846 mod.sml_values = vals;
4847 mod.sml_nvalues = NULL;
4848 mod.sml_next = NULL;
4849 Debug( pcache_debug,
4850 "%sSETTING CACHED QUERY URLS\n",
4851 vals == NULL ? "RE" : "", 0, 0 );
4853 op->orm_modlist = &mod;
4855 op->o_bd->be_modify( op, &rs );
4857 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4860 /* cleanup stuff inherited from the original database... */
4861 cm->db.be_limits = NULL;
4862 cm->db.be_acl = NULL;
4865 if ( cm->db.bd_info->bi_db_close ) {
4866 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4868 while ( (tm = qm->templates) != NULL ) {
4869 CachedQuery *qc, *qn;
4870 qm->templates = tm->qmnext;
4871 for ( qc = tm->query; qc; qc = qn ) {
4875 avl_free( tm->qbase, pcache_free_qbase );
4876 free( tm->querystr.bv_val );
4877 free( tm->bindfattrs );
4878 free( tm->bindftemp.bv_val );
4879 free( tm->bindfilterstr.bv_val );
4880 free( tm->bindbase.bv_val );
4881 filter_free( tm->bindfilter );
4882 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4883 free( tm->t_attrs.attrs );
4887 for ( i = 0; i < cm->numattrsets; i++ ) {
4890 /* Account of LDAP_NO_ATTRS */
4891 if ( !qm->attr_sets[i].count ) continue;
4893 for ( j = 0; !BER_BVISNULL( &qm->attr_sets[i].attrs[j].an_name ); j++ ) {
4894 if ( qm->attr_sets[i].attrs[j].an_desc &&
4895 ( qm->attr_sets[i].attrs[j].an_desc->ad_flags &
4896 SLAP_DESC_TEMPORARY ) ) {
4897 slap_sl_mfuncs.bmf_free( qm->attr_sets[i].attrs[j].an_desc, NULL );
4900 free( qm->attr_sets[i].attrs );
4902 free( qm->attr_sets );
4903 qm->attr_sets = NULL;
4905 #ifdef PCACHE_MONITOR
4906 if ( rc == LDAP_SUCCESS ) {
4907 rc = pcache_monitor_db_close( be );
4909 #endif /* PCACHE_MONITOR */
4920 slap_overinst *on = (slap_overinst *)be->bd_info;
4921 cache_manager *cm = on->on_bi.bi_private;
4922 query_manager *qm = cm->qm;
4924 if ( cm->db.be_private != NULL ) {
4925 backend_stopdown_one( &cm->db );
4928 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4929 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4933 #ifdef PCACHE_MONITOR
4934 pcache_monitor_db_destroy( be );
4935 #endif /* PCACHE_MONITOR */
4940 #ifdef PCACHE_CONTROL_PRIVDB
4942 Control ::= SEQUENCE {
4943 controlType LDAPOID,
4944 criticality BOOLEAN DEFAULT FALSE,
4945 controlValue OCTET STRING OPTIONAL }
4947 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4949 * criticality must be TRUE; controlValue must be absent.
4957 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4958 rs->sr_text = "privateDB control specified multiple times";
4959 return LDAP_PROTOCOL_ERROR;
4962 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4963 rs->sr_text = "privateDB control value not absent";
4964 return LDAP_PROTOCOL_ERROR;
4967 if ( !ctrl->ldctl_iscritical ) {
4968 rs->sr_text = "privateDB control criticality required";
4969 return LDAP_PROTOCOL_ERROR;
4972 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4974 return LDAP_SUCCESS;
4977 static char *extops[] = {
4978 LDAP_EXOP_MODIFY_PASSWD,
4981 #endif /* PCACHE_CONTROL_PRIVDB */
4983 static struct berval pcache_exop_MODIFY_PASSWD = BER_BVC( LDAP_EXOP_MODIFY_PASSWD );
4984 #ifdef PCACHE_EXOP_QUERY_DELETE
4985 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4987 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4988 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4989 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
4992 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
4993 requestName [0] LDAPOID,
4994 requestValue [1] OCTET STRING OPTIONAL }
4996 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
4998 requestValue ::= SEQUENCE { CHOICE {
5000 entryDN [1] LDAPDN },
5001 queryID [2] OCTET STRING (SIZE(16))
5002 -- constrained to UUID }
5004 * Either baseDN or entryDN must be present, to allow database selection.
5006 * 1. if baseDN and queryID are present, then the query corresponding
5007 * to queryID is deleted;
5008 * 2. if baseDN is present and queryID is absent, then all queries
5010 * 3. if entryDN is present and queryID is absent, then all queries
5011 * corresponding to the queryID values present in entryDN are deleted;
5012 * 4. if entryDN and queryID are present, then all queries
5013 * corresponding to the queryID values present in entryDN are deleted,
5014 * but only if the value of queryID is contained in the entry;
5016 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
5017 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
5018 * or by removing the database files.
5020 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
5021 COMPONENTS OF LDAPResult,
5022 responseName [10] LDAPOID OPTIONAL,
5023 responseValue [11] OCTET STRING OPTIONAL }
5025 * responseName and responseValue must be absent.
5029 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
5030 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
5031 * - if ndn != NULL, it is set to the normalized DN in the request
5032 * corresponding to either the baseDN or the entryDN, according
5033 * to *tagp; memory is malloc'ed on the Operation's slab, and must
5034 * be freed by the caller.
5035 * - if uuid != NULL, it is set to point to the normalized UUID;
5036 * memory is malloc'ed on the Operation's slab, and must
5037 * be freed by the caller.
5040 pcache_parse_query_delete(
5044 struct berval *uuid,
5048 int rc = LDAP_SUCCESS;
5051 BerElementBuffer berbuf;
5052 BerElement *ber = (BerElement *)&berbuf;
5053 struct berval reqdata = BER_BVNULL;
5065 if ( in == NULL || in->bv_len == 0 ) {
5066 *text = "empty request data field in queryDelete exop";
5067 return LDAP_PROTOCOL_ERROR;
5070 ber_dupbv_x( &reqdata, in, ctx );
5072 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
5073 ber_init2( ber, &reqdata, 0 );
5075 tag = ber_scanf( ber, "{" /*}*/ );
5077 if ( tag == LBER_ERROR ) {
5078 Debug( LDAP_DEBUG_TRACE,
5079 "pcache_parse_query_delete: decoding error.\n",
5081 goto decoding_error;
5084 tag = ber_peek_tag( ber, &len );
5085 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
5086 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
5090 if ( ndn != NULL ) {
5093 tag = ber_scanf( ber, "m", &dn );
5094 if ( tag == LBER_ERROR ) {
5095 Debug( LDAP_DEBUG_TRACE,
5096 "pcache_parse_query_delete: DN parse failed.\n",
5098 goto decoding_error;
5101 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
5102 if ( rc != LDAP_SUCCESS ) {
5103 *text = "invalid DN in queryDelete exop request data";
5108 tag = ber_scanf( ber, "x" /* "m" */ );
5109 if ( tag == LBER_DEFAULT ) {
5110 goto decoding_error;
5114 tag = ber_peek_tag( ber, &len );
5117 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
5118 if ( uuid != NULL ) {
5120 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
5122 tag = ber_scanf( ber, "m", &bv );
5123 if ( tag == LBER_ERROR ) {
5124 Debug( LDAP_DEBUG_TRACE,
5125 "pcache_parse_query_delete: UUID parse failed.\n",
5127 goto decoding_error;
5130 if ( bv.bv_len != 16 ) {
5131 Debug( LDAP_DEBUG_TRACE,
5132 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5133 (unsigned long)bv.bv_len, 0, 0 );
5134 goto decoding_error;
5137 rc = lutil_uuidstr_from_normalized(
5138 bv.bv_val, bv.bv_len,
5139 uuidbuf, sizeof( uuidbuf ) );
5141 goto decoding_error;
5143 ber_str2bv( uuidbuf, rc, 1, uuid );
5147 tag = ber_skip_tag( ber, &len );
5148 if ( tag == LBER_DEFAULT ) {
5149 goto decoding_error;
5153 Debug( LDAP_DEBUG_TRACE,
5154 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5155 (unsigned long)len, 0, 0 );
5156 goto decoding_error;
5160 tag = ber_peek_tag( ber, &len );
5163 if ( tag != LBER_DEFAULT || len != 0 ) {
5165 Debug( LDAP_DEBUG_TRACE,
5166 "pcache_parse_query_delete: decoding error\n",
5168 rc = LDAP_PROTOCOL_ERROR;
5169 *text = "queryDelete data decoding error";
5172 if ( ndn && !BER_BVISNULL( ndn ) ) {
5173 slap_sl_free( ndn->bv_val, ctx );
5177 if ( uuid && !BER_BVISNULL( uuid ) ) {
5178 slap_sl_free( uuid->bv_val, ctx );
5183 if ( !BER_BVISNULL( &reqdata ) ) {
5184 ber_memfree_x( reqdata.bv_val, ctx );
5191 pcache_exop_query_delete(
5195 BackendDB *bd = op->o_bd;
5197 struct berval uuid = BER_BVNULL,
5199 char buf[ SLAP_TEXT_BUFLEN ];
5201 ber_tag_t tag = LBER_DEFAULT;
5203 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5207 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5208 &tag, &op->o_req_ndn, uuidp,
5209 &rs->sr_text, op->o_tmpmemctx );
5210 if ( rs->sr_err != LDAP_SUCCESS ) {
5214 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5215 assert( !BER_BVISNULL( &op->o_req_ndn ) );
5216 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
5218 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
5219 snprintf( &buf[ len ], sizeof( buf ) - len, " pcacheQueryId=\"%s\"", uuid.bv_val );
5222 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
5223 op->o_log_prefix, buf, 0 );
5225 op->o_req_dn = op->o_req_ndn;
5227 op->o_bd = select_backend( &op->o_req_ndn, 0 );
5228 if ( op->o_bd == NULL ) {
5229 send_ldap_error( op, rs, LDAP_NO_SUCH_OBJECT,
5230 "no global superior knowledge" );
5232 rs->sr_err = backend_check_restrictions( op, rs,
5233 (struct berval *)&pcache_exop_QUERY_DELETE );
5234 if ( rs->sr_err != LDAP_SUCCESS ) {
5238 if ( op->o_bd->be_extended == NULL ) {
5239 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
5240 "backend does not support extended operations" );
5244 op->o_bd->be_extended( op, rs );
5247 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
5248 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
5249 BER_BVZERO( &op->o_req_ndn );
5250 BER_BVZERO( &op->o_req_dn );
5253 if ( !BER_BVISNULL( &uuid ) ) {
5254 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5261 #endif /* PCACHE_EXOP_QUERY_DELETE */
5264 pcache_op_extended( Operation *op, SlapReply *rs )
5266 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5267 cache_manager *cm = on->on_bi.bi_private;
5269 #ifdef PCACHE_CONTROL_PRIVDB
5270 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
5271 return pcache_op_privdb( op, rs );
5273 #endif /* PCACHE_CONTROL_PRIVDB */
5275 #ifdef PCACHE_EXOP_QUERY_DELETE
5276 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
5277 struct berval uuid = BER_BVNULL;
5278 ber_tag_t tag = LBER_DEFAULT;
5280 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5281 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
5282 assert( rs->sr_err == LDAP_SUCCESS );
5284 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
5285 /* remove all queries related to the selected entry */
5286 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
5287 cm, &op->o_req_ndn, &uuid );
5289 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
5290 if ( !BER_BVISNULL( &uuid ) ) {
5291 /* remove the selected query */
5292 rs->sr_err = pcache_remove_query_from_cache( op,
5296 /* TODO: remove all queries */
5297 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
5298 rs->sr_text = "deletion of all queries not implemented";
5302 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5305 #endif /* PCACHE_EXOP_QUERY_DELETE */
5307 /* We only care if we're configured for Bind caching */
5308 if ( bvmatch( &op->ore_reqoid, &pcache_exop_MODIFY_PASSWD ) &&
5310 /* See if the local entry exists and has a password.
5311 * It's too much work to find the matching query, so
5312 * we just see if there's a hashed password to update.
5314 Operation op2 = *op;
5320 op2.o_dn = op->o_bd->be_rootdn;
5321 op2.o_ndn = op->o_bd->be_rootndn;
5322 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL,
5323 slap_schema.si_ad_userPassword, 0, &e );
5324 if ( rc == LDAP_SUCCESS && e ) {
5325 /* See if a recognized password is hashed here */
5326 Attribute *a = attr_find( e->e_attrs,
5327 slap_schema.si_ad_userPassword );
5328 if ( a && a->a_vals[0].bv_val[0] == '{' &&
5329 lutil_passwd_scheme( a->a_vals[0].bv_val )) {
5332 be_entry_release_r( &op2, e );
5336 rc = overlay_op_walk( op, rs, op_extended, on->on_info,
5338 if ( rc == LDAP_SUCCESS ) {
5339 req_pwdexop_s *qpw = &op->oq_pwdexop;
5341 /* We don't care if it succeeds or not */
5342 pc_setpw( &op2, &qpw->rs_new, cm );
5347 return SLAP_CB_CONTINUE;
5351 pcache_entry_release( Operation *op, Entry *e, int rw )
5353 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5354 cache_manager *cm = on->on_bi.bi_private;
5355 BackendDB *db = op->o_bd;
5359 rc = be_entry_release_rw( op, e, rw );
5364 #ifdef PCACHE_MONITOR
5367 pcache_monitor_update(
5373 cache_manager *cm = (cache_manager *) priv;
5374 query_manager *qm = cm->qm;
5377 BerVarray vals = NULL;
5379 attr_delete( &e->e_attrs, ad_cachedQueryURL );
5380 if ( ( SLAP_OPATTRS( rs->sr_attr_flags ) || ad_inlist( ad_cachedQueryURL, rs->sr_attrs ) )
5381 && qm->templates != NULL )
5385 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
5386 for ( qc = tm->query; qc; qc = qc->next ) {
5389 if ( query2url( op, qc, &bv, 1 ) == 0 ) {
5390 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
5396 if ( vals != NULL ) {
5397 attr_merge_normalize( e, ad_cachedQueryURL, vals, NULL );
5398 ber_bvarray_free_x( vals, op->o_tmpmemctx );
5404 char buf[ SLAP_TEXT_BUFLEN ];
5407 /* number of cached queries */
5408 a = attr_find( e->e_attrs, ad_numQueries );
5409 assert( a != NULL );
5412 bv.bv_len = snprintf( buf, sizeof( buf ), "%lu", cm->num_cached_queries );
5414 if ( a->a_nvals != a->a_vals ) {
5415 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5417 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5419 /* number of cached entries */
5420 a = attr_find( e->e_attrs, ad_numEntries );
5421 assert( a != NULL );
5424 bv.bv_len = snprintf( buf, sizeof( buf ), "%d", cm->cur_entries );
5426 if ( a->a_nvals != a->a_vals ) {
5427 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5429 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5432 return SLAP_CB_CONTINUE;
5436 pcache_monitor_free(
5440 struct berval values[ 2 ];
5441 Modification mod = { 0 };
5444 char textbuf[ SLAP_TEXT_BUFLEN ];
5448 /* NOTE: if slap_shutdown != 0, priv might have already been freed */
5451 /* Remove objectClass */
5452 mod.sm_op = LDAP_MOD_DELETE;
5453 mod.sm_desc = slap_schema.si_ad_objectClass;
5454 mod.sm_values = values;
5456 values[ 0 ] = oc_olmPCache->soc_cname;
5457 BER_BVZERO( &values[ 1 ] );
5459 rc = modify_delete_values( e, &mod, 1, &text,
5460 textbuf, sizeof( textbuf ) );
5461 /* don't care too much about return code... */
5464 mod.sm_values = NULL;
5465 mod.sm_desc = ad_cachedQueryURL;
5467 rc = modify_delete_values( e, &mod, 1, &text,
5468 textbuf, sizeof( textbuf ) );
5469 /* don't care too much about return code... */
5472 mod.sm_values = NULL;
5473 mod.sm_desc = ad_numQueries;
5475 rc = modify_delete_values( e, &mod, 1, &text,
5476 textbuf, sizeof( textbuf ) );
5477 /* don't care too much about return code... */
5480 mod.sm_values = NULL;
5481 mod.sm_desc = ad_numEntries;
5483 rc = modify_delete_values( e, &mod, 1, &text,
5484 textbuf, sizeof( textbuf ) );
5485 /* don't care too much about return code... */
5487 return SLAP_CB_CONTINUE;
5491 * call from within pcache_initialize()
5494 pcache_monitor_initialize( void )
5496 static int pcache_monitor_initialized = 0;
5498 if ( backend_info( "monitor" ) == NULL ) {
5502 if ( pcache_monitor_initialized++ ) {
5510 pcache_monitor_db_init( BackendDB *be )
5512 if ( pcache_monitor_initialize() == LDAP_SUCCESS ) {
5513 SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_MONITORING;
5520 pcache_monitor_db_open( BackendDB *be )
5522 slap_overinst *on = (slap_overinst *)be->bd_info;
5523 cache_manager *cm = on->on_bi.bi_private;
5524 Attribute *a, *next;
5525 monitor_callback_t *cb = NULL;
5528 monitor_extra_t *mbe;
5530 if ( !SLAP_DBMONITORING( be ) ) {
5534 mi = backend_info( "monitor" );
5535 if ( !mi || !mi->bi_extra ) {
5536 SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
5541 /* don't bother if monitor is not configured */
5542 if ( !mbe->is_configured() ) {
5543 static int warning = 0;
5545 if ( warning++ == 0 ) {
5546 Debug( LDAP_DEBUG_ANY, "pcache_monitor_db_open: "
5547 "monitoring disabled; "
5548 "configure monitor database to enable\n",
5555 /* alloc as many as required (plus 1 for objectClass) */
5556 a = attrs_alloc( 1 + 2 );
5562 a->a_desc = slap_schema.si_ad_objectClass;
5563 attr_valadd( a, &oc_olmPCache->soc_cname, NULL, 1 );
5567 struct berval bv = BER_BVC( "0" );
5569 next->a_desc = ad_numQueries;
5570 attr_valadd( next, &bv, NULL, 1 );
5571 next = next->a_next;
5573 next->a_desc = ad_numEntries;
5574 attr_valadd( next, &bv, NULL, 1 );
5575 next = next->a_next;
5578 cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
5579 cb->mc_update = pcache_monitor_update;
5580 cb->mc_free = pcache_monitor_free;
5581 cb->mc_private = (void *)cm;
5583 /* make sure the database is registered; then add monitor attributes */
5584 BER_BVZERO( &cm->monitor_ndn );
5585 rc = mbe->register_overlay( be, on, &cm->monitor_ndn );
5587 rc = mbe->register_entry_attrs( &cm->monitor_ndn, a, cb,
5604 /* store for cleanup */
5605 cm->monitor_cb = (void *)cb;
5607 /* we don't need to keep track of the attributes, because
5608 * bdb_monitor_free() takes care of everything */
5617 pcache_monitor_db_close( BackendDB *be )
5619 slap_overinst *on = (slap_overinst *)be->bd_info;
5620 cache_manager *cm = on->on_bi.bi_private;
5622 if ( cm->monitor_cb != NULL ) {
5623 BackendInfo *mi = backend_info( "monitor" );
5624 monitor_extra_t *mbe;
5626 if ( mi && &mi->bi_extra ) {
5628 mbe->unregister_entry_callback( &cm->monitor_ndn,
5629 (monitor_callback_t *)cm->monitor_cb,
5638 pcache_monitor_db_destroy( BackendDB *be )
5643 #endif /* PCACHE_MONITOR */
5645 static slap_overinst pcache;
5647 static char *obsolete_names[] = {
5652 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5654 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
5659 struct berval debugbv = BER_BVC("pcache");
5663 code = slap_loglevel_get( &debugbv, &pcache_debug );
5668 #ifdef PCACHE_CONTROL_PRIVDB
5669 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
5670 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
5671 parse_privdb_ctrl, &privDB_cid );
5672 if ( code != LDAP_SUCCESS ) {
5673 Debug( LDAP_DEBUG_ANY,
5674 "pcache_initialize: failed to register control %s (%d)\n",
5675 PCACHE_CONTROL_PRIVDB, code, 0 );
5678 #endif /* PCACHE_CONTROL_PRIVDB */
5680 #ifdef PCACHE_EXOP_QUERY_DELETE
5681 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
5682 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
5684 if ( code != LDAP_SUCCESS ) {
5685 Debug( LDAP_DEBUG_ANY,
5686 "pcache_initialize: unable to register queryDelete exop: %d.\n",
5690 #endif /* PCACHE_EXOP_QUERY_DELETE */
5692 argv[ 0 ] = "back-bdb/back-hdb monitor";
5697 for ( i = 0; s_oid[ i ].name; i++ ) {
5699 argv[ 1 ] = s_oid[ i ].name;
5700 argv[ 2 ] = s_oid[ i ].oid;
5702 if ( parse_oidm( &c, 0, NULL ) != 0 ) {
5703 Debug( LDAP_DEBUG_ANY, "pcache_initialize: "
5704 "unable to add objectIdentifier \"%s=%s\"\n",
5705 s_oid[ i ].name, s_oid[ i ].oid, 0 );
5710 for ( i = 0; s_ad[i].desc != NULL; i++ ) {
5711 code = register_at( s_ad[i].desc, s_ad[i].adp, 0 );
5713 Debug( LDAP_DEBUG_ANY,
5714 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
5717 (*s_ad[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
5720 for ( i = 0; s_oc[i].desc != NULL; i++ ) {
5721 code = register_oc( s_oc[i].desc, s_oc[i].ocp, 0 );
5723 Debug( LDAP_DEBUG_ANY,
5724 "pcache_initialize: register_oc #%d failed\n", i, 0, 0 );
5727 (*s_oc[i].ocp)->soc_flags |= SLAP_OC_HIDE;
5730 pcache.on_bi.bi_type = "pcache";
5731 pcache.on_bi.bi_obsolete_names = obsolete_names;
5732 pcache.on_bi.bi_db_init = pcache_db_init;
5733 pcache.on_bi.bi_db_config = pcache_db_config;
5734 pcache.on_bi.bi_db_open = pcache_db_open;
5735 pcache.on_bi.bi_db_close = pcache_db_close;
5736 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
5738 pcache.on_bi.bi_op_search = pcache_op_search;
5739 pcache.on_bi.bi_op_bind = pcache_op_bind;
5740 #ifdef PCACHE_CONTROL_PRIVDB
5741 pcache.on_bi.bi_op_compare = pcache_op_privdb;
5742 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
5743 pcache.on_bi.bi_op_modify = pcache_op_privdb;
5744 pcache.on_bi.bi_op_add = pcache_op_privdb;
5745 pcache.on_bi.bi_op_delete = pcache_op_privdb;
5746 #endif /* PCACHE_CONTROL_PRIVDB */
5747 pcache.on_bi.bi_extended = pcache_op_extended;
5749 pcache.on_bi.bi_entry_release_rw = pcache_entry_release;
5750 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
5752 pcache.on_bi.bi_cf_ocs = pcocs;
5754 code = config_register_schema( pccfg, pcocs );
5755 if ( code ) return code;
5757 return overlay_register( &pcache );
5760 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5761 int init_module(int argc, char *argv[]) {
5762 return pcache_initialize();
5766 #endif /* defined(SLAPD_OVER_PROXYCACHE) */