2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2015 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, '=' );
466 AC_MEMCPY( t1, p1, i );
470 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
474 i = slap_bv2ad( &bv, &ad, text );
480 if ( *p2 == '<' || *p2 == '>' ) p2++;
481 if ( p2[1] != ')' ) {
483 while ( *p2 != ')' ) p2++;
488 descs = (AttributeDescription **)ch_realloc(descs,
489 (attr_cnt + 2)*sizeof(AttributeDescription *));
491 descs[attr_cnt++] = ad;
496 descs[attr_cnt] = NULL;
498 template->bv_val = temp2;
499 template->bv_len = t1 - temp2;
504 template_attrs( char *template, struct attr_set *set, AttributeName **ret,
515 AttributeDescription *ad;
516 AttributeName *attrs;
522 attrs = ch_calloc( set->count + 1, sizeof(AttributeName) );
523 for ( i=0; i < set->count; i++ )
524 attrs[i] = set->attrs[i];
526 alluser = an_find( attrs, slap_bv_all_user_attrs );
527 allop = an_find( attrs, slap_bv_all_operational_attrs );
530 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' ) p1++;
531 p2 = strchr( p1, '=' );
534 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
538 i = slap_bv2ad( &bv, &ad, text );
545 if ( ad == slap_schema.si_ad_objectClass )
548 if ( is_at_operational(ad->ad_type)) {
552 } else if ( alluser ) {
555 if ( !ad_inlist( ad, attrs )) {
556 attrs = (AttributeName *)ch_realloc(attrs,
557 (attr_cnt + 2)*sizeof(AttributeName));
559 attrs[attr_cnt].an_desc = ad;
560 attrs[attr_cnt].an_name = ad->ad_cname;
561 attrs[attr_cnt].an_oc = NULL;
562 attrs[attr_cnt].an_flags = 0;
563 BER_BVZERO( &attrs[attr_cnt+1].an_name );
571 *text = "couldn't parse template";
575 if ( !got_oc && !( set->flags & PC_GOT_OC )) {
576 attrs = (AttributeName *)ch_realloc(attrs,
577 (attr_cnt + 2)*sizeof(AttributeName));
579 ad = slap_schema.si_ad_objectClass;
580 attrs[attr_cnt].an_desc = ad;
581 attrs[attr_cnt].an_name = ad->ad_cname;
582 attrs[attr_cnt].an_oc = NULL;
583 attrs[attr_cnt].an_flags = 0;
584 BER_BVZERO( &attrs[attr_cnt+1].an_name );
592 * Turn an URL representing a formerly cached query into a cached query,
593 * and try to cache it
604 LDAPURLDesc *lud = NULL;
606 tempstr = BER_BVNULL,
611 unsigned long answerable_cnt;
614 #define GOT_UUID 0x1U
615 #define GOT_ATTRSET 0x2U
616 #define GOT_EXPIRY 0x4U
617 #define GOT_ANSWERABLE 0x8U
618 #define GOT_REFRESH 0x10U
619 #define GOT_ALL (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
622 rc = ldap_url_parse( url, &lud );
623 if ( rc != LDAP_URL_SUCCESS ) {
627 /* non-allowed fields */
628 if ( lud->lud_host != NULL ) {
633 if ( lud->lud_attrs != NULL ) {
639 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
644 /* required fields */
645 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
650 switch ( lud->lud_scope ) {
651 case LDAP_SCOPE_BASE:
652 case LDAP_SCOPE_ONELEVEL:
653 case LDAP_SCOPE_SUBTREE:
654 case LDAP_SCOPE_SUBORDINATE:
662 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
667 if ( lud->lud_exts == NULL ) {
672 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
673 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
674 struct berval tmpUUID;
675 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
677 if ( got & GOT_UUID ) {
682 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
683 if ( !BER_BVISEMPTY( &tmpUUID ) ) {
684 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
685 if ( rc != LDAP_SUCCESS ) {
691 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
692 if ( got & GOT_ATTRSET ) {
697 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
703 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
706 if ( got & GOT_EXPIRY ) {
711 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
715 expiry_time = (time_t)l;
718 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
719 if ( got & GOT_ANSWERABLE ) {
724 rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
728 got |= GOT_ANSWERABLE;
730 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
733 if ( got & GOT_REFRESH ) {
738 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
742 refresh_time = (time_t)l;
751 if ( got != GOT_ALL ) {
756 if ( !(got & GOT_REFRESH ))
759 /* ignore expired queries */
760 if ( expiry_time <= slap_get_time()) {
763 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
765 (void)remove_query_data( &op2, &uuid );
770 ber_str2bv( lud->lud_dn, 0, 0, &base );
771 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
772 if ( rc != LDAP_SUCCESS ) {
775 query.scope = lud->lud_scope;
776 query.filter = str2filter( lud->lud_filter );
777 if ( query.filter == NULL ) {
782 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
784 if ( filter2template( op, query.filter, &tempstr ) ) {
785 ch_free( tempstr.bv_val );
790 /* check for query containment */
791 qt = qm->attr_sets[attrset].templates;
792 for ( ; qt; qt = qt->qtnext ) {
793 /* find if template i can potentially answer tempstr */
794 if ( bvmatch( &qt->querystr, &tempstr ) ) {
804 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
806 cq->expiry_time = expiry_time;
807 cq->refresh_time = refresh_time;
809 cq->answerable_cnt = answerable_cnt;
812 /* it's now into cq->filter */
822 if ( query.filter != NULL ) filter_free( query.filter );
823 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
824 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
825 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
826 if ( lud != NULL ) ldap_free_urldesc( lud );
831 /* Return 1 for an added entry, else 0 */
837 struct berval* query_uuid )
840 Modifications* modlist = NULL;
841 const char* text = NULL;
843 char textbuf[SLAP_TEXT_BUFLEN];
844 size_t textlen = sizeof(textbuf);
846 SlapReply sreply = {REP_RESULT};
848 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
855 /* add queryId attribute */
856 attr_merge_one( e, ad_queryId, query_uuid, NULL );
858 /* append the attribute list from the fetched entry */
859 e->e_attrs->a_next = attr;
861 op->o_tag = LDAP_REQ_ADD;
862 op->o_protocol = LDAP_VERSION3;
863 op->o_callback = &cb;
864 op->o_time = slap_get_time();
865 op->o_do_not_cache = 1;
868 op->o_req_dn = e->e_name;
869 op->o_req_ndn = e->e_nname;
870 rc = op->o_bd->be_add( op, &sreply );
872 if ( rc != LDAP_SUCCESS ) {
873 if ( rc == LDAP_ALREADY_EXISTS ) {
874 rs_reinit( &sreply, REP_RESULT );
875 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
876 modlist->sml_op = LDAP_MOD_ADD;
877 op->o_tag = LDAP_REQ_MODIFY;
878 op->orm_modlist = modlist;
879 op->o_managedsait = SLAP_CONTROL_CRITICAL;
880 op->o_bd->be_modify( op, &sreply );
881 slap_mods_free( modlist, 1 );
882 } else if ( rc == LDAP_REFERRAL ||
883 rc == LDAP_NO_SUCH_OBJECT ) {
884 syncrepl_add_glue( op, e );
893 if ( op->ora_e == e )
901 /* Length-ordered sort on normalized DNs */
902 static int pcache_dn_cmp( const void *v1, const void *v2 )
904 const Qbase *q1 = v1, *q2 = v2;
906 int rc = q1->base.bv_len - q2->base.bv_len;
908 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
912 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
915 dif = bv1->bv_len - bv2->bv_len;
917 if ( dif > 0 ) len -= dif;
918 len = memcmp( bv1->bv_val, bv2->bv_val, len );
924 /* compare the current value in each filter */
925 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
927 int rc, weight1, weight2;
929 switch( f1->f_choice ) {
930 case LDAP_FILTER_AND:
934 case LDAP_FILTER_PRESENT:
937 case LDAP_FILTER_EQUALITY:
945 switch( f2->f_choice ) {
946 case LDAP_FILTER_AND:
950 case LDAP_FILTER_PRESENT:
953 case LDAP_FILTER_EQUALITY:
961 rc = weight1 - weight2;
965 rc = pcache_filter_cmp( f1->f_and, f2->f_and );
970 rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
973 if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
975 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
976 if ( !BER_BVISNULL( &f2->f_sub_initial )) {
977 rc = lex_bvcmp( &f1->f_sub_initial,
978 &f2->f_sub_initial );
982 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
986 if ( f1->f_sub_any ) {
987 if ( f2->f_sub_any ) {
988 rc = lex_bvcmp( f1->f_sub_any,
993 } else if ( f2->f_sub_any ) {
997 if ( !BER_BVISNULL( &f1->f_sub_final )) {
998 if ( !BER_BVISNULL( &f2->f_sub_final )) {
999 rc = lex_bvcmp( &f1->f_sub_final,
1004 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
1008 rc = lex_bvcmp( &f1->f_mr_value,
1022 rc = pcache_filter_cmp( f1, f2 );
1032 /* compare filters in each query */
1033 static int pcache_query_cmp( const void *v1, const void *v2 )
1035 const CachedQuery *q1 = v1, *q2 =v2;
1036 return pcache_filter_cmp( q1->filter, q2->filter );
1039 /* add query on top of LRU list */
1041 add_query_on_top (query_manager* qm, CachedQuery* qc)
1043 CachedQuery* top = qm->lru_top;
1050 qm->lru_bottom = qc;
1054 Debug( pcache_debug, "Base of added query = %s\n",
1055 qc->qbase->base.bv_val, 0, 0 );
1058 /* remove_query from LRU list */
1061 remove_query (query_manager* qm, CachedQuery* qc)
1070 down = qc->lru_down;
1076 qm->lru_bottom = up;
1082 up->lru_down = down;
1084 qc->lru_up = qc->lru_down = NULL;
1087 /* find and remove string2 from string1
1088 * from start if position = 1,
1089 * from end if position = 3,
1090 * from anywhere if position = 2
1091 * string1 is overwritten if position = 2.
1095 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
1099 if ( !ber2->bv_val )
1101 if ( !ber1->bv_val )
1104 switch( position ) {
1106 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
1107 ber2->bv_val, ber2->bv_len )) {
1109 ber1->bv_val += ber2->bv_len;
1110 ber1->bv_len -= ber2->bv_len;
1115 ber1->bv_val[ber1->bv_len] = '\0';
1116 temp = strstr( ber1->bv_val, ber2->bv_val );
1118 strcpy( temp, temp+ber2->bv_len );
1119 ber1->bv_len -= ber2->bv_len;
1125 if ( ber1->bv_len >= ber2->bv_len &&
1126 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
1129 ber1->bv_len -= ber2->bv_len;
1137 static struct berval*
1138 merge_init_final(Operation *op, struct berval* init, struct berval* any,
1139 struct berval* final)
1141 struct berval* merged, *temp;
1142 int i, any_count, count;
1144 for (any_count=0; any && any[any_count].bv_val; any_count++)
1154 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
1159 ber_dupbv_x( temp, init, op->o_tmpmemctx );
1163 for (i=0; i<any_count; i++) {
1164 ber_dupbv_x( temp, any, op->o_tmpmemctx );
1169 ber_dupbv_x( temp, final, op->o_tmpmemctx );
1176 /* Each element in stored must be found in incoming. Incoming is overwritten.
1179 strings_containment(struct berval* stored, struct berval* incoming)
1181 struct berval* element;
1185 for ( element=stored; element->bv_val != NULL; element++ ) {
1186 for (j = k; incoming[j].bv_val != NULL; j++) {
1187 if (find_and_remove(&(incoming[j]), element, 2)) {
1204 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
1208 struct berval init_incoming;
1209 struct berval final_incoming;
1210 struct berval *remaining_incoming = NULL;
1212 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
1213 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
1216 init_incoming = incoming->f_sub_initial;
1217 final_incoming = incoming->f_sub_final;
1219 if (find_and_remove(&init_incoming,
1220 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
1221 &(stored->f_sub_final), 3))
1223 if (stored->f_sub_any == NULL) {
1227 remaining_incoming = merge_init_final(op, &init_incoming,
1228 incoming->f_sub_any, &final_incoming);
1229 rc = strings_containment(stored->f_sub_any, remaining_incoming);
1230 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
1237 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
1239 struct berval incoming_val[2];
1242 incoming_val[1] = incoming->f_av_value;
1244 if (find_and_remove(incoming_val+1,
1245 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
1246 &(stored->f_sub_final), 3)) {
1247 if (stored->f_sub_any == NULL){
1251 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
1252 BER_BVZERO( incoming_val+1 );
1253 rc = strings_containment(stored->f_sub_any, incoming_val);
1254 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1261 filter_first( Filter *f )
1263 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1268 typedef struct fstack {
1269 struct fstack *fs_next;
1274 static CachedQuery *
1275 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
1279 MatchingRule* mrule = NULL;
1280 int res=0, eqpass= 0;
1283 CachedQuery cq, *qc;
1284 fstack *stack = NULL, *fsp;
1289 /* substring matches sort to the end, and we just have to
1290 * walk the entire list.
1292 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1293 ptr = tavl_end( root, 1 );
1294 dir = TAVL_DIR_LEFT;
1296 ptr = tavl_find3( root, &cq, pcache_query_cmp, &ret );
1297 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1306 /* an incoming substr query can only be satisfied by a cached
1309 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1310 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1313 /* an incoming eq query can be satisfied by a cached eq or substr
1316 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1317 if ( eqpass == 0 ) {
1318 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1319 nextpass: eqpass = 1;
1320 ptr = tavl_end( root, 1 );
1321 dir = TAVL_DIR_LEFT;
1325 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1331 switch (fs->f_choice) {
1332 case LDAP_FILTER_EQUALITY:
1333 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1334 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1338 case LDAP_FILTER_GE:
1339 case LDAP_FILTER_LE:
1340 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1347 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1348 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1349 &(fi->f_ava->aa_value),
1350 &(fs->f_ava->aa_value), &text);
1351 if (rc != LDAP_SUCCESS) {
1354 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1357 switch (fs->f_choice) {
1358 case LDAP_FILTER_OR:
1359 case LDAP_FILTER_AND:
1361 /* save our stack position */
1362 fsp = op->o_tmpalloc(sizeof(fstack), op->o_tmpmemctx);
1363 fsp->fs_next = stack;
1364 fsp->fs_fs = fs->f_next;
1365 fsp->fs_fi = fi->f_next;
1372 case LDAP_FILTER_SUBSTRINGS:
1373 /* check if the equality query can be
1374 * answered with cached substring query */
1375 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1376 && substr_containment_equality( op,
1379 /* check if the substring query can be
1380 * answered with cached substring query */
1381 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1382 ) && substr_containment_substr( op,
1388 case LDAP_FILTER_PRESENT:
1393 case LDAP_FILTER_EQUALITY:
1399 case LDAP_FILTER_GE:
1400 if (mrule && ret >= 0)
1405 case LDAP_FILTER_LE:
1406 if (mrule && ret <= 0)
1411 case LDAP_FILTER_NOT:
1417 if (!fs && !fi && stack) {
1420 stack = fsp->fs_next;
1423 op->o_tmpfree(fsp, op->o_tmpmemctx);
1425 } while((res) && (fi != NULL) && (fs != NULL));
1429 ptr = tavl_next( ptr, dir );
1434 /* check whether query is contained in any of
1435 * the cached queries in template
1437 static CachedQuery *
1438 query_containment(Operation *op, query_manager *qm,
1440 QueryTemplate *templa)
1443 int depth = 0, tscope;
1444 Qbase qbase, *qbptr = NULL;
1447 if (query->filter != NULL) {
1450 Debug( pcache_debug, "Lock QC index = %p\n",
1451 (void *) templa, 0, 0 );
1452 qbase.base = query->base;
1454 first = filter_first( query->filter );
1456 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1459 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1461 tscope = query->scope;
1462 /* Find a matching scope:
1463 * match at depth 0 OK
1466 * subord at depth > 0 OK
1467 * subtree at any depth OK
1469 * subtree or subord at any depth OK
1471 * subtree or subord at any depth OK
1473 * subord at depth > 0 OK
1474 * subtree at any depth OK
1476 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1477 switch ( query->scope ) {
1478 case LDAP_SCOPE_BASE:
1479 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1480 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1481 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1483 case LDAP_SCOPE_ONE:
1484 if ( tscope == LDAP_SCOPE_BASE )
1485 tscope = LDAP_SCOPE_ONE;
1486 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1487 if ( !depth ) break;
1488 if ( tscope < LDAP_SCOPE_SUBTREE )
1489 tscope = LDAP_SCOPE_SUBTREE;
1491 case LDAP_SCOPE_SUBTREE:
1492 if ( tscope < LDAP_SCOPE_SUBTREE )
1493 tscope = LDAP_SCOPE_SUBTREE;
1494 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1496 case LDAP_SCOPE_CHILDREN:
1497 if ( tscope < LDAP_SCOPE_SUBTREE )
1498 tscope = LDAP_SCOPE_SUBTREE;
1501 if ( !qbptr->scopes[tscope] ) continue;
1504 qc = find_filter( op, qbptr->scopes[tscope],
1505 query->filter, first );
1507 if ( qc->q_sizelimit ) {
1508 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1511 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1512 if (qm->lru_top != qc) {
1513 remove_query(qm, qc);
1514 add_query_on_top(qm, qc);
1516 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1521 if ( be_issuffix( op->o_bd, &qbase.base ))
1524 dnParent( &qbase.base, &pdn );
1529 Debug( pcache_debug,
1530 "Not answerable: Unlock QC index=%p\n",
1531 (void *) templa, 0, 0 );
1532 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1538 free_query (CachedQuery* qc)
1540 free(qc->q_uuid.bv_val);
1541 filter_free(qc->filter);
1542 ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1543 ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1544 memset(qc, 0, sizeof(*qc));
1549 /* Add query to query cache, the returned Query is locked for writing */
1550 static CachedQuery *
1555 QueryTemplate *templ,
1556 pc_caching_reason_t why,
1559 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1563 time_t ttl = 0, ttr = 0;
1566 new_cached_query->qtemp = templ;
1567 BER_BVZERO( &new_cached_query->q_uuid );
1568 new_cached_query->q_sizelimit = 0;
1570 now = slap_get_time();
1575 ttr = now + templ->ttr;
1579 ttl = templ->negttl;
1583 ttl = templ->limitttl;
1590 new_cached_query->expiry_time = now + ttl;
1591 new_cached_query->refresh_time = ttr;
1592 new_cached_query->bindref_time = 0;
1594 new_cached_query->bind_refcnt = 0;
1595 new_cached_query->answerable_cnt = 0;
1596 new_cached_query->refcnt = 1;
1597 ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1599 new_cached_query->lru_up = NULL;
1600 new_cached_query->lru_down = NULL;
1601 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1602 (long) new_cached_query->expiry_time,
1603 pc_caching_reason_str[ why ], 0 );
1605 new_cached_query->scope = query->scope;
1606 new_cached_query->filter = query->filter;
1607 new_cached_query->first = first = filter_first( query->filter );
1609 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1611 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1613 qb.base = query->base;
1615 /* Adding a query */
1616 Debug( pcache_debug, "Lock AQ index = %p\n",
1617 (void *) templ, 0, 0 );
1618 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1619 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1621 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1622 qbase->base.bv_len = qb.base.bv_len;
1623 qbase->base.bv_val = (char *)(qbase+1);
1624 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1625 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1626 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1628 new_cached_query->next = templ->query;
1629 new_cached_query->prev = NULL;
1630 new_cached_query->qbase = qbase;
1631 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1632 pcache_query_cmp, avl_dup_error );
1635 if (templ->query == NULL)
1636 templ->query_last = new_cached_query;
1638 templ->query->prev = new_cached_query;
1639 templ->query = new_cached_query;
1640 templ->no_of_queries++;
1642 ldap_pvt_thread_mutex_destroy(&new_cached_query->answerable_cnt_mutex);
1644 ldap_pvt_thread_rdwr_wunlock(&new_cached_query->rwlock);
1645 ldap_pvt_thread_rdwr_destroy( &new_cached_query->rwlock );
1646 ch_free( new_cached_query );
1647 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1648 query->filter, first );
1649 filter_free( query->filter );
1650 query->filter = NULL;
1652 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1653 (void *) templ, templ->no_of_queries, 0 );
1655 /* Adding on top of LRU list */
1657 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1658 add_query_on_top(qm, new_cached_query);
1659 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1661 Debug( pcache_debug, "Unlock AQ index = %p \n",
1662 (void *) templ, 0, 0 );
1663 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1665 return rc == 0 ? new_cached_query : NULL;
1669 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1671 if (!qc->prev && !qc->next) {
1672 template->query_last = template->query = NULL;
1673 } else if (qc->prev == NULL) {
1674 qc->next->prev = NULL;
1675 template->query = qc->next;
1676 } else if (qc->next == NULL) {
1677 qc->prev->next = NULL;
1678 template->query_last = qc->prev;
1680 qc->next->prev = qc->prev;
1681 qc->prev->next = qc->next;
1683 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1684 qc->qbase->queries--;
1685 if ( qc->qbase->queries == 0 ) {
1686 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1687 ch_free( qc->qbase );
1691 template->no_of_queries--;
1694 /* remove bottom query of LRU list from the query cache */
1696 * NOTE: slight change in functionality.
1698 * - if result->bv_val is NULL, the query at the bottom of the LRU
1700 * - otherwise, the query whose UUID is *result is removed
1701 * - if not found, result->bv_val is zeroed
1704 cache_replacement(query_manager* qm, struct berval *result)
1706 CachedQuery* bottom;
1707 QueryTemplate *temp;
1709 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1710 if ( BER_BVISNULL( result ) ) {
1711 bottom = qm->lru_bottom;
1714 Debug ( pcache_debug,
1715 "Cache replacement invoked without "
1716 "any query in LRU list\n", 0, 0, 0 );
1717 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1722 for ( bottom = qm->lru_bottom;
1724 bottom = bottom->lru_up )
1726 if ( bvmatch( result, &bottom->q_uuid ) ) {
1732 Debug ( pcache_debug,
1733 "Could not find query with uuid=\"%s\""
1734 "in LRU list\n", result->bv_val, 0, 0 );
1735 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1736 BER_BVZERO( result );
1741 temp = bottom->qtemp;
1742 remove_query(qm, bottom);
1743 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1745 *result = bottom->q_uuid;
1746 BER_BVZERO( &bottom->q_uuid );
1748 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1749 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1750 remove_from_template(bottom, temp);
1751 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1752 (void *) temp, temp->no_of_queries, 0 );
1753 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1754 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1759 struct query_info *next;
1771 struct query_info *qi;
1774 if ( rs->sr_type != REP_SEARCH ) return 0;
1776 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1777 if ( attr == NULL ) return 0;
1779 count = attr->a_numvals;
1780 assert( count > 0 );
1781 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1782 qi->next = op->o_callback->sc_private;
1783 op->o_callback->sc_private = qi;
1784 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1785 qi->del = ( count == 1 );
1793 struct berval *query_uuid )
1795 struct query_info *qi, *qnext;
1796 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
1797 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1798 Filter filter = {LDAP_FILTER_EQUALITY};
1799 SlapReply sreply = {REP_RESULT};
1800 slap_callback cb = { NULL, remove_func, NULL, NULL };
1803 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1804 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1805 filter.f_ava = &ava;
1806 filter.f_av_desc = ad_queryId;
1807 filter.f_av_value = *query_uuid;
1809 op->o_tag = LDAP_REQ_SEARCH;
1810 op->o_protocol = LDAP_VERSION3;
1811 op->o_callback = &cb;
1812 op->o_time = slap_get_time();
1813 op->o_do_not_cache = 1;
1815 op->o_req_dn = op->o_bd->be_suffix[0];
1816 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1817 op->ors_scope = LDAP_SCOPE_SUBTREE;
1818 op->ors_deref = LDAP_DEREF_NEVER;
1819 op->ors_slimit = SLAP_NO_LIMIT;
1820 op->ors_tlimit = SLAP_NO_LIMIT;
1821 op->ors_limit = NULL;
1822 op->ors_filter = &filter;
1823 op->ors_filterstr.bv_val = filter_str;
1824 op->ors_filterstr.bv_len = strlen(filter_str);
1825 op->ors_attrs = NULL;
1826 op->ors_attrsonly = 0;
1828 op->o_bd->be_search( op, &sreply );
1830 for ( qi=cb.sc_private; qi; qi=qnext ) {
1833 op->o_req_dn = qi->xdn;
1834 op->o_req_ndn = qi->xdn;
1835 rs_reinit( &sreply, REP_RESULT );
1838 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1839 query_uuid->bv_val, 0, 0 );
1841 op->o_tag = LDAP_REQ_DELETE;
1843 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1849 struct berval vals[2];
1851 vals[0] = *query_uuid;
1852 vals[1].bv_val = NULL;
1854 mod.sml_op = LDAP_MOD_DELETE;
1856 mod.sml_desc = ad_queryId;
1857 mod.sml_type = ad_queryId->ad_cname;
1858 mod.sml_values = vals;
1859 mod.sml_nvalues = NULL;
1860 mod.sml_numvals = 1;
1861 mod.sml_next = NULL;
1862 Debug( pcache_debug,
1863 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1864 query_uuid->bv_val, 0, 0 );
1866 op->orm_modlist = &mod;
1868 op->o_bd->be_modify( op, &sreply );
1870 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1871 op->o_tmpfree( qi, op->o_tmpmemctx );
1878 AttributeName* attrs,
1887 struct berval *fstr )
1889 AttributeDescription *ad;
1892 switch ( f->f_choice ) {
1893 case LDAP_FILTER_EQUALITY:
1895 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1896 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1897 assert( ret == len );
1898 fstr->bv_len += len;
1901 case LDAP_FILTER_GE:
1903 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1904 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1905 assert( ret == len );
1906 fstr->bv_len += len;
1909 case LDAP_FILTER_LE:
1911 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1912 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1913 assert( ret == len );
1914 fstr->bv_len += len;
1917 case LDAP_FILTER_APPROX:
1919 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1920 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1921 assert( ret == len );
1922 fstr->bv_len += len;
1925 case LDAP_FILTER_SUBSTRINGS:
1927 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1928 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1929 assert( ret == len );
1930 fstr->bv_len += len;
1933 case LDAP_FILTER_PRESENT:
1935 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1936 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1937 assert( ret == len );
1938 fstr->bv_len += len;
1941 case LDAP_FILTER_AND:
1942 case LDAP_FILTER_OR:
1943 case LDAP_FILTER_NOT: {
1945 fstr->bv_val[fstr->bv_len++] = '(';
1946 switch ( f->f_choice ) {
1947 case LDAP_FILTER_AND:
1948 fstr->bv_val[fstr->bv_len] = '&';
1950 case LDAP_FILTER_OR:
1951 fstr->bv_val[fstr->bv_len] = '|';
1953 case LDAP_FILTER_NOT:
1954 fstr->bv_val[fstr->bv_len] = '!';
1959 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1960 rc = filter2template( op, f, fstr );
1963 fstr->bv_val[fstr->bv_len++] = ')';
1964 fstr->bv_val[fstr->bv_len] = '\0';
1970 /* a filter should at least have room for "()",
1971 * an "=" and for a 1-char attr */
1972 strcpy( fstr->bv_val, "(?=)" );
1973 fstr->bv_len += STRLENOF("(?=)");
1980 #define BI_HASHED 0x01
1981 #define BI_DIDCB 0x02
1982 #define BI_LOOKUP 0x04
1986 typedef struct bindinfo {
1987 cache_manager *bi_cm;
1989 QueryTemplate *bi_templ;
1990 struct search_info *bi_si;
1992 slap_callback bi_cb;
1995 struct search_info {
1998 QueryTemplate *qtemp;
1999 AttributeName* save_attrs; /* original attributes, saved for response */
2000 int swap_saved_attrs;
2005 int slimit_exceeded;
2006 pc_caching_reason_t caching_reason;
2012 remove_query_and_data(
2015 struct berval *uuid )
2017 query_manager* qm = cm->qm;
2019 qm->crfunc( qm, uuid );
2020 if ( !BER_BVISNULL( uuid ) ) {
2023 Debug( pcache_debug,
2024 "Removing query UUID %s\n",
2025 uuid->bv_val, 0, 0 );
2026 return_val = remove_query_data( op, uuid );
2027 Debug( pcache_debug,
2028 "QUERY REMOVED, SIZE=%d\n",
2030 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
2031 cm->cur_entries -= return_val;
2032 cm->num_cached_queries--;
2033 Debug( pcache_debug,
2034 "STORED QUERIES = %lu\n",
2035 cm->num_cached_queries, 0, 0 );
2036 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
2037 Debug( pcache_debug,
2038 "QUERY REMOVED, CACHE ="
2040 cm->cur_entries, 0, 0 );
2045 * Callback used to fetch queryId values based on entryUUID;
2046 * used by pcache_remove_entries_from_cache()
2049 fetch_queryId_cb( Operation *op, SlapReply *rs )
2053 /* only care about searchEntry responses */
2054 if ( rs->sr_type != REP_SEARCH ) {
2058 /* allow only one response per entryUUID */
2059 if ( op->o_callback->sc_private != NULL ) {
2065 /* copy all queryId values into callback's private data */
2066 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2068 BerVarray vals = NULL;
2070 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
2071 op->o_callback->sc_private = (void *)vals;
2075 /* clear entry if required */
2076 rs_flush_entry( op, rs, (slap_overinst *) op->o_bd->bd_info );
2082 * Call that allows to remove a set of entries from the cache,
2083 * by forcing the removal of all the related queries.
2086 pcache_remove_entries_from_cache(
2089 BerVarray entryUUIDs )
2091 Connection conn = { 0 };
2092 OperationBuffer opbuf;
2094 slap_callback sc = { 0 };
2096 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
2097 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2098 AttributeName attrs[ 2 ] = {{{ 0 }}};
2102 void *thrctx = ldap_pvt_thread_pool_context();
2104 connection_fake_init( &conn, &opbuf, thrctx );
2112 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2113 op->ors_scope = LDAP_SCOPE_SUBTREE;
2114 op->ors_deref = LDAP_DEREF_NEVER;
2115 f.f_choice = LDAP_FILTER_EQUALITY;
2117 ava.aa_desc = slap_schema.si_ad_entryUUID;
2118 op->ors_filter = &f;
2120 op->ors_tlimit = SLAP_NO_LIMIT;
2121 op->ors_limit = NULL;
2122 attrs[ 0 ].an_desc = ad_queryId;
2123 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2124 op->ors_attrs = attrs;
2125 op->ors_attrsonly = 0;
2127 op->o_req_dn = cm->db.be_suffix[ 0 ];
2128 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2130 op->o_tag = LDAP_REQ_SEARCH;
2131 op->o_protocol = LDAP_VERSION3;
2132 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2134 op->o_dn = op->o_bd->be_rootdn;
2135 op->o_ndn = op->o_bd->be_rootndn;
2136 sc.sc_response = fetch_queryId_cb;
2137 op->o_callback = ≻
2139 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
2140 BerVarray vals = NULL;
2141 SlapReply rs = { REP_RESULT };
2143 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
2144 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
2145 op->ors_filterstr.bv_val = filtbuf;
2146 ava.aa_value = entryUUIDs[ s ];
2148 rc = op->o_bd->be_search( op, &rs );
2149 if ( rc != LDAP_SUCCESS ) {
2153 vals = (BerVarray)op->o_callback->sc_private;
2154 if ( vals != NULL ) {
2157 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2158 struct berval val = vals[ i ];
2160 remove_query_and_data( op, cm, &val );
2162 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2163 ch_free( val.bv_val );
2167 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2168 op->o_callback->sc_private = NULL;
2176 * Call that allows to remove a query from the cache.
2179 pcache_remove_query_from_cache(
2182 struct berval *queryid )
2184 Operation op2 = *op;
2188 /* remove the selected query */
2189 remove_query_and_data( &op2, cm, queryid );
2191 return LDAP_SUCCESS;
2195 * Call that allows to remove a set of queries related to an entry
2196 * from the cache; if queryid is not null, the entry must belong to
2197 * the query indicated by queryid.
2200 pcache_remove_entry_queries_from_cache(
2204 struct berval *queryid )
2206 Connection conn = { 0 };
2207 OperationBuffer opbuf;
2209 slap_callback sc = { 0 };
2210 SlapReply rs = { REP_RESULT };
2212 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
2213 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2214 AttributeName attrs[ 2 ] = {{{ 0 }}};
2217 BerVarray vals = NULL;
2220 void *thrctx = ldap_pvt_thread_pool_context();
2222 connection_fake_init( &conn, &opbuf, thrctx );
2230 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2231 op->ors_scope = LDAP_SCOPE_BASE;
2232 op->ors_deref = LDAP_DEREF_NEVER;
2233 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
2234 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
2235 f.f_choice = LDAP_FILTER_PRESENT;
2236 f.f_desc = slap_schema.si_ad_objectClass;
2239 op->ors_filterstr.bv_len = snprintf( filter_str,
2240 sizeof( filter_str ), "(%s=%s)",
2241 ad_queryId->ad_cname.bv_val, queryid->bv_val );
2242 f.f_choice = LDAP_FILTER_EQUALITY;
2244 f.f_av_desc = ad_queryId;
2245 f.f_av_value = *queryid;
2247 op->ors_filter = &f;
2249 op->ors_tlimit = SLAP_NO_LIMIT;
2250 op->ors_limit = NULL;
2251 attrs[ 0 ].an_desc = ad_queryId;
2252 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2253 op->ors_attrs = attrs;
2254 op->ors_attrsonly = 0;
2256 op->o_req_dn = *ndn;
2257 op->o_req_ndn = *ndn;
2259 op->o_tag = LDAP_REQ_SEARCH;
2260 op->o_protocol = LDAP_VERSION3;
2261 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2263 op->o_dn = op->o_bd->be_rootdn;
2264 op->o_ndn = op->o_bd->be_rootndn;
2265 sc.sc_response = fetch_queryId_cb;
2266 op->o_callback = ≻
2268 rc = op->o_bd->be_search( op, &rs );
2269 if ( rc != LDAP_SUCCESS ) {
2273 vals = (BerVarray)op->o_callback->sc_private;
2274 if ( vals != NULL ) {
2277 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2278 struct berval val = vals[ i ];
2280 remove_query_and_data( op, cm, &val );
2282 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2283 ch_free( val.bv_val );
2287 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2290 return LDAP_SUCCESS;
2296 struct berval *query_uuid )
2298 struct search_info *si = op->o_callback->sc_private;
2299 slap_overinst *on = si->on;
2300 cache_manager *cm = on->on_bi.bi_private;
2303 struct berval crp_uuid;
2304 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2306 Connection conn = {0};
2307 OperationBuffer opbuf;
2308 void *thrctx = ldap_pvt_thread_pool_context();
2310 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2311 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2313 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2314 op_tmp = &opbuf.ob_op;
2315 op_tmp->o_bd = &cm->db;
2316 op_tmp->o_dn = cm->db.be_rootdn;
2317 op_tmp->o_ndn = cm->db.be_rootndn;
2319 Debug( pcache_debug, "UUID for query being added = %s\n",
2322 for ( e=si->head; e; e=si->head ) {
2323 si->head = e->e_private;
2324 e->e_private = NULL;
2325 while ( cm->cur_entries > (cm->max_entries) ) {
2326 BER_BVZERO( &crp_uuid );
2327 remove_query_and_data( op_tmp, cm, &crp_uuid );
2330 return_val = merge_entry(op_tmp, e, 0, query_uuid);
2331 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2332 cm->cur_entries += return_val;
2333 Debug( pcache_debug,
2334 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2335 cm->cur_entries, 0, 0 );
2337 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2344 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2345 slap_callback *cb = op->o_callback;
2346 struct search_info *si = cb->sc_private;
2347 slap_overinst *on = si->on;
2348 cache_manager *cm = on->on_bi.bi_private;
2349 query_manager* qm = cm->qm;
2351 if ( rs->sr_type == REP_RESULT ||
2352 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2354 if ( si->swap_saved_attrs ) {
2355 rs->sr_attrs = si->save_attrs;
2356 op->ors_attrs = si->save_attrs;
2358 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) &&
2359 si->caching_reason == PC_IGNORE )
2361 filter_free( si->query.filter );
2363 /* duplicate query, free it */
2365 for (;si->head; si->head=e) {
2366 e = si->head->e_private;
2367 si->head->e_private = NULL;
2368 entry_free(si->head);
2372 } else if ( si->caching_reason != PC_IGNORE ) {
2373 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2374 si->qtemp, si->caching_reason, 1 );
2377 switch ( si->caching_reason ) {
2379 cache_entries( op, &qc->q_uuid );
2382 si->pbi->bi_cq = qc;
2387 qc->q_sizelimit = rs->sr_nentries;
2397 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2398 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2399 cm->num_cached_queries++;
2400 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2401 cm->num_cached_queries, 0, 0 );
2402 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2404 /* If the consistency checker suspended itself,
2407 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2408 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2409 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2411 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2413 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2416 } else if ( si->count ) {
2417 /* duplicate query, free it */
2419 for (;si->head; si->head=e) {
2420 e = si->head->e_private;
2421 si->head->e_private = NULL;
2422 entry_free(si->head);
2427 filter_free( si->query.filter );
2430 op->o_callback = op->o_callback->sc_next;
2431 op->o_tmpfree( cb, op->o_tmpmemctx );
2434 return SLAP_CB_CONTINUE;
2442 struct search_info *si = op->o_callback->sc_private;
2444 if ( si->swap_saved_attrs ) {
2445 rs->sr_attrs = si->save_attrs;
2446 rs->sr_attr_flags = slap_attr_flags( si->save_attrs );
2447 op->ors_attrs = si->save_attrs;
2450 if ( rs->sr_type == REP_SEARCH ) {
2453 /* don't return more entries than requested by the client */
2454 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2455 si->slimit_exceeded = 1;
2458 /* If we haven't exceeded the limit for this query,
2459 * build a chain of answers to store. If we hit the
2460 * limit, empty the chain and ignore the rest.
2463 slap_overinst *on = si->on;
2464 cache_manager *cm = on->on_bi.bi_private;
2466 /* check if the entry contains undefined
2467 * attributes/objectClasses (ITS#5680) */
2468 if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2469 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2470 op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
2474 /* check for malformed entries: attrs with no values */
2476 Attribute *a = rs->sr_entry->e_attrs;
2477 for (; a; a=a->a_next) {
2478 if ( !a->a_numvals ) {
2479 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2480 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2481 a->a_desc->ad_cname.bv_val );
2487 if ( si->count < si->max ) {
2489 e = entry_dup( rs->sr_entry );
2490 if ( !si->head ) si->head = e;
2491 if ( si->tail ) si->tail->e_private = e;
2498 for (;si->head; si->head=e) {
2499 e = si->head->e_private;
2500 si->head->e_private = NULL;
2501 entry_free(si->head);
2506 if ( si->slimit_exceeded ) {
2509 } else if ( rs->sr_type == REP_RESULT ) {
2512 if ( rs->sr_err == LDAP_SUCCESS ) {
2513 si->caching_reason = PC_POSITIVE;
2515 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2516 && si->qtemp->limitttl )
2520 si->caching_reason = PC_SIZELIMIT;
2521 for (;si->head; si->head=e) {
2522 e = si->head->e_private;
2523 si->head->e_private = NULL;
2524 entry_free(si->head);
2528 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2529 rs->sr_err == LDAP_SUCCESS )
2531 si->caching_reason = PC_NEGATIVE;
2535 if ( si->slimit_exceeded ) {
2536 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2540 return SLAP_CB_CONTINUE;
2543 /* NOTE: this is a quick workaround to let pcache minimally interact
2544 * with pagedResults. A more articulated solutions would be to
2545 * perform the remote query without control and cache all results,
2546 * performing the pagedResults search only within the client
2547 * and the proxy. This requires pcache to understand pagedResults. */
2549 pcache_chk_controls(
2553 const char *non = "";
2554 const char *stripped = "";
2556 switch( op->o_pagedresults ) {
2557 case SLAP_CONTROL_NONCRITICAL:
2559 stripped = "; stripped";
2562 case SLAP_CONTROL_CRITICAL:
2563 Debug( pcache_debug, "%s: "
2564 "%scritical pagedResults control "
2565 "disabled with proxy cache%s.\n",
2566 op->o_log_prefix, non, stripped );
2568 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2572 rs->sr_err = SLAP_CB_CONTINUE;
2580 pc_setpw( Operation *op, struct berval *pwd, cache_manager *cm )
2582 struct berval vals[2];
2585 const char *text = NULL;
2586 BER_BVZERO( &vals[0] );
2587 slap_passwd_hash( pwd, &vals[0], &text );
2588 if ( BER_BVISEMPTY( &vals[0] )) {
2589 Debug( pcache_debug, "pc_setpw: hash failed %s\n",
2595 BER_BVZERO( &vals[1] );
2599 SlapReply sr = { REP_RESULT };
2600 slap_callback cb = { 0, slap_null_cb, 0, 0 };
2603 mod.sml_op = LDAP_MOD_REPLACE;
2605 mod.sml_desc = slap_schema.si_ad_userPassword;
2606 mod.sml_type = mod.sml_desc->ad_cname;
2607 mod.sml_values = vals;
2608 mod.sml_nvalues = NULL;
2609 mod.sml_numvals = 1;
2610 mod.sml_next = NULL;
2612 op->o_tag = LDAP_REQ_MODIFY;
2613 op->orm_modlist = &mod;
2615 op->o_dn = op->o_bd->be_rootdn;
2616 op->o_ndn = op->o_bd->be_rootndn;
2617 op->o_callback = &cb;
2618 Debug( pcache_debug, "pc_setpw: CACHING BIND for %s\n",
2619 op->o_req_dn.bv_val, 0, 0 );
2620 rc = op->o_bd->be_modify( op, &sr );
2621 ch_free( vals[0].bv_val );
2626 typedef struct bindcacheinfo {
2632 pc_bind_save( Operation *op, SlapReply *rs )
2634 if ( rs->sr_err == LDAP_SUCCESS ) {
2635 bindcacheinfo *bci = op->o_callback->sc_private;
2636 slap_overinst *on = bci->on;
2637 cache_manager *cm = on->on_bi.bi_private;
2638 CachedQuery *qc = bci->qc;
2641 ldap_pvt_thread_rdwr_wlock( &qc->rwlock );
2642 if ( qc->bind_refcnt-- ) {
2643 Operation op2 = *op;
2644 if ( pc_setpw( &op2, &op->orb_cred, cm ) == LDAP_SUCCESS )
2645 bci->qc->bindref_time = op->o_time + bci->qc->qtemp->bindttr;
2650 ldap_pvt_thread_rdwr_wunlock( &qc->rwlock );
2651 if ( delete ) free_query(qc);
2653 return SLAP_CB_CONTINUE;
2657 pc_bind_attrs( Operation *op, Entry *e, QueryTemplate *temp,
2658 struct berval *fbv )
2661 struct berval *vals, pres = BER_BVC("*");
2665 vals = op->o_tmpalloc( temp->bindnattrs * sizeof( struct berval ),
2668 for ( i=0; i<temp->bindnattrs; i++ ) {
2669 a = attr_find( e->e_attrs, temp->bindfattrs[i] );
2670 if ( a && a->a_vals ) {
2671 vals[i] = a->a_vals[0];
2672 len += a->a_vals[0].bv_len;
2677 fbv->bv_len = len + temp->bindftemp.bv_len;
2678 fbv->bv_val = op->o_tmpalloc( fbv->bv_len + 1, op->o_tmpmemctx );
2680 p1 = temp->bindftemp.bv_val;
2685 if ( p1[0] == '=' && p1[1] == ')' ) {
2686 AC_MEMCPY( p2, vals[i].bv_val, vals[i].bv_len );
2687 p2 += vals[i].bv_len;
2693 op->o_tmpfree( vals, op->o_tmpmemctx );
2695 /* FIXME: are we sure str2filter_x can't fail?
2696 * caller needs to check */
2698 Filter *f = str2filter_x( op, fbv->bv_val );
2699 assert( f != NULL );
2704 /* Check if the requested entry is from the cache and has a valid
2705 * ttr and password hash
2708 pc_bind_search( Operation *op, SlapReply *rs )
2710 if ( rs->sr_type == REP_SEARCH ) {
2711 bindinfo *pbi = op->o_callback->sc_private;
2713 /* We only care if this is an already cached result and we're
2714 * below the refresh time, or we're offline.
2717 if (( pbi->bi_cm->cc_paused & PCACHE_CC_OFFLINE ) ||
2718 op->o_time < pbi->bi_cq->bindref_time ) {
2721 /* See if a recognized password is hashed here */
2722 a = attr_find( rs->sr_entry->e_attrs,
2723 slap_schema.si_ad_userPassword );
2724 if ( a && a->a_vals[0].bv_val[0] == '{' &&
2725 lutil_passwd_scheme( a->a_vals[0].bv_val ))
2726 pbi->bi_flags |= BI_HASHED;
2728 Debug( pcache_debug, "pc_bind_search: cache is stale, "
2729 "reftime: %ld, current time: %ld\n",
2730 pbi->bi_cq->bindref_time, op->o_time, 0 );
2732 } else if ( pbi->bi_si ) {
2733 /* This search result is going into the cache */
2737 filter_free( pbi->bi_si->query.filter );
2738 f = pc_bind_attrs( op, rs->sr_entry, pbi->bi_templ, &fbv );
2739 op->o_tmpfree( fbv.bv_val, op->o_tmpmemctx );
2740 pbi->bi_si->query.filter = filter_dup( f, NULL );
2741 filter_free_x( op, f, 1 );
2747 /* We always want pc_bind_search to run after the search handlers */
2749 pc_bind_resp( Operation *op, SlapReply *rs )
2751 bindinfo *pbi = op->o_callback->sc_private;
2752 if ( !( pbi->bi_flags & BI_DIDCB )) {
2753 slap_callback *sc = op->o_callback;
2754 while ( sc && sc->sc_response != pcache_response )
2757 sc = op->o_callback;
2758 pbi->bi_cb.sc_next = sc->sc_next;
2759 sc->sc_next = &pbi->bi_cb;
2760 pbi->bi_flags |= BI_DIDCB;
2762 return SLAP_CB_CONTINUE;
2765 #ifdef PCACHE_CONTROL_PRIVDB
2771 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2772 cache_manager *cm = on->on_bi.bi_private;
2773 slap_callback *save_cb;
2776 /* skip if control is unset */
2777 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2778 return SLAP_CB_CONTINUE;
2781 /* The cache DB isn't open yet */
2782 if ( cm->defer_db_open ) {
2783 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2784 "pcachePrivDB: cacheDB not available" );
2788 /* FIXME: might be a little bit exaggerated... */
2789 if ( !be_isroot( op ) ) {
2790 save_cb = op->o_callback;
2791 op->o_callback = NULL;
2792 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2793 "pcachePrivDB: operation not allowed" );
2794 op->o_callback = save_cb;
2799 /* map tag to operation */
2800 type = slap_req2op( op->o_tag );
2801 if ( type != SLAP_OP_LAST ) {
2802 BackendInfo *bi = cm->db.bd_info;
2805 /* execute, if possible */
2806 if ( (&bi->bi_op_bind)[ type ] ) {
2807 Operation op2 = *op;
2811 rc = (&bi->bi_op_bind)[ type ]( &op2, rs );
2812 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2813 op->o_conn->c_authz_cookie = cm->db.be_private;
2820 /* otherwise fall back to error */
2821 save_cb = op->o_callback;
2822 op->o_callback = NULL;
2823 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2824 "operation not supported with pcachePrivDB control" );
2825 op->o_callback = save_cb;
2829 #endif /* PCACHE_CONTROL_PRIVDB */
2836 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2837 cache_manager *cm = on->on_bi.bi_private;
2838 QueryTemplate *temp;
2840 slap_callback cb = { 0 }, *sc;
2846 #ifdef PCACHE_CONTROL_PRIVDB
2847 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL )
2848 return pcache_op_privdb( op, rs );
2849 #endif /* PCACHE_CONTROL_PRIVDB */
2851 /* Skip if we're not configured for Binds, or cache DB isn't open yet */
2852 if ( !cm->cache_binds || cm->defer_db_open )
2853 return SLAP_CB_CONTINUE;
2855 /* First find a matching template with Bind info */
2856 for ( temp=cm->qm->templates; temp; temp=temp->qmnext ) {
2857 if ( temp->bindttr && dnIsSuffix( &op->o_req_ndn, &temp->bindbase ))
2860 /* Didn't find a suitable template, just passthru */
2862 return SLAP_CB_CONTINUE;
2864 /* See if the entry is already locally cached. If so, we can
2865 * populate the query filter to retrieve the cached query. We
2866 * need to check the bindrefresh time in the query.
2869 op2.o_dn = op->o_bd->be_rootdn;
2870 op2.o_ndn = op->o_bd->be_rootndn;
2875 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL, NULL, 0, &e );
2876 if ( rc == LDAP_SUCCESS && e ) {
2877 bi.bi_flags |= BI_LOOKUP;
2878 op2.ors_filter = pc_bind_attrs( op, e, temp, &op2.ors_filterstr );
2879 be_entry_release_r( &op2, e );
2881 op2.ors_filter = temp->bindfilter;
2882 op2.ors_filterstr = temp->bindfilterstr;
2885 op2.o_bd = op->o_bd;
2886 op2.o_tag = LDAP_REQ_SEARCH;
2887 op2.ors_scope = LDAP_SCOPE_BASE;
2888 op2.ors_deref = LDAP_DEREF_NEVER;
2890 op2.ors_tlimit = SLAP_NO_LIMIT;
2891 op2.ors_limit = NULL;
2892 op2.ors_attrs = cm->qm->attr_sets[temp->attr_set_index].attrs;
2893 op2.ors_attrsonly = 0;
2895 /* We want to invoke search at the same level of the stack
2896 * as we're already at...
2903 bi.bi_cb.sc_response = pc_bind_search;
2904 bi.bi_cb.sc_cleanup = NULL;
2905 bi.bi_cb.sc_private = &bi;
2906 cb.sc_private = &bi;
2907 cb.sc_response = pc_bind_resp;
2908 op2.o_callback = &cb;
2909 overlay_op_walk( &op2, rs, op_search, on->on_info, on );
2911 /* OK, just bind locally */
2912 if ( bi.bi_flags & BI_HASHED ) {
2914 BackendDB *be = op->o_bd;
2917 Debug( pcache_debug, "pcache_op_bind: CACHED BIND for %s\n",
2918 op->o_req_dn.bv_val, 0, 0 );
2920 if ( op->o_bd->be_bind( op, rs ) == LDAP_SUCCESS ) {
2921 op->o_conn->c_authz_cookie = cm->db.be_private;
2924 ldap_pvt_thread_rdwr_wlock( &bi.bi_cq->rwlock );
2925 if ( !bi.bi_cq->bind_refcnt-- ) {
2928 ldap_pvt_thread_rdwr_wunlock( &bi.bi_cq->rwlock );
2929 if ( delete ) free_query( bi.bi_cq );
2933 /* We have a cached query to work with */
2935 sc = op->o_tmpalloc( sizeof(slap_callback) + sizeof(bindcacheinfo),
2937 sc->sc_response = pc_bind_save;
2938 sc->sc_cleanup = NULL;
2939 sc->sc_private = sc+1;
2940 bci = sc->sc_private;
2941 sc->sc_next = op->o_callback;
2942 op->o_callback = sc;
2946 return SLAP_CB_CONTINUE;
2949 static slap_response refresh_merge;
2956 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2957 cache_manager *cm = on->on_bi.bi_private;
2958 query_manager* qm = cm->qm;
2963 QueryTemplate *qtemp = NULL;
2964 bindinfo *pbi = NULL;
2967 CachedQuery *answerable = NULL;
2970 struct berval tempstr;
2972 #ifdef PCACHE_CONTROL_PRIVDB
2973 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2974 return pcache_op_privdb( op, rs );
2976 #endif /* PCACHE_CONTROL_PRIVDB */
2978 /* The cache DB isn't open yet */
2979 if ( cm->defer_db_open ) {
2980 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2981 "pcachePrivDB: cacheDB not available" );
2985 /* pickup runtime ACL changes */
2986 cm->db.be_acl = op->o_bd->be_acl;
2989 /* See if we're processing a Bind request
2990 * or a cache refresh */
2991 slap_callback *cb = op->o_callback;
2993 for ( ; cb; cb=cb->sc_next ) {
2994 if ( cb->sc_response == pc_bind_resp ) {
2995 pbi = cb->sc_private;
2998 if ( cb->sc_response == refresh_merge ) {
2999 /* This is a refresh, do not search the cache */
3000 return SLAP_CB_CONTINUE;
3005 /* FIXME: cannot cache/answer requests with pagedResults control */
3007 query.filter = op->ors_filter;
3010 query.base = pbi->bi_templ->bindbase;
3011 query.scope = pbi->bi_templ->bindscope;
3012 attr_set = pbi->bi_templ->attr_set_index;
3014 qtemp = pbi->bi_templ;
3015 if ( pbi->bi_flags & BI_LOOKUP )
3016 answerable = qm->qcfunc(op, qm, &query, qtemp);
3019 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1,
3022 if ( filter2template( op, op->ors_filter, &tempstr ))
3024 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3025 return SLAP_CB_CONTINUE;
3028 Debug( pcache_debug, "query template of incoming query = %s\n",
3029 tempstr.bv_val, 0, 0 );
3032 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
3034 query.base = op->o_req_ndn;
3035 query.scope = op->ors_scope;
3037 /* check for query containment */
3038 if (attr_set > -1) {
3039 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
3040 for (; qt; qt = qt->qtnext ) {
3041 /* find if template i can potentially answer tempstr */
3042 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
3046 Debug( pcache_debug, "Entering QC, querystr = %s\n",
3047 op->ors_filterstr.bv_val, 0, 0 );
3048 answerable = qm->qcfunc(op, qm, &query, qt);
3050 /* if != NULL, rlocks qtemp->t_rwlock */
3055 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3059 BackendDB *save_bd = op->o_bd;
3061 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
3062 answerable->answerable_cnt++;
3063 /* we only care about refcnts if we're refreshing */
3064 if ( answerable->refresh_time )
3065 answerable->refcnt++;
3066 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
3067 answerable->answerable_cnt, 0, 0 );
3068 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
3070 ldap_pvt_thread_rdwr_wlock(&answerable->rwlock);
3071 if ( BER_BVISNULL( &answerable->q_uuid )) {
3072 /* No entries cached, just an empty result set */
3074 send_ldap_result( op, rs );
3076 /* Let Bind know we used a cached query */
3078 answerable->bind_refcnt++;
3079 pbi->bi_cq = answerable;
3083 if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
3085 /* The cached entry was already processed by any
3086 * other overlays, so don't let it get processed again.
3088 * This loop removes over_back_response from the stack.
3090 if ( overlay_callback_after_backover( op, &cb, 0) == 0 ) {
3091 slap_callback **scp;
3092 for ( scp = &op->o_callback; *scp != NULL;
3093 scp = &(*scp)->sc_next ) {
3094 if ( (*scp)->sc_next == &cb ) {
3101 i = cm->db.bd_info->bi_op_search( op, rs );
3103 ldap_pvt_thread_rdwr_wunlock(&answerable->rwlock);
3104 /* locked by qtemp->qcfunc (query_containment) */
3105 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
3110 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
3112 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3113 if (cm->num_cached_queries >= cm->max_queries) {
3116 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3118 if (op->ors_attrsonly)
3123 struct search_info *si;
3125 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
3126 query.filter = filter_dup(op->ors_filter, NULL);
3128 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
3129 cb->sc_response = pcache_response;
3130 cb->sc_cleanup = pcache_op_cleanup;
3131 cb->sc_private = (cb+1);
3132 si = cb->sc_private;
3136 si->max = cm->num_entries_limit ;
3140 si->slimit_exceeded = 0;
3141 si->caching_reason = PC_IGNORE;
3142 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
3143 si->slimit = op->ors_slimit;
3144 op->ors_slimit = cm->num_entries_limit;
3148 si->swap_saved_attrs = 1;
3149 si->save_attrs = op->ors_attrs;
3154 op->ors_attrs = qtemp->t_attrs.attrs;
3156 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3157 cb->sc_next = op->o_callback;
3158 op->o_callback = cb;
3161 slap_callback **pcb;
3163 /* need to move the callback at the end, in case other
3164 * overlays are present, so that the final entry is
3165 * actually cached */
3167 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
3172 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
3176 return SLAP_CB_CONTINUE;
3181 AttributeName* attrs,
3189 for ( ; attrs[i].an_name.bv_val; i++ ) {
3190 /* only count valid attribute names
3191 * (searches ignore others, this overlay does the same) */
3192 if ( attrs[i].an_desc ) {
3198 /* recognize default or explicit single "*" */
3200 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_all_user_attrs ) ) )
3203 attrs = slap_anlist_all_user_attributes;
3205 /* recognize implicit (no valid attributes) or explicit single "1.1" */
3206 } else if ( count == 0 ||
3207 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) )
3213 for ( i = 0; i < num; i++ ) {
3217 if ( count > qm->attr_sets[i].count ) {
3218 if ( qm->attr_sets[i].count &&
3219 bvmatch( &qm->attr_sets[i].attrs[0].an_name, slap_bv_all_user_attrs )) {
3226 if ( !qm->attr_sets[i].count ) {
3232 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
3233 if ( !a2->an_desc && !bvmatch( &a2->an_name, slap_bv_all_user_attrs ) ) continue;
3235 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
3253 /* Refresh a cached query:
3254 * 1: Replay the query on the remote DB and merge each entry into
3255 * the local DB. Remember the DNs of each remote entry.
3256 * 2: Search the local DB for all entries matching this queryID.
3257 * Delete any entry whose DN is not in the list from (1).
3259 typedef struct dnlist {
3260 struct dnlist *next;
3265 typedef struct refresh_info {
3273 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
3275 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
3277 dn->dn.bv_len = bvdn->bv_len;
3278 dn->dn.bv_val = (char *)(dn+1);
3279 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
3280 dn->dn.bv_val[dn->dn.bv_len] = '\0';
3285 refresh_merge( Operation *op, SlapReply *rs )
3287 if ( rs->sr_type == REP_SEARCH ) {
3288 refresh_info *ri = op->o_callback->sc_private;
3294 ocb = op->o_callback;
3295 /* Find local entry, merge */
3296 op->o_bd = ri->ri_be;
3297 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
3298 if ( rc != LDAP_SUCCESS || e == NULL ) {
3299 /* No local entry, just add it. FIXME: we are not checking
3300 * the cache entry limit here
3302 merge_entry( op, rs->sr_entry, 1, &ri->ri_q->q_uuid );
3304 /* Entry exists, update it */
3307 Modifications *modlist, *mods = NULL;
3308 const char* text = NULL;
3309 char textbuf[SLAP_TEXT_BUFLEN];
3310 size_t textlen = sizeof(textbuf);
3311 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
3315 /* Get a copy of only the attrs we requested */
3316 for ( a=e->e_attrs; a; a=a->a_next ) {
3317 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
3318 *b = attr_alloc( a->a_desc );
3320 /* The actual values still belong to e */
3321 (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
3322 SLAP_ATTR_DONT_FREE_DATA;
3323 b = &((*b)->a_next);
3327 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
3328 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
3329 &mods, &modlist, 0 );
3330 be_entry_release_r( op, e );
3331 attrs_free( ne.e_attrs );
3332 slap_mods_free( modlist, 1 );
3333 /* mods is NULL if there are no changes */
3335 SlapReply rs2 = { REP_RESULT };
3336 struct berval dn = op->o_req_dn;
3337 struct berval ndn = op->o_req_ndn;
3338 op->o_tag = LDAP_REQ_MODIFY;
3339 op->orm_modlist = mods;
3340 op->o_req_dn = rs->sr_entry->e_name;
3341 op->o_req_ndn = rs->sr_entry->e_nname;
3342 op->o_callback = &cb;
3343 op->o_bd->be_modify( op, &rs2 );
3344 rs->sr_err = rs2.sr_err;
3345 rs_assert_done( &rs2 );
3346 slap_mods_free( mods, 1 );
3348 op->o_req_ndn = ndn;
3352 /* Add DN to list */
3353 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3355 if ( ri->ri_tail ) {
3356 ri->ri_tail->next = dnl;
3361 op->o_callback = ocb;
3367 refresh_purge( Operation *op, SlapReply *rs )
3369 if ( rs->sr_type == REP_SEARCH ) {
3370 refresh_info *ri = op->o_callback->sc_private;
3374 /* Did the entry exist on the remote? */
3375 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
3376 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
3377 dnlist *dnext = (*dn)->next;
3378 op->o_tmpfree( *dn, op->o_tmpmemctx );
3384 /* No, so put it on the list to delete */
3387 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3388 dnl->next = ri->ri_dels;
3390 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
3391 /* If ours is the only queryId, delete entry */
3392 dnl->delete = ( a->a_numvals == 1 );
3399 refresh_query( Operation *op, CachedQuery *query, slap_overinst *on )
3401 SlapReply rs = {REP_RESULT};
3402 slap_callback cb = { 0 };
3403 refresh_info ri = { 0 };
3404 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
3405 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3406 Filter filter = {LDAP_FILTER_EQUALITY};
3407 AttributeName attrs[ 2 ] = {{{ 0 }}};
3411 ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
3413 ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
3415 cb.sc_response = refresh_merge;
3416 cb.sc_private = &ri;
3419 ri.ri_be = op->o_bd;
3422 op->o_tag = LDAP_REQ_SEARCH;
3423 op->o_protocol = LDAP_VERSION3;
3424 op->o_callback = &cb;
3425 op->o_do_not_cache = 1;
3427 op->o_req_dn = query->qbase->base;
3428 op->o_req_ndn = query->qbase->base;
3429 op->ors_scope = query->scope;
3430 op->ors_deref = LDAP_DEREF_NEVER;
3431 op->ors_slimit = SLAP_NO_LIMIT;
3432 op->ors_tlimit = SLAP_NO_LIMIT;
3433 op->ors_limit = NULL;
3434 op->ors_filter = query->filter;
3435 filter2bv_x( op, query->filter, &op->ors_filterstr );
3436 op->ors_attrs = query->qtemp->t_attrs.attrs;
3437 op->ors_attrsonly = 0;
3439 op->o_bd = on->on_info->oi_origdb;
3440 rc = op->o_bd->be_search( op, &rs );
3442 op->o_bd = ri.ri_be;
3446 /* Get the DNs of all entries matching this query */
3447 cb.sc_response = refresh_purge;
3449 op->o_bd = ri.ri_be;
3450 op->o_req_dn = op->o_bd->be_suffix[0];
3451 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3452 op->ors_scope = LDAP_SCOPE_SUBTREE;
3453 op->ors_deref = LDAP_DEREF_NEVER;
3454 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
3455 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
3456 filter.f_ava = &ava;
3457 filter.f_av_desc = ad_queryId;
3458 filter.f_av_value = query->q_uuid;
3459 attrs[ 0 ].an_desc = ad_queryId;
3460 attrs[ 0 ].an_name = ad_queryId->ad_cname;
3461 op->ors_attrs = attrs;
3462 op->ors_attrsonly = 0;
3463 rs_reinit( &rs, REP_RESULT );
3464 rc = op->o_bd->be_search( op, &rs );
3465 if ( rc ) goto leave;
3467 while (( dn = ri.ri_dels )) {
3468 op->o_req_dn = dn->dn;
3469 op->o_req_ndn = dn->dn;
3470 rs_reinit( &rs, REP_RESULT );
3472 op->o_tag = LDAP_REQ_DELETE;
3473 op->o_bd->be_delete( op, &rs );
3476 struct berval vals[2];
3478 vals[0] = query->q_uuid;
3479 BER_BVZERO( &vals[1] );
3480 mod.sml_op = LDAP_MOD_DELETE;
3482 mod.sml_desc = ad_queryId;
3483 mod.sml_type = ad_queryId->ad_cname;
3484 mod.sml_values = vals;
3485 mod.sml_nvalues = NULL;
3486 mod.sml_numvals = 1;
3487 mod.sml_next = NULL;
3489 op->o_tag = LDAP_REQ_MODIFY;
3490 op->orm_modlist = &mod;
3491 op->o_bd->be_modify( op, &rs );
3493 ri.ri_dels = dn->next;
3494 op->o_tmpfree( dn, op->o_tmpmemctx );
3498 /* reset our local heap, we're done with it */
3499 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
3508 struct re_s *rtask = arg;
3509 slap_overinst *on = rtask->arg;
3510 cache_manager *cm = on->on_bi.bi_private;
3511 query_manager *qm = cm->qm;
3512 Connection conn = {0};
3513 OperationBuffer opbuf;
3516 CachedQuery *query, *qprev;
3517 int return_val, pause = PCACHE_CC_PAUSED;
3518 QueryTemplate *templ;
3520 /* Don't expire anything when we're offline */
3521 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
3522 pause = PCACHE_CC_OFFLINE;
3526 connection_fake_init( &conn, &opbuf, ctx );
3530 op->o_dn = cm->db.be_rootdn;
3531 op->o_ndn = cm->db.be_rootndn;
3535 for (templ = qm->templates; templ; templ=templ->qmnext) {
3537 if ( !templ->query_last ) continue;
3539 op->o_time = slap_get_time();
3540 if ( !templ->ttr ) {
3542 if ( templ->negttl && templ->negttl < ttl )
3543 ttl = templ->negttl;
3544 if ( templ->limitttl && templ->limitttl < ttl )
3545 ttl = templ->limitttl;
3546 /* The oldest timestamp that needs expiration checking */
3550 for ( query=templ->query_last; query; query=qprev ) {
3551 qprev = query->prev;
3552 if ( query->refresh_time && query->refresh_time < op->o_time ) {
3553 /* A refresh will extend the expiry if the query has been
3554 * referenced, but not if it's unreferenced. If the
3555 * expiration has been hit, then skip the refresh since
3556 * we're just going to discard the result anyway.
3558 if ( query->refcnt )
3559 query->expiry_time = op->o_time + templ->ttl;
3560 if ( query->expiry_time > op->o_time ) {
3561 refresh_query( op, query, on );
3566 if (query->expiry_time < op->o_time) {
3568 Debug( pcache_debug, "Lock CR index = %p\n",
3569 (void *) templ, 0, 0 );
3570 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
3571 if ( query == templ->query_last ) {
3573 remove_from_template(query, templ);
3574 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
3575 (void *) templ, templ->no_of_queries, 0 );
3576 Debug( pcache_debug, "Unlock CR index = %p\n",
3577 (void *) templ, 0, 0 );
3580 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3583 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
3584 remove_query(qm, query);
3585 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
3586 if ( BER_BVISNULL( &query->q_uuid ))
3589 return_val = remove_query_data(op, &query->q_uuid);
3590 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3592 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3593 cm->cur_entries -= return_val;
3594 cm->num_cached_queries--;
3595 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3596 cm->num_cached_queries, 0, 0 );
3597 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3598 Debug( pcache_debug,
3599 "STALE QUERY REMOVED, CACHE ="
3601 cm->cur_entries, 0, 0 );
3602 ldap_pvt_thread_rdwr_wlock( &query->rwlock );
3603 if ( query->bind_refcnt-- ) {
3608 ldap_pvt_thread_rdwr_wunlock( &query->rwlock );
3609 if ( rem ) free_query(query);
3610 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3611 } else if ( !templ->ttr && query->expiry_time > ttl ) {
3612 /* We don't need to check for refreshes, and this
3613 * query's expiry is too new, and all subsequent queries
3614 * will be newer yet. So stop looking.
3616 * If we have refreshes, then we always have to walk the
3617 * entire query list.
3625 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3626 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3627 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3629 /* If there were no queries, defer processing for a while */
3630 if ( cm->cc_paused != pause )
3631 cm->cc_paused = pause;
3632 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3634 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3639 #define MAX_ATTR_SETS 500
3652 static ConfigDriver pc_cf_gen;
3653 static ConfigLDAPadd pc_ldadd;
3654 static ConfigCfAdd pc_cfadd;
3656 static ConfigTable pccfg[] = {
3657 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3659 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3660 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3661 "DESC 'Proxy Cache basic parameters' "
3662 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3663 { "pcacheAttrset", "index> <attributes...",
3664 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3665 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3666 "DESC 'A set of attributes to cache' "
3667 "EQUALITY caseIgnoreMatch "
3668 "SYNTAX OMsDirectoryString )", NULL, NULL },
3669 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3671 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3672 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3673 "DESC 'Filter template, attrset, cache TTL, "
3674 "optional negative TTL, optional sizelimit TTL, "
3676 "EQUALITY caseIgnoreMatch "
3677 "SYNTAX OMsDirectoryString )", NULL, NULL },
3678 { "pcachePosition", "head|tail(default)",
3679 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3680 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3681 "DESC 'Response callback position in overlay stack' "
3682 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3683 { "pcacheMaxQueries", "queries",
3684 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3685 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3686 "DESC 'Maximum number of queries to cache' "
3687 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
3688 { "pcachePersist", "TRUE|FALSE",
3689 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3690 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3691 "DESC 'Save cached queries for hot restart' "
3692 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3693 { "pcacheValidate", "TRUE|FALSE",
3694 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3695 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3696 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3697 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3698 { "pcacheOffline", "TRUE|FALSE",
3699 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3700 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3701 "DESC 'Set cache to offline mode and disable expiration' "
3702 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3703 { "pcacheBind", "filter> <attrset-index> <TTR> <scope> <base",
3704 6, 6, 0, ARG_MAGIC|PC_BIND, pc_cf_gen,
3705 "( OLcfgOvAt:2.9 NAME 'olcPcacheBind' "
3706 "DESC 'Parameters for caching Binds' "
3707 "EQUALITY caseIgnoreMatch "
3708 "SYNTAX OMsDirectoryString )", NULL, NULL },
3709 { "pcache-", "private database args",
3710 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3713 /* Legacy keywords */
3714 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3716 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3718 { "proxyattrset", "index> <attributes...",
3719 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3721 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3722 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3724 { "response-callback", "head|tail(default)",
3725 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3727 { "proxyCacheQueries", "queries",
3728 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3730 { "proxySaveQueries", "TRUE|FALSE",
3731 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3733 { "proxyCheckCacheability", "TRUE|FALSE",
3734 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3737 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3740 static ConfigOCs pcocs[] = {
3741 { "( OLcfgOvOc:2.1 "
3742 "NAME 'olcPcacheConfig' "
3743 "DESC 'ProxyCache configuration' "
3744 "SUP olcOverlayConfig "
3745 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3746 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3747 "olcPcacheValidate $ olcPcacheOffline $ olcPcacheBind ) )",
3748 Cft_Overlay, pccfg, NULL, pc_cfadd },
3749 { "( OLcfgOvOc:2.2 "
3750 "NAME 'olcPcacheDatabase' "
3751 "DESC 'Cache database configuration' "
3752 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3756 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3759 pc_ldadd_cleanup( ConfigArgs *c )
3761 slap_overinst *on = c->ca_private;
3762 return pcache_db_open2( on, &c->reply );
3766 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3771 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3772 p->ce_bi->bi_cf_ocs != pcocs )
3773 return LDAP_CONSTRAINT_VIOLATION;
3775 on = (slap_overinst *)p->ce_bi;
3776 cm = on->on_bi.bi_private;
3778 /* Defer open if this is an LDAPadd */
3779 if ( CONFIG_ONLINE_ADD( ca ))
3780 ca->cleanup = pc_ldadd_cleanup;
3782 cm->defer_db_open = 0;
3783 ca->ca_private = on;
3784 return LDAP_SUCCESS;
3788 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3790 CfEntryInfo *pe = p->e_private;
3791 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3792 cache_manager *cm = on->on_bi.bi_private;
3795 /* FIXME: should not hardcode "olcDatabase" here */
3796 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3797 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3798 0, cm->db.bd_info->bi_type );
3799 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3802 bv.bv_val = ca->cr_msg;
3804 cm->defer_db_open = 0;
3806 /* We can only create this entry if the database is table-driven
3808 if ( cm->db.bd_info->bi_cf_ocs )
3809 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3816 pc_cf_gen( ConfigArgs *c )
3818 slap_overinst *on = (slap_overinst *)c->bi;
3819 cache_manager* cm = on->on_bi.bi_private;
3820 query_manager* qm = cm->qm;
3821 QueryTemplate* temp;
3822 AttributeName* attr_name;
3823 AttributeName* attrarray;
3824 const char* text=NULL;
3829 if ( c->op == SLAP_CONFIG_EMIT ) {
3833 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3834 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3835 cm->num_entries_limit, cm->cc_period );
3836 bv.bv_val = c->cr_msg;
3837 value_add_one( &c->rvalue_vals, &bv );
3840 for (i=0; i<cm->numattrsets; i++) {
3841 if ( !qm->attr_sets[i].count ) continue;
3843 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3845 /* count the attr length */
3846 for ( attr_name = qm->attr_sets[i].attrs;
3847 attr_name->an_name.bv_val; attr_name++ )
3849 bv.bv_len += attr_name->an_name.bv_len + 1;
3850 if ( attr_name->an_desc &&
3851 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3852 bv.bv_len += STRLENOF("undef:");
3856 bv.bv_val = ch_malloc( bv.bv_len+1 );
3857 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3858 for ( attr_name = qm->attr_sets[i].attrs;
3859 attr_name->an_name.bv_val; attr_name++ ) {
3861 if ( attr_name->an_desc &&
3862 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3863 ptr = lutil_strcopy( ptr, "undef:" );
3865 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3867 ber_bvarray_add( &c->rvalue_vals, &bv );
3869 if ( !c->rvalue_vals )
3873 for (temp=qm->templates; temp; temp=temp->qmnext) {
3874 /* HEADS-UP: always print all;
3875 * if optional == 0, ignore */
3876 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3877 " %d %ld %ld %ld %ld",
3878 temp->attr_set_index,
3883 bv.bv_len += temp->querystr.bv_len + 2;
3884 bv.bv_val = ch_malloc( bv.bv_len+1 );
3887 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3889 strcpy( ptr, c->cr_msg );
3890 ber_bvarray_add( &c->rvalue_vals, &bv );
3892 if ( !c->rvalue_vals )
3896 for (temp=qm->templates; temp; temp=temp->qmnext) {
3897 if ( !temp->bindttr ) continue;
3898 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3900 temp->attr_set_index,
3902 ldap_pvt_scope2str( temp->bindscope ));
3903 bv.bv_len += temp->bindbase.bv_len + temp->bindftemp.bv_len + 4;
3904 bv.bv_val = ch_malloc( bv.bv_len + 1 );
3907 ptr = lutil_strcopy( ptr, temp->bindftemp.bv_val );
3909 ptr = lutil_strcopy( ptr, c->cr_msg );
3911 ptr = lutil_strcopy( ptr, temp->bindbase.bv_val );
3914 ber_bvarray_add( &c->rvalue_vals, &bv );
3916 if ( !c->rvalue_vals )
3920 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3921 BER_BVSTR( &bv, "head" );
3923 BER_BVSTR( &bv, "tail" );
3925 value_add_one( &c->rvalue_vals, &bv );
3928 c->value_int = cm->max_queries;
3931 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3935 } else if ( c->op == LDAP_MOD_DELETE ) {
3938 case PC_ATTR: /* FIXME */
3943 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3944 /* If there were cached queries when we went offline,
3945 * restart the checker now.
3947 if ( cm->num_cached_queries ) {
3948 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3950 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3951 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3961 if ( cm->numattrsets > 0 ) {
3962 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive already provided" );
3963 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3967 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3968 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3970 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3973 if ( cm->numattrsets <= 0 ) {
3974 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3975 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3978 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3979 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3980 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3984 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3985 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3986 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3990 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3991 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3993 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3996 if ( cm->max_entries <= 0 ) {
3997 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3998 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
4002 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
4003 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
4005 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4008 if ( cm->num_entries_limit <= 0 ) {
4009 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
4010 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4013 if ( cm->num_entries_limit > cm->max_entries ) {
4014 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
4015 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4019 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4020 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
4022 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4026 cm->cc_period = (time_t)t;
4027 Debug( pcache_debug,
4028 "Total # of attribute sets to be cached = %d.\n",
4029 cm->numattrsets, 0, 0 );
4030 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
4031 sizeof( struct attr_set ) );
4034 if ( cm->numattrsets == 0 ) {
4035 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4036 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4039 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
4040 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
4042 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4046 if ( num < 0 || num >= cm->numattrsets ) {
4047 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
4048 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4049 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4052 qm->attr_sets[num].flags |= PC_CONFIGURED;
4053 if ( c->argc == 2 ) {
4055 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4056 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
4057 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4060 } else if ( c->argc == 3 ) {
4061 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4062 qm->attr_sets[num].count = 1;
4063 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4064 sizeof( AttributeName ) );
4065 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4068 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4069 qm->attr_sets[num].count = 1;
4070 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4071 sizeof( AttributeName ) );
4072 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4075 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
4078 /* else: fallthru */
4080 } else if ( c->argc == 4 ) {
4081 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
4082 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
4084 qm->attr_sets[num].count = 2;
4085 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
4086 sizeof( AttributeName ) );
4087 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4088 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4091 /* else: fallthru */
4094 if ( c->argc > 2 ) {
4095 int all_user = 0, all_op = 0;
4097 qm->attr_sets[num].count = c->argc - 2;
4098 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
4099 sizeof( AttributeName ) );
4100 attr_name = qm->attr_sets[num].attrs;
4101 for ( i = 2; i < c->argc; i++ ) {
4102 attr_name->an_desc = NULL;
4103 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
4104 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4105 "invalid attr #%d \"%s\" in attrlist",
4106 i - 2, c->argv[i] );
4107 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4108 ch_free( qm->attr_sets[num].attrs );
4109 qm->attr_sets[num].attrs = NULL;
4110 qm->attr_sets[num].count = 0;
4113 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4115 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
4116 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4118 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4120 if ( strncasecmp( c->argv[i], "undef:", STRLENOF("undef:") ) == 0 ) {
4122 ber_str2bv( c->argv[i] + STRLENOF("undef:"), 0, 0, &bv );
4123 attr_name->an_desc = slap_bv2tmp_ad( &bv, NULL );
4125 } else if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
4126 strcpy( c->cr_msg, text );
4127 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4128 ch_free( qm->attr_sets[num].attrs );
4129 qm->attr_sets[num].attrs = NULL;
4130 qm->attr_sets[num].count = 0;
4133 attr_name->an_name = attr_name->an_desc->ad_cname;
4135 attr_name->an_oc = NULL;
4136 attr_name->an_flags = 0;
4137 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
4138 qm->attr_sets[num].flags |= PC_GOT_OC;
4140 BER_BVZERO( &attr_name->an_name );
4143 /* warn if list contains both "*" and "+" */
4144 if ( i > 4 && all_user && all_op ) {
4145 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4146 "warning: attribute list contains \"*\" and \"+\"" );
4147 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4152 if ( cm->numattrsets == 0 ) {
4153 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4154 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4157 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4158 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
4160 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4164 if ( i < 0 || i >= cm->numattrsets ||
4165 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4166 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
4167 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4168 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4172 AttributeName *attrs;
4174 cnt = template_attrs( c->argv[1], &qm->attr_sets[i], &attrs, &text );
4176 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4178 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4181 temp = ch_calloc( 1, sizeof( QueryTemplate ));
4182 temp->qmnext = qm->templates;
4183 qm->templates = temp;
4184 temp->t_attrs.attrs = attrs;
4185 temp->t_attrs.count = cnt;
4187 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
4188 temp->query = temp->query_last = NULL;
4189 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4190 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4191 "unable to parse template ttl=\"%s\"",
4193 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4195 ch_free( temp->t_attrs.attrs );
4199 temp->ttl = (time_t)t;
4200 temp->negttl = (time_t)0;
4201 temp->limitttl = (time_t)0;
4202 temp->ttr = (time_t)0;
4203 switch ( c->argc ) {
4205 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
4206 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4207 "unable to parse template ttr=\"%s\"",
4209 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4212 temp->ttr = (time_t)t;
4216 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4217 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4218 "unable to parse template sizelimit ttl=\"%s\"",
4220 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4223 temp->limitttl = (time_t)t;
4227 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
4228 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4229 "unable to parse template negative ttl=\"%s\"",
4231 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4234 temp->negttl = (time_t)t;
4238 temp->no_of_queries = 0;
4240 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
4241 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
4242 Debug( pcache_debug, " query template: %s\n",
4243 temp->querystr.bv_val, 0, 0 );
4244 temp->attr_set_index = i;
4245 qm->attr_sets[i].flags |= PC_REFERENCED;
4246 temp->qtnext = qm->attr_sets[i].templates;
4247 qm->attr_sets[i].templates = temp;
4248 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
4249 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
4250 for ( i=0; attrarray[i].an_name.bv_val; i++ )
4251 Debug( pcache_debug, "\t%s\n",
4252 attrarray[i].an_name.bv_val, 0, 0 );
4256 if ( !qm->templates ) {
4257 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcacheTemplate\" directive not provided yet" );
4258 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4261 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4262 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse Bind index #=\"%s\"",
4264 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4268 if ( i < 0 || i >= cm->numattrsets ||
4269 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4270 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind index %d invalid (%s%d)",
4271 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4272 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4275 { struct berval bv, tempbv;
4276 AttributeDescription **descs;
4278 ber_str2bv( c->argv[1], 0, 0, &bv );
4279 ndescs = ftemp_attrs( &bv, &tempbv, &descs, &text );
4281 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4283 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4286 for ( temp = qm->templates; temp; temp=temp->qmnext ) {
4287 if ( temp->attr_set_index == i && bvmatch( &tempbv,
4291 ch_free( tempbv.bv_val );
4294 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind template %s %d invalid",
4296 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4299 ber_dupbv( &temp->bindftemp, &bv );
4300 temp->bindfattrs = descs;
4301 temp->bindnattrs = ndescs;
4303 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4304 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4305 "unable to parse bind ttr=\"%s\"",
4307 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4309 ch_free( temp->bindfattrs );
4310 temp->bindfattrs = NULL;
4311 ch_free( temp->bindftemp.bv_val );
4312 BER_BVZERO( &temp->bindftemp );
4315 num = ldap_pvt_str2scope( c->argv[4] );
4317 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4318 "unable to parse bind scope=\"%s\"",
4320 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4324 struct berval dn, ndn;
4325 ber_str2bv( c->argv[5], 0, 0, &dn );
4326 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
4328 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4329 "invalid bind baseDN=\"%s\"",
4331 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4334 if ( temp->bindbase.bv_val )
4335 ch_free( temp->bindbase.bv_val );
4336 temp->bindbase = ndn;
4339 /* convert the template into dummy filter */
4341 char *eq = temp->bindftemp.bv_val, *e2;
4344 while ((eq = strchr(eq, '=' ))) {
4349 bv.bv_len = temp->bindftemp.bv_len + i;
4350 bv.bv_val = ch_malloc( bv.bv_len + 1 );
4351 for ( e2 = bv.bv_val, eq = temp->bindftemp.bv_val;
4362 f = str2filter( bv.bv_val );
4364 ch_free( bv.bv_val );
4365 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4366 "unable to parse bindfilter=\"%s\"", bv.bv_val );
4367 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4368 ch_free( temp->bindbase.bv_val );
4369 BER_BVZERO( &temp->bindbase );
4372 if ( temp->bindfilter )
4373 filter_free( temp->bindfilter );
4374 if ( temp->bindfilterstr.bv_val )
4375 ch_free( temp->bindfilterstr.bv_val );
4376 temp->bindfilterstr = bv;
4377 temp->bindfilter = f;
4379 temp->bindttr = (time_t)t;
4380 temp->bindscope = num;
4381 cm->cache_binds = 1;
4385 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
4386 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
4388 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
4389 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4392 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
4393 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4398 if ( c->value_int <= 0 ) {
4399 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
4400 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4403 cm->max_queries = c->value_int;
4407 cm->cc_paused |= PCACHE_CC_OFFLINE;
4409 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
4412 if ( cm->db.be_private == NULL ) {
4413 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4414 "private database must be defined before setting database specific options" );
4415 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4419 if ( cm->db.bd_info->bi_cf_ocs ) {
4422 char *argv0 = c->argv[ 0 ];
4424 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4426 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
4428 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4429 "private database does not recognize specific option '%s'",
4431 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4435 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
4437 c->bi = c->be->bd_info;
4439 rc = config_add_vals( ct, c );
4443 c->table = c2.table;
4446 c->argv[ 0 ] = argv0;
4448 } else if ( cm->db.be_config != NULL ) {
4449 char *argv0 = c->argv[ 0 ];
4451 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4452 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
4453 c->argv[ 0 ] = argv0;
4456 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4457 "no means to set private database specific options" );
4458 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4463 rc = SLAP_CONF_UNKNOWN;
4479 slap_overinst *on = (slap_overinst *)be->bd_info;
4480 cache_manager* cm = on->on_bi.bi_private;
4482 /* Something for the cache database? */
4483 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
4484 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
4486 return SLAP_CONF_UNKNOWN;
4494 slap_overinst *on = (slap_overinst *)be->bd_info;
4498 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
4499 on->on_bi.bi_private = cm;
4501 qm = (query_manager*)ch_malloc(sizeof(query_manager));
4504 cm->db.bd_info = NULL;
4505 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
4506 cm->db.be_private = NULL;
4507 cm->db.bd_self = &cm->db;
4509 cm->numattrsets = 0;
4510 cm->num_entries_limit = 5;
4511 cm->num_cached_queries = 0;
4512 cm->max_entries = 0;
4513 cm->cur_entries = 0;
4514 cm->max_queries = 10000;
4515 cm->save_queries = 0;
4516 cm->check_cacheability = 0;
4517 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4518 cm->defer_db_open = 1;
4519 cm->cache_binds = 0;
4520 cm->cc_period = 1000;
4523 #ifdef PCACHE_MONITOR
4524 cm->monitor_cb = NULL;
4525 #endif /* PCACHE_MONITOR */
4527 qm->attr_sets = NULL;
4528 qm->templates = NULL;
4530 qm->lru_bottom = NULL;
4532 qm->qcfunc = query_containment;
4533 qm->crfunc = cache_replacement;
4534 qm->addfunc = add_query;
4535 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
4537 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
4539 #ifndef PCACHE_MONITOR
4541 #else /* PCACHE_MONITOR */
4542 return pcache_monitor_db_init( be );
4543 #endif /* PCACHE_MONITOR */
4547 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
4549 assert( op->o_tag == LDAP_REQ_SEARCH );
4551 if ( rs->sr_type == REP_SEARCH ) {
4554 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
4558 assert( a->a_nvals != NULL );
4560 valsp = op->o_callback->sc_private;
4561 assert( *valsp == NULL );
4563 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
4571 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
4573 assert( op->o_tag == LDAP_REQ_SEARCH );
4575 if ( rs->sr_type == REP_SEARCH ) {
4576 int *countp = (int *)op->o_callback->sc_private;
4589 cache_manager *cm = on->on_bi.bi_private;
4590 query_manager* qm = cm->qm;
4593 rc = backend_startup_one( &cm->db, cr );
4595 cm->defer_db_open = 0;
4598 /* There is no runqueue in TOOL mode */
4599 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
4600 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4601 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
4602 consistency_check, on,
4603 "pcache_consistency", cm->db.be_suffix[0].bv_val );
4604 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4606 /* Cached database must have the rootdn */
4607 if ( BER_BVISNULL( &cm->db.be_rootndn )
4608 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
4610 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
4611 "underlying database of type \"%s\"\n"
4612 " serving naming context \"%s\"\n"
4613 " has no \"rootdn\", required by \"pcache\".\n",
4614 on->on_info->oi_orig->bi_type,
4615 cm->db.be_suffix[0].bv_val, 0 );
4619 if ( cm->save_queries ) {
4620 void *thrctx = ldap_pvt_thread_pool_context();
4621 Connection conn = { 0 };
4622 OperationBuffer opbuf;
4624 slap_callback cb = { 0 };
4625 SlapReply rs = { REP_RESULT };
4626 BerVarray vals = NULL;
4627 Filter f = { 0 }, f2 = { 0 };
4628 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
4629 AttributeName attrs[ 2 ] = {{{ 0 }}};
4631 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4636 op->o_tag = LDAP_REQ_SEARCH;
4637 op->o_protocol = LDAP_VERSION3;
4638 cb.sc_response = pcache_cachedquery_open_cb;
4639 cb.sc_private = &vals;
4640 op->o_callback = &cb;
4641 op->o_time = slap_get_time();
4642 op->o_do_not_cache = 1;
4643 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4645 op->o_dn = cm->db.be_rootdn;
4646 op->o_ndn = cm->db.be_rootndn;
4647 op->o_req_dn = cm->db.be_suffix[ 0 ];
4648 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
4650 op->ors_scope = LDAP_SCOPE_BASE;
4651 op->ors_deref = LDAP_DEREF_NEVER;
4653 op->ors_tlimit = SLAP_NO_LIMIT;
4654 op->ors_limit = NULL;
4655 ber_str2bv( "(pcacheQueryURL=*)", 0, 0, &op->ors_filterstr );
4656 f.f_choice = LDAP_FILTER_PRESENT;
4657 f.f_desc = ad_cachedQueryURL;
4658 op->ors_filter = &f;
4659 attrs[ 0 ].an_desc = ad_cachedQueryURL;
4660 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
4661 op->ors_attrs = attrs;
4662 op->ors_attrsonly = 0;
4664 rc = op->o_bd->be_search( op, &rs );
4665 if ( rc == LDAP_SUCCESS && vals != NULL ) {
4668 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
4669 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
4670 cm->num_cached_queries++;
4674 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4677 /* count cached entries */
4678 f.f_choice = LDAP_FILTER_NOT;
4680 f2.f_choice = LDAP_FILTER_EQUALITY;
4682 f2.f_av_desc = slap_schema.si_ad_objectClass;
4683 BER_BVSTR( &f2.f_av_value, "glue" );
4684 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
4686 op->ors_slimit = SLAP_NO_LIMIT;
4687 op->ors_scope = LDAP_SCOPE_SUBTREE;
4688 op->ors_attrs = slap_anlist_no_attrs;
4690 rs_reinit( &rs, REP_RESULT );
4691 op->o_callback->sc_response = pcache_cachedquery_count_cb;
4692 op->o_callback->sc_private = &rs.sr_nentries;
4694 rc = op->o_bd->be_search( op, &rs );
4696 cm->cur_entries = rs.sr_nentries;
4710 slap_overinst *on = (slap_overinst *)be->bd_info;
4711 cache_manager *cm = on->on_bi.bi_private;
4712 query_manager* qm = cm->qm;
4713 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
4715 /* check attr sets */
4716 for ( i = 0; i < cm->numattrsets; i++) {
4717 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
4718 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
4719 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
4723 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
4727 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
4728 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
4733 if ( ncf || rf || nrf ) {
4734 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
4735 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
4736 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
4743 /* need to inherit something from the original database... */
4744 cm->db.be_def_limit = be->be_def_limit;
4745 cm->db.be_limits = be->be_limits;
4746 cm->db.be_acl = be->be_acl;
4747 cm->db.be_dfltaccess = be->be_dfltaccess;
4749 if ( SLAP_DBMONITORING( be ) ) {
4750 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
4753 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
4756 if ( !cm->defer_db_open ) {
4757 rc = pcache_db_open2( on, cr );
4760 #ifdef PCACHE_MONITOR
4761 if ( rc == LDAP_SUCCESS ) {
4762 rc = pcache_monitor_db_open( be );
4764 #endif /* PCACHE_MONITOR */
4770 pcache_free_qbase( void *v )
4776 tavl_free( qb->scopes[i], NULL );
4786 slap_overinst *on = (slap_overinst *)be->bd_info;
4787 cache_manager *cm = on->on_bi.bi_private;
4788 query_manager *qm = cm->qm;
4792 /* stop the thread ... */
4794 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4795 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4796 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4798 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4799 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4803 if ( cm->save_queries ) {
4805 BerVarray vals = NULL;
4808 Connection conn = { 0 };
4809 OperationBuffer opbuf;
4811 slap_callback cb = { 0 };
4813 SlapReply rs = { REP_RESULT };
4814 Modifications mod = {{ 0 }};
4816 thrctx = ldap_pvt_thread_pool_context();
4818 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4821 mod.sml_numvals = 0;
4822 if ( qm->templates != NULL ) {
4823 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4824 for ( qc = tm->query; qc; qc = qc->next ) {
4827 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4828 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4836 op->o_dn = cm->db.be_rootdn;
4837 op->o_ndn = cm->db.be_rootndn;
4839 op->o_tag = LDAP_REQ_MODIFY;
4840 op->o_protocol = LDAP_VERSION3;
4841 cb.sc_response = slap_null_cb;
4842 op->o_callback = &cb;
4843 op->o_time = slap_get_time();
4844 op->o_do_not_cache = 1;
4845 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4847 op->o_req_dn = op->o_bd->be_suffix[0];
4848 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4850 mod.sml_op = LDAP_MOD_REPLACE;
4852 mod.sml_desc = ad_cachedQueryURL;
4853 mod.sml_type = ad_cachedQueryURL->ad_cname;
4854 mod.sml_values = vals;
4855 mod.sml_nvalues = NULL;
4856 mod.sml_next = NULL;
4857 Debug( pcache_debug,
4858 "%sSETTING CACHED QUERY URLS\n",
4859 vals == NULL ? "RE" : "", 0, 0 );
4861 op->orm_modlist = &mod;
4863 op->o_bd->be_modify( op, &rs );
4865 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4868 /* cleanup stuff inherited from the original database... */
4869 cm->db.be_limits = NULL;
4870 cm->db.be_acl = NULL;
4872 if ( cm->db.bd_info->bi_db_close ) {
4873 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4876 #ifdef PCACHE_MONITOR
4877 if ( rc == LDAP_SUCCESS ) {
4878 rc = pcache_monitor_db_close( be );
4880 #endif /* PCACHE_MONITOR */
4891 slap_overinst *on = (slap_overinst *)be->bd_info;
4892 cache_manager *cm = on->on_bi.bi_private;
4893 query_manager *qm = cm->qm;
4897 if ( cm->db.be_private != NULL ) {
4898 backend_stopdown_one( &cm->db );
4901 while ( (tm = qm->templates) != NULL ) {
4902 CachedQuery *qc, *qn;
4903 qm->templates = tm->qmnext;
4904 for ( qc = tm->query; qc; qc = qn ) {
4908 avl_free( tm->qbase, pcache_free_qbase );
4909 free( tm->querystr.bv_val );
4910 free( tm->bindfattrs );
4911 free( tm->bindftemp.bv_val );
4912 free( tm->bindfilterstr.bv_val );
4913 free( tm->bindbase.bv_val );
4914 filter_free( tm->bindfilter );
4915 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4916 free( tm->t_attrs.attrs );
4920 for ( i = 0; i < cm->numattrsets; i++ ) {
4923 /* Account of LDAP_NO_ATTRS */
4924 if ( !qm->attr_sets[i].count ) continue;
4926 for ( j = 0; !BER_BVISNULL( &qm->attr_sets[i].attrs[j].an_name ); j++ ) {
4927 if ( qm->attr_sets[i].attrs[j].an_desc &&
4928 ( qm->attr_sets[i].attrs[j].an_desc->ad_flags &
4929 SLAP_DESC_TEMPORARY ) ) {
4930 slap_sl_mfuncs.bmf_free( qm->attr_sets[i].attrs[j].an_desc, NULL );
4933 free( qm->attr_sets[i].attrs );
4935 free( qm->attr_sets );
4936 qm->attr_sets = NULL;
4938 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4939 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4943 #ifdef PCACHE_MONITOR
4944 pcache_monitor_db_destroy( be );
4945 #endif /* PCACHE_MONITOR */
4950 #ifdef PCACHE_CONTROL_PRIVDB
4952 Control ::= SEQUENCE {
4953 controlType LDAPOID,
4954 criticality BOOLEAN DEFAULT FALSE,
4955 controlValue OCTET STRING OPTIONAL }
4957 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4959 * criticality must be TRUE; controlValue must be absent.
4967 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4968 rs->sr_text = "privateDB control specified multiple times";
4969 return LDAP_PROTOCOL_ERROR;
4972 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4973 rs->sr_text = "privateDB control value not absent";
4974 return LDAP_PROTOCOL_ERROR;
4977 if ( !ctrl->ldctl_iscritical ) {
4978 rs->sr_text = "privateDB control criticality required";
4979 return LDAP_PROTOCOL_ERROR;
4982 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4984 return LDAP_SUCCESS;
4987 static char *extops[] = {
4988 LDAP_EXOP_MODIFY_PASSWD,
4991 #endif /* PCACHE_CONTROL_PRIVDB */
4993 static struct berval pcache_exop_MODIFY_PASSWD = BER_BVC( LDAP_EXOP_MODIFY_PASSWD );
4994 #ifdef PCACHE_EXOP_QUERY_DELETE
4995 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4997 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4998 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4999 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
5002 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
5003 requestName [0] LDAPOID,
5004 requestValue [1] OCTET STRING OPTIONAL }
5006 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
5008 requestValue ::= SEQUENCE { CHOICE {
5010 entryDN [1] LDAPDN },
5011 queryID [2] OCTET STRING (SIZE(16))
5012 -- constrained to UUID }
5014 * Either baseDN or entryDN must be present, to allow database selection.
5016 * 1. if baseDN and queryID are present, then the query corresponding
5017 * to queryID is deleted;
5018 * 2. if baseDN is present and queryID is absent, then all queries
5020 * 3. if entryDN is present and queryID is absent, then all queries
5021 * corresponding to the queryID values present in entryDN are deleted;
5022 * 4. if entryDN and queryID are present, then all queries
5023 * corresponding to the queryID values present in entryDN are deleted,
5024 * but only if the value of queryID is contained in the entry;
5026 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
5027 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
5028 * or by removing the database files.
5030 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
5031 COMPONENTS OF LDAPResult,
5032 responseName [10] LDAPOID OPTIONAL,
5033 responseValue [11] OCTET STRING OPTIONAL }
5035 * responseName and responseValue must be absent.
5039 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
5040 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
5041 * - if ndn != NULL, it is set to the normalized DN in the request
5042 * corresponding to either the baseDN or the entryDN, according
5043 * to *tagp; memory is malloc'ed on the Operation's slab, and must
5044 * be freed by the caller.
5045 * - if uuid != NULL, it is set to point to the normalized UUID;
5046 * memory is malloc'ed on the Operation's slab, and must
5047 * be freed by the caller.
5050 pcache_parse_query_delete(
5054 struct berval *uuid,
5058 int rc = LDAP_SUCCESS;
5061 BerElementBuffer berbuf;
5062 BerElement *ber = (BerElement *)&berbuf;
5063 struct berval reqdata = BER_BVNULL;
5075 if ( in == NULL || in->bv_len == 0 ) {
5076 *text = "empty request data field in queryDelete exop";
5077 return LDAP_PROTOCOL_ERROR;
5080 ber_dupbv_x( &reqdata, in, ctx );
5082 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
5083 ber_init2( ber, &reqdata, 0 );
5085 tag = ber_scanf( ber, "{" /*}*/ );
5087 if ( tag == LBER_ERROR ) {
5088 Debug( LDAP_DEBUG_TRACE,
5089 "pcache_parse_query_delete: decoding error.\n",
5091 goto decoding_error;
5094 tag = ber_peek_tag( ber, &len );
5095 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
5096 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
5100 if ( ndn != NULL ) {
5103 tag = ber_scanf( ber, "m", &dn );
5104 if ( tag == LBER_ERROR ) {
5105 Debug( LDAP_DEBUG_TRACE,
5106 "pcache_parse_query_delete: DN parse failed.\n",
5108 goto decoding_error;
5111 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
5112 if ( rc != LDAP_SUCCESS ) {
5113 *text = "invalid DN in queryDelete exop request data";
5118 tag = ber_scanf( ber, "x" /* "m" */ );
5119 if ( tag == LBER_DEFAULT ) {
5120 goto decoding_error;
5124 tag = ber_peek_tag( ber, &len );
5127 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
5128 if ( uuid != NULL ) {
5130 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
5132 tag = ber_scanf( ber, "m", &bv );
5133 if ( tag == LBER_ERROR ) {
5134 Debug( LDAP_DEBUG_TRACE,
5135 "pcache_parse_query_delete: UUID parse failed.\n",
5137 goto decoding_error;
5140 if ( bv.bv_len != 16 ) {
5141 Debug( LDAP_DEBUG_TRACE,
5142 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5143 (unsigned long)bv.bv_len, 0, 0 );
5144 goto decoding_error;
5147 rc = lutil_uuidstr_from_normalized(
5148 bv.bv_val, bv.bv_len,
5149 uuidbuf, sizeof( uuidbuf ) );
5151 goto decoding_error;
5153 ber_str2bv( uuidbuf, rc, 1, uuid );
5157 tag = ber_skip_tag( ber, &len );
5158 if ( tag == LBER_DEFAULT ) {
5159 goto decoding_error;
5163 Debug( LDAP_DEBUG_TRACE,
5164 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5165 (unsigned long)len, 0, 0 );
5166 goto decoding_error;
5170 tag = ber_peek_tag( ber, &len );
5173 if ( tag != LBER_DEFAULT || len != 0 ) {
5175 Debug( LDAP_DEBUG_TRACE,
5176 "pcache_parse_query_delete: decoding error\n",
5178 rc = LDAP_PROTOCOL_ERROR;
5179 *text = "queryDelete data decoding error";
5182 if ( ndn && !BER_BVISNULL( ndn ) ) {
5183 slap_sl_free( ndn->bv_val, ctx );
5187 if ( uuid && !BER_BVISNULL( uuid ) ) {
5188 slap_sl_free( uuid->bv_val, ctx );
5193 if ( !BER_BVISNULL( &reqdata ) ) {
5194 ber_memfree_x( reqdata.bv_val, ctx );
5201 pcache_exop_query_delete(
5205 BackendDB *bd = op->o_bd;
5207 struct berval uuid = BER_BVNULL,
5209 char buf[ SLAP_TEXT_BUFLEN ];
5211 ber_tag_t tag = LBER_DEFAULT;
5213 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5217 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5218 &tag, &op->o_req_ndn, uuidp,
5219 &rs->sr_text, op->o_tmpmemctx );
5220 if ( rs->sr_err != LDAP_SUCCESS ) {
5224 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5225 assert( !BER_BVISNULL( &op->o_req_ndn ) );
5226 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
5228 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
5229 snprintf( &buf[ len ], sizeof( buf ) - len, " pcacheQueryId=\"%s\"", uuid.bv_val );
5232 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
5233 op->o_log_prefix, buf, 0 );
5235 op->o_req_dn = op->o_req_ndn;
5237 op->o_bd = select_backend( &op->o_req_ndn, 0 );
5238 if ( op->o_bd == NULL ) {
5239 send_ldap_error( op, rs, LDAP_NO_SUCH_OBJECT,
5240 "no global superior knowledge" );
5242 rs->sr_err = backend_check_restrictions( op, rs,
5243 (struct berval *)&pcache_exop_QUERY_DELETE );
5244 if ( rs->sr_err != LDAP_SUCCESS ) {
5248 if ( op->o_bd->be_extended == NULL ) {
5249 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
5250 "backend does not support extended operations" );
5254 op->o_bd->be_extended( op, rs );
5257 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
5258 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
5259 BER_BVZERO( &op->o_req_ndn );
5260 BER_BVZERO( &op->o_req_dn );
5263 if ( !BER_BVISNULL( &uuid ) ) {
5264 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5271 #endif /* PCACHE_EXOP_QUERY_DELETE */
5274 pcache_op_extended( Operation *op, SlapReply *rs )
5276 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5277 cache_manager *cm = on->on_bi.bi_private;
5279 #ifdef PCACHE_CONTROL_PRIVDB
5280 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
5281 return pcache_op_privdb( op, rs );
5283 #endif /* PCACHE_CONTROL_PRIVDB */
5285 #ifdef PCACHE_EXOP_QUERY_DELETE
5286 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
5287 struct berval uuid = BER_BVNULL;
5288 ber_tag_t tag = LBER_DEFAULT;
5290 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5291 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
5292 assert( rs->sr_err == LDAP_SUCCESS );
5294 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
5295 /* remove all queries related to the selected entry */
5296 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
5297 cm, &op->o_req_ndn, &uuid );
5299 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
5300 if ( !BER_BVISNULL( &uuid ) ) {
5301 /* remove the selected query */
5302 rs->sr_err = pcache_remove_query_from_cache( op,
5306 /* TODO: remove all queries */
5307 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
5308 rs->sr_text = "deletion of all queries not implemented";
5312 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5315 #endif /* PCACHE_EXOP_QUERY_DELETE */
5317 /* We only care if we're configured for Bind caching */
5318 if ( bvmatch( &op->ore_reqoid, &pcache_exop_MODIFY_PASSWD ) &&
5320 /* See if the local entry exists and has a password.
5321 * It's too much work to find the matching query, so
5322 * we just see if there's a hashed password to update.
5324 Operation op2 = *op;
5330 op2.o_dn = op->o_bd->be_rootdn;
5331 op2.o_ndn = op->o_bd->be_rootndn;
5332 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL,
5333 slap_schema.si_ad_userPassword, 0, &e );
5334 if ( rc == LDAP_SUCCESS && e ) {
5335 /* See if a recognized password is hashed here */
5336 Attribute *a = attr_find( e->e_attrs,
5337 slap_schema.si_ad_userPassword );
5338 if ( a && a->a_vals[0].bv_val[0] == '{' &&
5339 lutil_passwd_scheme( a->a_vals[0].bv_val )) {
5342 be_entry_release_r( &op2, e );
5346 rc = overlay_op_walk( op, rs, op_extended, on->on_info,
5348 if ( rc == LDAP_SUCCESS ) {
5349 req_pwdexop_s *qpw = &op->oq_pwdexop;
5351 /* We don't care if it succeeds or not */
5352 pc_setpw( &op2, &qpw->rs_new, cm );
5357 return SLAP_CB_CONTINUE;
5361 pcache_entry_release( Operation *op, Entry *e, int rw )
5363 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5364 cache_manager *cm = on->on_bi.bi_private;
5365 BackendDB *db = op->o_bd;
5369 rc = be_entry_release_rw( op, e, rw );
5374 #ifdef PCACHE_MONITOR
5377 pcache_monitor_update(
5383 cache_manager *cm = (cache_manager *) priv;
5384 query_manager *qm = cm->qm;
5387 BerVarray vals = NULL;
5389 attr_delete( &e->e_attrs, ad_cachedQueryURL );
5390 if ( ( SLAP_OPATTRS( rs->sr_attr_flags ) || ad_inlist( ad_cachedQueryURL, rs->sr_attrs ) )
5391 && qm->templates != NULL )
5395 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
5396 for ( qc = tm->query; qc; qc = qc->next ) {
5399 if ( query2url( op, qc, &bv, 1 ) == 0 ) {
5400 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
5406 if ( vals != NULL ) {
5407 attr_merge_normalize( e, ad_cachedQueryURL, vals, NULL );
5408 ber_bvarray_free_x( vals, op->o_tmpmemctx );
5414 char buf[ SLAP_TEXT_BUFLEN ];
5417 /* number of cached queries */
5418 a = attr_find( e->e_attrs, ad_numQueries );
5419 assert( a != NULL );
5422 bv.bv_len = snprintf( buf, sizeof( buf ), "%lu", cm->num_cached_queries );
5424 if ( a->a_nvals != a->a_vals ) {
5425 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5427 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5429 /* number of cached entries */
5430 a = attr_find( e->e_attrs, ad_numEntries );
5431 assert( a != NULL );
5434 bv.bv_len = snprintf( buf, sizeof( buf ), "%d", cm->cur_entries );
5436 if ( a->a_nvals != a->a_vals ) {
5437 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5439 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5442 return SLAP_CB_CONTINUE;
5446 pcache_monitor_free(
5450 struct berval values[ 2 ];
5451 Modification mod = { 0 };
5454 char textbuf[ SLAP_TEXT_BUFLEN ];
5458 /* NOTE: if slap_shutdown != 0, priv might have already been freed */
5461 /* Remove objectClass */
5462 mod.sm_op = LDAP_MOD_DELETE;
5463 mod.sm_desc = slap_schema.si_ad_objectClass;
5464 mod.sm_values = values;
5466 values[ 0 ] = oc_olmPCache->soc_cname;
5467 BER_BVZERO( &values[ 1 ] );
5469 rc = modify_delete_values( e, &mod, 1, &text,
5470 textbuf, sizeof( textbuf ) );
5471 /* don't care too much about return code... */
5474 mod.sm_values = NULL;
5475 mod.sm_desc = ad_cachedQueryURL;
5477 rc = modify_delete_values( e, &mod, 1, &text,
5478 textbuf, sizeof( textbuf ) );
5479 /* don't care too much about return code... */
5482 mod.sm_values = NULL;
5483 mod.sm_desc = ad_numQueries;
5485 rc = modify_delete_values( e, &mod, 1, &text,
5486 textbuf, sizeof( textbuf ) );
5487 /* don't care too much about return code... */
5490 mod.sm_values = NULL;
5491 mod.sm_desc = ad_numEntries;
5493 rc = modify_delete_values( e, &mod, 1, &text,
5494 textbuf, sizeof( textbuf ) );
5495 /* don't care too much about return code... */
5497 return SLAP_CB_CONTINUE;
5501 * call from within pcache_initialize()
5504 pcache_monitor_initialize( void )
5506 static int pcache_monitor_initialized = 0;
5508 if ( backend_info( "monitor" ) == NULL ) {
5512 if ( pcache_monitor_initialized++ ) {
5520 pcache_monitor_db_init( BackendDB *be )
5522 if ( pcache_monitor_initialize() == LDAP_SUCCESS ) {
5523 SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_MONITORING;
5530 pcache_monitor_db_open( BackendDB *be )
5532 slap_overinst *on = (slap_overinst *)be->bd_info;
5533 cache_manager *cm = on->on_bi.bi_private;
5534 Attribute *a, *next;
5535 monitor_callback_t *cb = NULL;
5538 monitor_extra_t *mbe;
5540 if ( !SLAP_DBMONITORING( be ) ) {
5544 mi = backend_info( "monitor" );
5545 if ( !mi || !mi->bi_extra ) {
5546 SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
5551 /* don't bother if monitor is not configured */
5552 if ( !mbe->is_configured() ) {
5553 static int warning = 0;
5555 if ( warning++ == 0 ) {
5556 Debug( LDAP_DEBUG_ANY, "pcache_monitor_db_open: "
5557 "monitoring disabled; "
5558 "configure monitor database to enable\n",
5565 /* alloc as many as required (plus 1 for objectClass) */
5566 a = attrs_alloc( 1 + 2 );
5572 a->a_desc = slap_schema.si_ad_objectClass;
5573 attr_valadd( a, &oc_olmPCache->soc_cname, NULL, 1 );
5577 struct berval bv = BER_BVC( "0" );
5579 next->a_desc = ad_numQueries;
5580 attr_valadd( next, &bv, NULL, 1 );
5581 next = next->a_next;
5583 next->a_desc = ad_numEntries;
5584 attr_valadd( next, &bv, NULL, 1 );
5585 next = next->a_next;
5588 cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
5589 cb->mc_update = pcache_monitor_update;
5590 cb->mc_free = pcache_monitor_free;
5591 cb->mc_private = (void *)cm;
5593 /* make sure the database is registered; then add monitor attributes */
5594 BER_BVZERO( &cm->monitor_ndn );
5595 rc = mbe->register_overlay( be, on, &cm->monitor_ndn );
5597 rc = mbe->register_entry_attrs( &cm->monitor_ndn, a, cb,
5614 /* store for cleanup */
5615 cm->monitor_cb = (void *)cb;
5617 /* we don't need to keep track of the attributes, because
5618 * bdb_monitor_free() takes care of everything */
5627 pcache_monitor_db_close( BackendDB *be )
5629 slap_overinst *on = (slap_overinst *)be->bd_info;
5630 cache_manager *cm = on->on_bi.bi_private;
5632 if ( cm->monitor_cb != NULL ) {
5633 BackendInfo *mi = backend_info( "monitor" );
5634 monitor_extra_t *mbe;
5636 if ( mi && &mi->bi_extra ) {
5638 mbe->unregister_entry_callback( &cm->monitor_ndn,
5639 (monitor_callback_t *)cm->monitor_cb,
5648 pcache_monitor_db_destroy( BackendDB *be )
5653 #endif /* PCACHE_MONITOR */
5655 static slap_overinst pcache;
5657 static char *obsolete_names[] = {
5662 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5664 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
5669 struct berval debugbv = BER_BVC("pcache");
5673 code = slap_loglevel_get( &debugbv, &pcache_debug );
5678 #ifdef PCACHE_CONTROL_PRIVDB
5679 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
5680 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
5681 parse_privdb_ctrl, &privDB_cid );
5682 if ( code != LDAP_SUCCESS ) {
5683 Debug( LDAP_DEBUG_ANY,
5684 "pcache_initialize: failed to register control %s (%d)\n",
5685 PCACHE_CONTROL_PRIVDB, code, 0 );
5688 #endif /* PCACHE_CONTROL_PRIVDB */
5690 #ifdef PCACHE_EXOP_QUERY_DELETE
5691 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
5692 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
5694 if ( code != LDAP_SUCCESS ) {
5695 Debug( LDAP_DEBUG_ANY,
5696 "pcache_initialize: unable to register queryDelete exop: %d.\n",
5700 #endif /* PCACHE_EXOP_QUERY_DELETE */
5702 argv[ 0 ] = "back-bdb/back-hdb monitor";
5707 for ( i = 0; s_oid[ i ].name; i++ ) {
5709 argv[ 1 ] = s_oid[ i ].name;
5710 argv[ 2 ] = s_oid[ i ].oid;
5712 if ( parse_oidm( &c, 0, NULL ) != 0 ) {
5713 Debug( LDAP_DEBUG_ANY, "pcache_initialize: "
5714 "unable to add objectIdentifier \"%s=%s\"\n",
5715 s_oid[ i ].name, s_oid[ i ].oid, 0 );
5720 for ( i = 0; s_ad[i].desc != NULL; i++ ) {
5721 code = register_at( s_ad[i].desc, s_ad[i].adp, 0 );
5723 Debug( LDAP_DEBUG_ANY,
5724 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
5727 (*s_ad[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
5730 for ( i = 0; s_oc[i].desc != NULL; i++ ) {
5731 code = register_oc( s_oc[i].desc, s_oc[i].ocp, 0 );
5733 Debug( LDAP_DEBUG_ANY,
5734 "pcache_initialize: register_oc #%d failed\n", i, 0, 0 );
5737 (*s_oc[i].ocp)->soc_flags |= SLAP_OC_HIDE;
5740 pcache.on_bi.bi_type = "pcache";
5741 pcache.on_bi.bi_obsolete_names = obsolete_names;
5742 pcache.on_bi.bi_db_init = pcache_db_init;
5743 pcache.on_bi.bi_db_config = pcache_db_config;
5744 pcache.on_bi.bi_db_open = pcache_db_open;
5745 pcache.on_bi.bi_db_close = pcache_db_close;
5746 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
5748 pcache.on_bi.bi_op_search = pcache_op_search;
5749 pcache.on_bi.bi_op_bind = pcache_op_bind;
5750 #ifdef PCACHE_CONTROL_PRIVDB
5751 pcache.on_bi.bi_op_compare = pcache_op_privdb;
5752 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
5753 pcache.on_bi.bi_op_modify = pcache_op_privdb;
5754 pcache.on_bi.bi_op_add = pcache_op_privdb;
5755 pcache.on_bi.bi_op_delete = pcache_op_privdb;
5756 #endif /* PCACHE_CONTROL_PRIVDB */
5757 pcache.on_bi.bi_extended = pcache_op_extended;
5759 pcache.on_bi.bi_entry_release_rw = pcache_entry_release;
5760 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
5762 pcache.on_bi.bi_cf_ocs = pcocs;
5764 code = config_register_schema( pccfg, pcocs );
5765 if ( code ) return code;
5767 return overlay_register( &pcache );
5770 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5771 int init_module(int argc, char *argv[]) {
5772 return pcache_initialize();
5776 #endif /* defined(SLAPD_OVER_PROXYCACHE) */