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"
42 * Control that allows to access the private DB
43 * instead of the public one
45 #define PCACHE_CONTROL_PRIVDB "1.3.6.1.4.1.4203.666.11.9.5.1"
48 * Extended Operation that allows to remove a query from the cache
50 #define PCACHE_EXOP_QUERY_DELETE "1.3.6.1.4.1.4203.666.11.9.6.1"
55 #define PCACHE_MONITOR
58 /* query cache structs */
61 typedef struct Query_s {
62 Filter* filter; /* Search Filter */
63 struct berval base; /* Search Base */
64 int scope; /* Search scope */
67 struct query_template_s;
69 typedef struct Qbase_s {
70 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
75 /* struct representing a cached query */
76 typedef struct cached_query_s {
81 struct berval q_uuid; /* query identifier */
83 struct query_template_s *qtemp; /* template of the query */
84 time_t expiry_time; /* time till the query is considered invalid */
85 time_t refresh_time; /* time till the query is refreshed */
86 time_t bindref_time; /* time till the bind is refreshed */
87 int bind_refcnt; /* number of bind operation referencing this query */
88 unsigned long answerable_cnt; /* how many times it was answerable */
89 int refcnt; /* references since last refresh */
90 ldap_pvt_thread_mutex_t answerable_cnt_mutex;
91 struct cached_query_s *next; /* next query in the template */
92 struct cached_query_s *prev; /* previous query in the template */
93 struct cached_query_s *lru_up; /* previous query in the LRU list */
94 struct cached_query_s *lru_down; /* next query in the LRU list */
95 ldap_pvt_thread_rdwr_t rwlock;
101 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>,x-refresh=<refresh>
103 * <base> ::= CachedQuery.qbase->base
104 * <scope> ::= CachedQuery.scope
105 * <filter> ::= filter2bv(CachedQuery.filter)
106 * <uuid> ::= CachedQuery.q_uuid
107 * <attrset> ::= CachedQuery.qtemp->attr_set_index
108 * <expiry> ::= CachedQuery.expiry_time
109 * <refresh> ::= CachedQuery.refresh_time
111 * quick hack: parse URI, call add_query() and then fix
112 * CachedQuery.expiry_time and CachedQuery.q_uuid
114 * NOTE: if the <attrset> changes, all stored URLs will be invalidated.
118 * Represents a set of projected attributes.
122 struct query_template_s *templates;
123 AttributeName* attrs; /* specifies the set */
125 #define PC_CONFIGURED (0x1)
126 #define PC_REFERENCED (0x2)
127 #define PC_GOT_OC (0x4)
128 int count; /* number of attributes */
131 /* struct representing a query template
132 * e.g. template string = &(cn=)(mail=)
134 typedef struct query_template_s {
135 struct query_template_s *qtnext;
136 struct query_template_s *qmnext;
139 CachedQuery* query; /* most recent query cached for the template */
140 CachedQuery* query_last; /* oldest query cached for the template */
141 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
142 struct berval querystr; /* Filter string corresponding to the QT */
143 struct berval bindbase; /* base DN for Bind request */
144 struct berval bindfilterstr; /* Filter string for Bind request */
145 struct berval bindftemp; /* bind filter template */
147 AttributeDescription **bindfattrs; /* attrs to substitute in ftemp */
149 int bindnattrs; /* number of bindfattrs */
151 int attr_set_index; /* determines the projected attributes */
152 int no_of_queries; /* Total number of queries in the template */
153 time_t ttl; /* TTL for the queries of this template */
154 time_t negttl; /* TTL for negative results */
155 time_t limitttl; /* TTL for sizelimit exceeding results */
156 time_t ttr; /* time to refresh */
157 time_t bindttr; /* TTR for cached binds */
158 struct attr_set t_attrs; /* filter attrs + attr_set */
166 } pc_caching_reason_t;
168 static const char *pc_caching_reason_str[] = {
177 struct query_manager_s;
179 /* prototypes for functions for 1) query containment
180 * 2) query addition, 3) cache replacement
182 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
183 Query*, QueryTemplate*);
184 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
185 Query*, QueryTemplate*, pc_caching_reason_t, int wlock);
186 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
188 /* LDAP query cache */
189 typedef struct query_manager_s {
190 struct attr_set* attr_sets; /* possible sets of projected attributes */
191 QueryTemplate* templates; /* cacheable templates */
193 CachedQuery* lru_top; /* top and bottom of LRU list */
194 CachedQuery* lru_bottom;
196 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
198 /* Query cache methods */
199 QCfunc *qcfunc; /* Query containment*/
200 CRfunc *crfunc; /* cache replacement */
201 AddQueryfunc *addfunc; /* add query */
204 /* LDAP query cache manager */
205 typedef struct cache_manager_s {
206 BackendDB db; /* underlying database */
207 unsigned long num_cached_queries; /* total number of cached queries */
208 unsigned long max_queries; /* upper bound on # of cached queries */
209 int save_queries; /* save cached queries across restarts */
210 int check_cacheability; /* check whether a query is cacheable */
211 int numattrsets; /* number of attribute sets */
212 int cur_entries; /* current number of entries cached */
213 int max_entries; /* max number of entries cached */
214 int num_entries_limit; /* max # of entries in a cacheable query */
216 char response_cb; /* install the response callback
217 * at the tail of the callback list */
218 #define PCACHE_RESPONSE_CB_HEAD 0
219 #define PCACHE_RESPONSE_CB_TAIL 1
220 char defer_db_open; /* defer open for online add */
221 char cache_binds; /* cache binds or just passthru */
223 time_t cc_period; /* interval between successive consistency checks (sec) */
224 #define PCACHE_CC_PAUSED 1
225 #define PCACHE_CC_OFFLINE 2
229 ldap_pvt_thread_mutex_t cache_mutex;
231 query_manager* qm; /* query cache managed by the cache manager */
233 #ifdef PCACHE_MONITOR
235 struct berval monitor_ndn;
236 #endif /* PCACHE_MONITOR */
239 #ifdef PCACHE_MONITOR
240 static int pcache_monitor_db_init( BackendDB *be );
241 static int pcache_monitor_db_open( BackendDB *be );
242 static int pcache_monitor_db_close( BackendDB *be );
243 static int pcache_monitor_db_destroy( BackendDB *be );
244 #endif /* PCACHE_MONITOR */
246 static int pcache_debug;
248 #ifdef PCACHE_CONTROL_PRIVDB
249 static int privDB_cid;
250 #endif /* PCACHE_CONTROL_PRIVDB */
252 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
254 #ifdef PCACHE_MONITOR
255 static AttributeDescription *ad_numQueries, *ad_numEntries;
256 static ObjectClass *oc_olmPCache;
257 #endif /* PCACHE_MONITOR */
263 { "PCacheOID", "1.3.6.1.4.1.4203.666.11.9.1" },
264 { "PCacheAttributes", "PCacheOID:1" },
265 { "PCacheObjectClasses", "PCacheOID:2" },
272 AttributeDescription **adp;
274 { "( PCacheAttributes:1 "
275 "NAME 'pcacheQueryID' "
276 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
277 "EQUALITY octetStringMatch "
278 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
279 "NO-USER-MODIFICATION "
280 "USAGE directoryOperation )",
282 { "( PCacheAttributes:2 "
283 "NAME 'pcacheQueryURL' "
284 "DESC 'URI describing a cached query' "
285 "EQUALITY caseExactMatch "
286 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
287 "NO-USER-MODIFICATION "
288 "USAGE directoryOperation )",
289 &ad_cachedQueryURL },
290 #ifdef PCACHE_MONITOR
291 { "( PCacheAttributes:3 "
292 "NAME 'pcacheNumQueries' "
293 "DESC 'Number of cached queries' "
294 "EQUALITY integerMatch "
295 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
296 "NO-USER-MODIFICATION "
297 "USAGE directoryOperation )",
299 { "( PCacheAttributes:4 "
300 "NAME 'pcacheNumEntries' "
301 "DESC 'Number of cached entries' "
302 "EQUALITY integerMatch "
303 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
304 "NO-USER-MODIFICATION "
305 "USAGE directoryOperation )",
307 #endif /* PCACHE_MONITOR */
316 #ifdef PCACHE_MONITOR
317 /* augments an existing object, so it must be AUXILIARY */
318 { "( PCacheObjectClasses:1 "
319 "NAME ( 'olmPCache' ) "
323 "$ pcacheNumQueries "
324 "$ pcacheNumEntries "
327 #endif /* PCACHE_MONITOR */
336 struct berval *fstr );
343 QueryTemplate *templ,
344 pc_caching_reason_t why,
350 struct berval *query_uuid );
353 * Turn a cached query into its URL representation
356 query2url( Operation *op, CachedQuery *q, struct berval *urlbv, int dolock )
358 struct berval bv_scope,
360 char attrset_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
361 expiry_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
362 refresh_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
363 answerable_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
365 ber_len_t attrset_len,
371 ldap_pvt_thread_rdwr_rlock( &q->rwlock );
374 ldap_pvt_scope2bv( q->scope, &bv_scope );
375 filter2bv_x( op, q->filter, &bv_filter );
376 attrset_len = sprintf( attrset_buf,
377 "%lu", (unsigned long)q->qtemp->attr_set_index );
378 expiry_len = sprintf( expiry_buf,
379 "%lu", (unsigned long)q->expiry_time );
380 answerable_len = snprintf( answerable_buf, sizeof( answerable_buf ),
381 "%lu", q->answerable_cnt );
382 if ( q->refresh_time )
383 refresh_len = sprintf( refresh_buf,
384 "%lu", (unsigned long)q->refresh_time );
388 urlbv->bv_len = STRLENOF( "ldap:///" )
389 + q->qbase->base.bv_len
394 + STRLENOF( "?x-uuid=" )
396 + STRLENOF( ",x-attrset=" )
398 + STRLENOF( ",x-expiry=" )
400 + STRLENOF( ",x-answerable=" )
403 urlbv->bv_len += STRLENOF( ",x-refresh=" )
406 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
407 ptr = lutil_strcopy( ptr, "ldap:///" );
408 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
409 ptr = lutil_strcopy( ptr, "??" );
410 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
411 ptr = lutil_strcopy( ptr, "?" );
412 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
413 ptr = lutil_strcopy( ptr, "?x-uuid=" );
414 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
415 ptr = lutil_strcopy( ptr, ",x-attrset=" );
416 ptr = lutil_strcopy( ptr, attrset_buf );
417 ptr = lutil_strcopy( ptr, ",x-expiry=" );
418 ptr = lutil_strcopy( ptr, expiry_buf );
419 ptr = lutil_strcopy( ptr, ",x-answerable=" );
420 ptr = lutil_strcopy( ptr, answerable_buf );
422 ptr = lutil_strcopy( ptr, ",x-refresh=" );
423 ptr = lutil_strcopy( ptr, refresh_buf );
426 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
429 ldap_pvt_thread_rdwr_runlock( &q->rwlock );
435 /* Find and record the empty filter clauses */
438 ftemp_attrs( struct berval *ftemp, struct berval *template,
439 AttributeDescription ***ret, const char **text )
445 AttributeDescription *ad;
446 AttributeDescription **descs = NULL;
449 temp2 = ch_malloc( ftemp->bv_len + 1 );
456 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' )
459 p2 = strchr( p1, '=' );
468 AC_MEMCPY( t1, p1, i );
472 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
476 i = slap_bv2ad( &bv, &ad, text );
482 if ( *p2 == '<' || *p2 == '>' ) p2++;
483 if ( p2[1] != ')' ) {
485 while ( *p2 != ')' ) p2++;
490 descs = (AttributeDescription **)ch_realloc(descs,
491 (attr_cnt + 2)*sizeof(AttributeDescription *));
493 descs[attr_cnt++] = ad;
498 descs[attr_cnt] = NULL;
500 template->bv_val = temp2;
501 template->bv_len = t1 - temp2;
506 template_attrs( char *template, struct attr_set *set, AttributeName **ret,
517 AttributeDescription *ad;
518 AttributeName *attrs;
524 attrs = ch_calloc( set->count + 1, sizeof(AttributeName) );
525 for ( i=0; i < set->count; i++ )
526 attrs[i] = set->attrs[i];
528 alluser = an_find( attrs, slap_bv_all_user_attrs );
529 allop = an_find( attrs, slap_bv_all_operational_attrs );
532 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' ) p1++;
533 p2 = strchr( p1, '=' );
536 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
540 i = slap_bv2ad( &bv, &ad, text );
547 if ( ad == slap_schema.si_ad_objectClass )
550 if ( is_at_operational(ad->ad_type)) {
554 } else if ( alluser ) {
557 if ( !ad_inlist( ad, attrs )) {
558 attrs = (AttributeName *)ch_realloc(attrs,
559 (attr_cnt + 2)*sizeof(AttributeName));
561 attrs[attr_cnt].an_desc = ad;
562 attrs[attr_cnt].an_name = ad->ad_cname;
563 attrs[attr_cnt].an_oc = NULL;
564 attrs[attr_cnt].an_flags = 0;
565 BER_BVZERO( &attrs[attr_cnt+1].an_name );
573 *text = "couldn't parse template";
577 if ( !got_oc && !( set->flags & PC_GOT_OC )) {
578 attrs = (AttributeName *)ch_realloc(attrs,
579 (attr_cnt + 2)*sizeof(AttributeName));
581 ad = slap_schema.si_ad_objectClass;
582 attrs[attr_cnt].an_desc = ad;
583 attrs[attr_cnt].an_name = ad->ad_cname;
584 attrs[attr_cnt].an_oc = NULL;
585 attrs[attr_cnt].an_flags = 0;
586 BER_BVZERO( &attrs[attr_cnt+1].an_name );
594 * Turn an URL representing a formerly cached query into a cached query,
595 * and try to cache it
606 LDAPURLDesc *lud = NULL;
608 tempstr = BER_BVNULL,
613 unsigned long answerable_cnt;
616 #define GOT_UUID 0x1U
617 #define GOT_ATTRSET 0x2U
618 #define GOT_EXPIRY 0x4U
619 #define GOT_ANSWERABLE 0x8U
620 #define GOT_REFRESH 0x10U
621 #define GOT_ALL (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
624 rc = ldap_url_parse( url, &lud );
625 if ( rc != LDAP_URL_SUCCESS ) {
629 /* non-allowed fields */
630 if ( lud->lud_host != NULL ) {
635 if ( lud->lud_attrs != NULL ) {
641 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
646 /* required fields */
647 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
652 switch ( lud->lud_scope ) {
653 case LDAP_SCOPE_BASE:
654 case LDAP_SCOPE_ONELEVEL:
655 case LDAP_SCOPE_SUBTREE:
656 case LDAP_SCOPE_SUBORDINATE:
664 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
669 if ( lud->lud_exts == NULL ) {
674 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
675 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
676 struct berval tmpUUID;
677 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
679 if ( got & GOT_UUID ) {
684 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
685 if ( !BER_BVISEMPTY( &tmpUUID ) ) {
686 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
687 if ( rc != LDAP_SUCCESS ) {
693 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
694 if ( got & GOT_ATTRSET ) {
699 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
705 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
708 if ( got & GOT_EXPIRY ) {
713 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
717 expiry_time = (time_t)l;
720 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
721 if ( got & GOT_ANSWERABLE ) {
726 rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
730 got |= GOT_ANSWERABLE;
732 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
735 if ( got & GOT_REFRESH ) {
740 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
744 refresh_time = (time_t)l;
753 if ( got != GOT_ALL ) {
758 if ( !(got & GOT_REFRESH ))
761 /* ignore expired queries */
762 if ( expiry_time <= slap_get_time()) {
765 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
767 (void)remove_query_data( &op2, &uuid );
772 ber_str2bv( lud->lud_dn, 0, 0, &base );
773 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
774 if ( rc != LDAP_SUCCESS ) {
777 query.scope = lud->lud_scope;
778 query.filter = str2filter( lud->lud_filter );
779 if ( query.filter == NULL ) {
784 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
786 if ( filter2template( op, query.filter, &tempstr ) ) {
787 ch_free( tempstr.bv_val );
792 /* check for query containment */
793 qt = qm->attr_sets[attrset].templates;
794 for ( ; qt; qt = qt->qtnext ) {
795 /* find if template i can potentially answer tempstr */
796 if ( bvmatch( &qt->querystr, &tempstr ) ) {
806 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
808 cq->expiry_time = expiry_time;
809 cq->refresh_time = refresh_time;
811 cq->answerable_cnt = answerable_cnt;
814 /* it's now into cq->filter */
824 if ( query.filter != NULL ) filter_free( query.filter );
825 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
826 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
827 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
828 if ( lud != NULL ) ldap_free_urldesc( lud );
833 /* Return 1 for an added entry, else 0 */
839 struct berval* query_uuid )
842 Modifications* modlist = NULL;
843 const char* text = NULL;
845 char textbuf[SLAP_TEXT_BUFLEN];
846 size_t textlen = sizeof(textbuf);
848 SlapReply sreply = {REP_RESULT};
850 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
857 /* add queryId attribute */
858 attr_merge_one( e, ad_queryId, query_uuid, NULL );
860 /* append the attribute list from the fetched entry */
861 e->e_attrs->a_next = attr;
863 op->o_tag = LDAP_REQ_ADD;
864 op->o_protocol = LDAP_VERSION3;
865 op->o_callback = &cb;
866 op->o_time = slap_get_time();
867 op->o_do_not_cache = 1;
870 op->o_req_dn = e->e_name;
871 op->o_req_ndn = e->e_nname;
872 rc = op->o_bd->be_add( op, &sreply );
874 if ( rc != LDAP_SUCCESS ) {
875 if ( rc == LDAP_ALREADY_EXISTS ) {
876 rs_reinit( &sreply, REP_RESULT );
877 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
878 modlist->sml_op = LDAP_MOD_ADD;
879 op->o_tag = LDAP_REQ_MODIFY;
880 op->orm_modlist = modlist;
881 op->o_managedsait = SLAP_CONTROL_CRITICAL;
882 op->o_bd->be_modify( op, &sreply );
883 slap_mods_free( modlist, 1 );
884 } else if ( rc == LDAP_REFERRAL ||
885 rc == LDAP_NO_SUCH_OBJECT ) {
886 syncrepl_add_glue( op, e );
895 if ( op->ora_e == e )
903 /* Length-ordered sort on normalized DNs */
904 static int pcache_dn_cmp( const void *v1, const void *v2 )
906 const Qbase *q1 = v1, *q2 = v2;
908 int rc = q1->base.bv_len - q2->base.bv_len;
910 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
914 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
917 dif = bv1->bv_len - bv2->bv_len;
919 if ( dif > 0 ) len -= dif;
920 len = memcmp( bv1->bv_val, bv2->bv_val, len );
926 /* compare the current value in each filter */
927 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
929 int rc, weight1, weight2;
931 switch( f1->f_choice ) {
932 case LDAP_FILTER_AND:
936 case LDAP_FILTER_PRESENT:
939 case LDAP_FILTER_EQUALITY:
947 switch( f2->f_choice ) {
948 case LDAP_FILTER_AND:
952 case LDAP_FILTER_PRESENT:
955 case LDAP_FILTER_EQUALITY:
963 rc = weight1 - weight2;
967 rc = pcache_filter_cmp( f1->f_and, f2->f_and );
972 rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
975 if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
977 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
978 if ( !BER_BVISNULL( &f2->f_sub_initial )) {
979 rc = lex_bvcmp( &f1->f_sub_initial,
980 &f2->f_sub_initial );
984 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
988 if ( f1->f_sub_any ) {
989 if ( f2->f_sub_any ) {
990 rc = lex_bvcmp( f1->f_sub_any,
995 } else if ( f2->f_sub_any ) {
999 if ( !BER_BVISNULL( &f1->f_sub_final )) {
1000 if ( !BER_BVISNULL( &f2->f_sub_final )) {
1001 rc = lex_bvcmp( &f1->f_sub_final,
1006 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
1010 rc = lex_bvcmp( &f1->f_mr_value,
1024 rc = pcache_filter_cmp( f1, f2 );
1034 /* compare filters in each query */
1035 static int pcache_query_cmp( const void *v1, const void *v2 )
1037 const CachedQuery *q1 = v1, *q2 =v2;
1038 return pcache_filter_cmp( q1->filter, q2->filter );
1041 /* add query on top of LRU list */
1043 add_query_on_top (query_manager* qm, CachedQuery* qc)
1045 CachedQuery* top = qm->lru_top;
1052 qm->lru_bottom = qc;
1056 Debug( pcache_debug, "Base of added query = %s\n",
1057 qc->qbase->base.bv_val, 0, 0 );
1060 /* remove_query from LRU list */
1063 remove_query (query_manager* qm, CachedQuery* qc)
1072 down = qc->lru_down;
1078 qm->lru_bottom = up;
1084 up->lru_down = down;
1086 qc->lru_up = qc->lru_down = NULL;
1089 /* find and remove string2 from string1
1090 * from start if position = 1,
1091 * from end if position = 3,
1092 * from anywhere if position = 2
1093 * string1 is overwritten if position = 2.
1097 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
1101 if ( !ber2->bv_val )
1103 if ( !ber1->bv_val )
1106 switch( position ) {
1108 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
1109 ber2->bv_val, ber2->bv_len )) {
1111 ber1->bv_val += ber2->bv_len;
1112 ber1->bv_len -= ber2->bv_len;
1117 ber1->bv_val[ber1->bv_len] = '\0';
1118 temp = strstr( ber1->bv_val, ber2->bv_val );
1120 strcpy( temp, temp+ber2->bv_len );
1121 ber1->bv_len -= ber2->bv_len;
1127 if ( ber1->bv_len >= ber2->bv_len &&
1128 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
1131 ber1->bv_len -= ber2->bv_len;
1139 static struct berval*
1140 merge_init_final(Operation *op, struct berval* init, struct berval* any,
1141 struct berval* final)
1143 struct berval* merged, *temp;
1144 int i, any_count, count;
1146 for (any_count=0; any && any[any_count].bv_val; any_count++)
1156 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
1161 ber_dupbv_x( temp, init, op->o_tmpmemctx );
1165 for (i=0; i<any_count; i++) {
1166 ber_dupbv_x( temp, any, op->o_tmpmemctx );
1171 ber_dupbv_x( temp, final, op->o_tmpmemctx );
1178 /* Each element in stored must be found in incoming. Incoming is overwritten.
1181 strings_containment(struct berval* stored, struct berval* incoming)
1183 struct berval* element;
1187 for ( element=stored; element->bv_val != NULL; element++ ) {
1188 for (j = k; incoming[j].bv_val != NULL; j++) {
1189 if (find_and_remove(&(incoming[j]), element, 2)) {
1206 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
1210 struct berval init_incoming;
1211 struct berval final_incoming;
1212 struct berval *remaining_incoming = NULL;
1214 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
1215 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
1218 init_incoming = incoming->f_sub_initial;
1219 final_incoming = incoming->f_sub_final;
1221 if (find_and_remove(&init_incoming,
1222 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
1223 &(stored->f_sub_final), 3))
1225 if (stored->f_sub_any == NULL) {
1229 remaining_incoming = merge_init_final(op, &init_incoming,
1230 incoming->f_sub_any, &final_incoming);
1231 rc = strings_containment(stored->f_sub_any, remaining_incoming);
1232 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
1239 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
1241 struct berval incoming_val[2];
1244 incoming_val[1] = incoming->f_av_value;
1246 if (find_and_remove(incoming_val+1,
1247 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
1248 &(stored->f_sub_final), 3)) {
1249 if (stored->f_sub_any == NULL){
1253 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
1254 BER_BVZERO( incoming_val+1 );
1255 rc = strings_containment(stored->f_sub_any, incoming_val);
1256 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1263 filter_first( Filter *f )
1265 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1270 typedef struct fstack {
1271 struct fstack *fs_next;
1276 static CachedQuery *
1277 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
1281 MatchingRule* mrule = NULL;
1282 int res=0, eqpass= 0;
1285 CachedQuery cq, *qc;
1286 fstack *stack = NULL, *fsp;
1291 /* substring matches sort to the end, and we just have to
1292 * walk the entire list.
1294 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1295 ptr = tavl_end( root, 1 );
1296 dir = TAVL_DIR_LEFT;
1298 ptr = tavl_find3( root, &cq, pcache_query_cmp, &ret );
1299 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1308 /* an incoming substr query can only be satisfied by a cached
1311 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1312 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1315 /* an incoming eq query can be satisfied by a cached eq or substr
1318 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1319 if ( eqpass == 0 ) {
1320 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1321 nextpass: eqpass = 1;
1322 ptr = tavl_end( root, 1 );
1323 dir = TAVL_DIR_LEFT;
1327 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1333 switch (fs->f_choice) {
1334 case LDAP_FILTER_EQUALITY:
1335 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1336 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1340 case LDAP_FILTER_GE:
1341 case LDAP_FILTER_LE:
1342 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1349 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1350 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1351 &(fi->f_ava->aa_value),
1352 &(fs->f_ava->aa_value), &text);
1353 if (rc != LDAP_SUCCESS) {
1356 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1359 switch (fs->f_choice) {
1360 case LDAP_FILTER_OR:
1361 case LDAP_FILTER_AND:
1363 /* save our stack position */
1364 fsp = op->o_tmpalloc(sizeof(fstack), op->o_tmpmemctx);
1365 fsp->fs_next = stack;
1366 fsp->fs_fs = fs->f_next;
1367 fsp->fs_fi = fi->f_next;
1374 case LDAP_FILTER_SUBSTRINGS:
1375 /* check if the equality query can be
1376 * answered with cached substring query */
1377 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1378 && substr_containment_equality( op,
1381 /* check if the substring query can be
1382 * answered with cached substring query */
1383 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1384 ) && substr_containment_substr( op,
1390 case LDAP_FILTER_PRESENT:
1395 case LDAP_FILTER_EQUALITY:
1401 case LDAP_FILTER_GE:
1402 if (mrule && ret >= 0)
1407 case LDAP_FILTER_LE:
1408 if (mrule && ret <= 0)
1413 case LDAP_FILTER_NOT:
1419 if (!fs && !fi && stack) {
1422 stack = fsp->fs_next;
1425 op->o_tmpfree(fsp, op->o_tmpmemctx);
1427 } while((res) && (fi != NULL) && (fs != NULL));
1431 ptr = tavl_next( ptr, dir );
1436 /* check whether query is contained in any of
1437 * the cached queries in template
1439 static CachedQuery *
1440 query_containment(Operation *op, query_manager *qm,
1442 QueryTemplate *templa)
1445 int depth = 0, tscope;
1446 Qbase qbase, *qbptr = NULL;
1449 if (query->filter != NULL) {
1452 Debug( pcache_debug, "Lock QC index = %p\n",
1453 (void *) templa, 0, 0 );
1454 qbase.base = query->base;
1456 first = filter_first( query->filter );
1458 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1461 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1463 tscope = query->scope;
1464 /* Find a matching scope:
1465 * match at depth 0 OK
1468 * subord at depth > 0 OK
1469 * subtree at any depth OK
1471 * subtree or subord at any depth OK
1473 * subtree or subord at any depth OK
1475 * subord at depth > 0 OK
1476 * subtree at any depth OK
1478 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1479 switch ( query->scope ) {
1480 case LDAP_SCOPE_BASE:
1481 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1482 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1483 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1485 case LDAP_SCOPE_ONE:
1486 if ( tscope == LDAP_SCOPE_BASE )
1487 tscope = LDAP_SCOPE_ONE;
1488 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1489 if ( !depth ) break;
1490 if ( tscope < LDAP_SCOPE_SUBTREE )
1491 tscope = LDAP_SCOPE_SUBTREE;
1493 case LDAP_SCOPE_SUBTREE:
1494 if ( tscope < LDAP_SCOPE_SUBTREE )
1495 tscope = LDAP_SCOPE_SUBTREE;
1496 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1498 case LDAP_SCOPE_CHILDREN:
1499 if ( tscope < LDAP_SCOPE_SUBTREE )
1500 tscope = LDAP_SCOPE_SUBTREE;
1503 if ( !qbptr->scopes[tscope] ) continue;
1506 qc = find_filter( op, qbptr->scopes[tscope],
1507 query->filter, first );
1509 if ( qc->q_sizelimit ) {
1510 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1513 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1514 if (qm->lru_top != qc) {
1515 remove_query(qm, qc);
1516 add_query_on_top(qm, qc);
1518 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1523 if ( be_issuffix( op->o_bd, &qbase.base ))
1526 dnParent( &qbase.base, &pdn );
1531 Debug( pcache_debug,
1532 "Not answerable: Unlock QC index=%p\n",
1533 (void *) templa, 0, 0 );
1534 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1540 free_query (CachedQuery* qc)
1542 free(qc->q_uuid.bv_val);
1543 filter_free(qc->filter);
1544 ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1545 ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1546 memset(qc, 0, sizeof(*qc));
1551 /* Add query to query cache, the returned Query is locked for writing */
1552 static CachedQuery *
1557 QueryTemplate *templ,
1558 pc_caching_reason_t why,
1561 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1565 time_t ttl = 0, ttr = 0;
1568 new_cached_query->qtemp = templ;
1569 BER_BVZERO( &new_cached_query->q_uuid );
1570 new_cached_query->q_sizelimit = 0;
1572 now = slap_get_time();
1577 ttr = now + templ->ttr;
1581 ttl = templ->negttl;
1585 ttl = templ->limitttl;
1592 new_cached_query->expiry_time = now + ttl;
1593 new_cached_query->refresh_time = ttr;
1594 new_cached_query->bindref_time = 0;
1596 new_cached_query->bind_refcnt = 0;
1597 new_cached_query->answerable_cnt = 0;
1598 new_cached_query->refcnt = 1;
1599 ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1601 new_cached_query->lru_up = NULL;
1602 new_cached_query->lru_down = NULL;
1603 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1604 (long) new_cached_query->expiry_time,
1605 pc_caching_reason_str[ why ], 0 );
1607 new_cached_query->scope = query->scope;
1608 new_cached_query->filter = query->filter;
1609 new_cached_query->first = first = filter_first( query->filter );
1611 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1613 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1615 qb.base = query->base;
1617 /* Adding a query */
1618 Debug( pcache_debug, "Lock AQ index = %p\n",
1619 (void *) templ, 0, 0 );
1620 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1621 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1623 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1624 qbase->base.bv_len = qb.base.bv_len;
1625 qbase->base.bv_val = (char *)(qbase+1);
1626 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1627 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1628 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1630 new_cached_query->next = templ->query;
1631 new_cached_query->prev = NULL;
1632 new_cached_query->qbase = qbase;
1633 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1634 pcache_query_cmp, avl_dup_error );
1637 if (templ->query == NULL)
1638 templ->query_last = new_cached_query;
1640 templ->query->prev = new_cached_query;
1641 templ->query = new_cached_query;
1642 templ->no_of_queries++;
1644 ldap_pvt_thread_mutex_destroy(&new_cached_query->answerable_cnt_mutex);
1646 ldap_pvt_thread_rdwr_wunlock(&new_cached_query->rwlock);
1647 ldap_pvt_thread_rdwr_destroy( &new_cached_query->rwlock );
1648 ch_free( new_cached_query );
1649 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1650 query->filter, first );
1651 filter_free( query->filter );
1652 query->filter = NULL;
1654 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1655 (void *) templ, templ->no_of_queries, 0 );
1657 /* Adding on top of LRU list */
1659 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1660 add_query_on_top(qm, new_cached_query);
1661 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1663 Debug( pcache_debug, "Unlock AQ index = %p \n",
1664 (void *) templ, 0, 0 );
1665 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1667 return rc == 0 ? new_cached_query : NULL;
1671 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1673 if (!qc->prev && !qc->next) {
1674 template->query_last = template->query = NULL;
1675 } else if (qc->prev == NULL) {
1676 qc->next->prev = NULL;
1677 template->query = qc->next;
1678 } else if (qc->next == NULL) {
1679 qc->prev->next = NULL;
1680 template->query_last = qc->prev;
1682 qc->next->prev = qc->prev;
1683 qc->prev->next = qc->next;
1685 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1686 qc->qbase->queries--;
1687 if ( qc->qbase->queries == 0 ) {
1688 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1689 ch_free( qc->qbase );
1693 template->no_of_queries--;
1696 /* remove bottom query of LRU list from the query cache */
1698 * NOTE: slight change in functionality.
1700 * - if result->bv_val is NULL, the query at the bottom of the LRU
1702 * - otherwise, the query whose UUID is *result is removed
1703 * - if not found, result->bv_val is zeroed
1706 cache_replacement(query_manager* qm, struct berval *result)
1708 CachedQuery* bottom;
1709 QueryTemplate *temp;
1711 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1712 if ( BER_BVISNULL( result ) ) {
1713 bottom = qm->lru_bottom;
1716 Debug ( pcache_debug,
1717 "Cache replacement invoked without "
1718 "any query in LRU list\n", 0, 0, 0 );
1719 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1724 for ( bottom = qm->lru_bottom;
1726 bottom = bottom->lru_up )
1728 if ( bvmatch( result, &bottom->q_uuid ) ) {
1734 Debug ( pcache_debug,
1735 "Could not find query with uuid=\"%s\""
1736 "in LRU list\n", result->bv_val, 0, 0 );
1737 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1738 BER_BVZERO( result );
1743 temp = bottom->qtemp;
1744 remove_query(qm, bottom);
1745 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1747 *result = bottom->q_uuid;
1748 BER_BVZERO( &bottom->q_uuid );
1750 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1751 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1752 remove_from_template(bottom, temp);
1753 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1754 (void *) temp, temp->no_of_queries, 0 );
1755 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1756 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1761 struct query_info *next;
1773 struct query_info *qi;
1776 if ( rs->sr_type != REP_SEARCH ) return 0;
1778 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1779 if ( attr == NULL ) return 0;
1781 count = attr->a_numvals;
1782 assert( count > 0 );
1783 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1784 qi->next = op->o_callback->sc_private;
1785 op->o_callback->sc_private = qi;
1786 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1787 qi->del = ( count == 1 );
1795 struct berval *query_uuid )
1797 struct query_info *qi, *qnext;
1798 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
1799 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1800 Filter filter = {LDAP_FILTER_EQUALITY};
1801 SlapReply sreply = {REP_RESULT};
1802 slap_callback cb = { NULL, remove_func, NULL, NULL };
1805 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1806 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1807 filter.f_ava = &ava;
1808 filter.f_av_desc = ad_queryId;
1809 filter.f_av_value = *query_uuid;
1811 op->o_tag = LDAP_REQ_SEARCH;
1812 op->o_protocol = LDAP_VERSION3;
1813 op->o_callback = &cb;
1814 op->o_time = slap_get_time();
1815 op->o_do_not_cache = 1;
1817 op->o_req_dn = op->o_bd->be_suffix[0];
1818 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1819 op->ors_scope = LDAP_SCOPE_SUBTREE;
1820 op->ors_deref = LDAP_DEREF_NEVER;
1821 op->ors_slimit = SLAP_NO_LIMIT;
1822 op->ors_tlimit = SLAP_NO_LIMIT;
1823 op->ors_limit = NULL;
1824 op->ors_filter = &filter;
1825 op->ors_filterstr.bv_val = filter_str;
1826 op->ors_filterstr.bv_len = strlen(filter_str);
1827 op->ors_attrs = NULL;
1828 op->ors_attrsonly = 0;
1830 op->o_bd->be_search( op, &sreply );
1832 for ( qi=cb.sc_private; qi; qi=qnext ) {
1835 op->o_req_dn = qi->xdn;
1836 op->o_req_ndn = qi->xdn;
1837 rs_reinit( &sreply, REP_RESULT );
1840 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1841 query_uuid->bv_val, 0, 0 );
1843 op->o_tag = LDAP_REQ_DELETE;
1845 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1851 struct berval vals[2];
1853 vals[0] = *query_uuid;
1854 vals[1].bv_val = NULL;
1856 mod.sml_op = LDAP_MOD_DELETE;
1858 mod.sml_desc = ad_queryId;
1859 mod.sml_type = ad_queryId->ad_cname;
1860 mod.sml_values = vals;
1861 mod.sml_nvalues = NULL;
1862 mod.sml_numvals = 1;
1863 mod.sml_next = NULL;
1864 Debug( pcache_debug,
1865 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1866 query_uuid->bv_val, 0, 0 );
1868 op->orm_modlist = &mod;
1870 op->o_bd->be_modify( op, &sreply );
1872 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1873 op->o_tmpfree( qi, op->o_tmpmemctx );
1880 AttributeName* attrs,
1889 struct berval *fstr )
1891 AttributeDescription *ad;
1894 switch ( f->f_choice ) {
1895 case LDAP_FILTER_EQUALITY:
1897 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1898 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1899 assert( ret == len );
1900 fstr->bv_len += len;
1903 case LDAP_FILTER_GE:
1905 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1906 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1907 assert( ret == len );
1908 fstr->bv_len += len;
1911 case LDAP_FILTER_LE:
1913 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1914 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1915 assert( ret == len );
1916 fstr->bv_len += len;
1919 case LDAP_FILTER_APPROX:
1921 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1922 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1923 assert( ret == len );
1924 fstr->bv_len += len;
1927 case LDAP_FILTER_SUBSTRINGS:
1929 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1930 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1931 assert( ret == len );
1932 fstr->bv_len += len;
1935 case LDAP_FILTER_PRESENT:
1937 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1938 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1939 assert( ret == len );
1940 fstr->bv_len += len;
1943 case LDAP_FILTER_AND:
1944 case LDAP_FILTER_OR:
1945 case LDAP_FILTER_NOT: {
1947 fstr->bv_val[fstr->bv_len++] = '(';
1948 switch ( f->f_choice ) {
1949 case LDAP_FILTER_AND:
1950 fstr->bv_val[fstr->bv_len] = '&';
1952 case LDAP_FILTER_OR:
1953 fstr->bv_val[fstr->bv_len] = '|';
1955 case LDAP_FILTER_NOT:
1956 fstr->bv_val[fstr->bv_len] = '!';
1961 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1962 rc = filter2template( op, f, fstr );
1965 fstr->bv_val[fstr->bv_len++] = ')';
1966 fstr->bv_val[fstr->bv_len] = '\0';
1972 /* a filter should at least have room for "()",
1973 * an "=" and for a 1-char attr */
1974 strcpy( fstr->bv_val, "(?=)" );
1975 fstr->bv_len += STRLENOF("(?=)");
1982 #define BI_HASHED 0x01
1983 #define BI_DIDCB 0x02
1984 #define BI_LOOKUP 0x04
1988 typedef struct bindinfo {
1989 cache_manager *bi_cm;
1991 QueryTemplate *bi_templ;
1992 struct search_info *bi_si;
1994 slap_callback bi_cb;
1997 struct search_info {
2000 QueryTemplate *qtemp;
2001 AttributeName* save_attrs; /* original attributes, saved for response */
2002 int swap_saved_attrs;
2007 int slimit_exceeded;
2008 pc_caching_reason_t caching_reason;
2014 remove_query_and_data(
2017 struct berval *uuid )
2019 query_manager* qm = cm->qm;
2021 qm->crfunc( qm, uuid );
2022 if ( !BER_BVISNULL( uuid ) ) {
2025 Debug( pcache_debug,
2026 "Removing query UUID %s\n",
2027 uuid->bv_val, 0, 0 );
2028 return_val = remove_query_data( op, uuid );
2029 Debug( pcache_debug,
2030 "QUERY REMOVED, SIZE=%d\n",
2032 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
2033 cm->cur_entries -= return_val;
2034 cm->num_cached_queries--;
2035 Debug( pcache_debug,
2036 "STORED QUERIES = %lu\n",
2037 cm->num_cached_queries, 0, 0 );
2038 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
2039 Debug( pcache_debug,
2040 "QUERY REMOVED, CACHE ="
2042 cm->cur_entries, 0, 0 );
2047 * Callback used to fetch queryId values based on entryUUID;
2048 * used by pcache_remove_entries_from_cache()
2051 fetch_queryId_cb( Operation *op, SlapReply *rs )
2055 /* only care about searchEntry responses */
2056 if ( rs->sr_type != REP_SEARCH ) {
2060 /* allow only one response per entryUUID */
2061 if ( op->o_callback->sc_private != NULL ) {
2067 /* copy all queryId values into callback's private data */
2068 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2070 BerVarray vals = NULL;
2072 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
2073 op->o_callback->sc_private = (void *)vals;
2077 /* clear entry if required */
2078 rs_flush_entry( op, rs, (slap_overinst *) op->o_bd->bd_info );
2084 * Call that allows to remove a set of entries from the cache,
2085 * by forcing the removal of all the related queries.
2088 pcache_remove_entries_from_cache(
2091 BerVarray entryUUIDs )
2093 Connection conn = { 0 };
2094 OperationBuffer opbuf;
2096 slap_callback sc = { 0 };
2098 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
2099 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2100 AttributeName attrs[ 2 ] = {{{ 0 }}};
2104 void *thrctx = ldap_pvt_thread_pool_context();
2106 connection_fake_init( &conn, &opbuf, thrctx );
2114 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2115 op->ors_scope = LDAP_SCOPE_SUBTREE;
2116 op->ors_deref = LDAP_DEREF_NEVER;
2117 f.f_choice = LDAP_FILTER_EQUALITY;
2119 ava.aa_desc = slap_schema.si_ad_entryUUID;
2120 op->ors_filter = &f;
2122 op->ors_tlimit = SLAP_NO_LIMIT;
2123 op->ors_limit = NULL;
2124 attrs[ 0 ].an_desc = ad_queryId;
2125 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2126 op->ors_attrs = attrs;
2127 op->ors_attrsonly = 0;
2129 op->o_req_dn = cm->db.be_suffix[ 0 ];
2130 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2132 op->o_tag = LDAP_REQ_SEARCH;
2133 op->o_protocol = LDAP_VERSION3;
2134 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2136 op->o_dn = op->o_bd->be_rootdn;
2137 op->o_ndn = op->o_bd->be_rootndn;
2138 sc.sc_response = fetch_queryId_cb;
2139 op->o_callback = ≻
2141 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
2142 BerVarray vals = NULL;
2143 SlapReply rs = { REP_RESULT };
2145 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
2146 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
2147 op->ors_filterstr.bv_val = filtbuf;
2148 ava.aa_value = entryUUIDs[ s ];
2150 rc = op->o_bd->be_search( op, &rs );
2151 if ( rc != LDAP_SUCCESS ) {
2155 vals = (BerVarray)op->o_callback->sc_private;
2156 if ( vals != NULL ) {
2159 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2160 struct berval val = vals[ i ];
2162 remove_query_and_data( op, cm, &val );
2164 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2165 ch_free( val.bv_val );
2169 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2170 op->o_callback->sc_private = NULL;
2178 * Call that allows to remove a query from the cache.
2181 pcache_remove_query_from_cache(
2184 struct berval *queryid )
2186 Operation op2 = *op;
2190 /* remove the selected query */
2191 remove_query_and_data( &op2, cm, queryid );
2193 return LDAP_SUCCESS;
2197 * Call that allows to remove a set of queries related to an entry
2198 * from the cache; if queryid is not null, the entry must belong to
2199 * the query indicated by queryid.
2202 pcache_remove_entry_queries_from_cache(
2206 struct berval *queryid )
2208 Connection conn = { 0 };
2209 OperationBuffer opbuf;
2211 slap_callback sc = { 0 };
2212 SlapReply rs = { REP_RESULT };
2214 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
2215 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2216 AttributeName attrs[ 2 ] = {{{ 0 }}};
2219 BerVarray vals = NULL;
2222 void *thrctx = ldap_pvt_thread_pool_context();
2224 connection_fake_init( &conn, &opbuf, thrctx );
2232 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2233 op->ors_scope = LDAP_SCOPE_BASE;
2234 op->ors_deref = LDAP_DEREF_NEVER;
2235 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
2236 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
2237 f.f_choice = LDAP_FILTER_PRESENT;
2238 f.f_desc = slap_schema.si_ad_objectClass;
2241 op->ors_filterstr.bv_len = snprintf( filter_str,
2242 sizeof( filter_str ), "(%s=%s)",
2243 ad_queryId->ad_cname.bv_val, queryid->bv_val );
2244 f.f_choice = LDAP_FILTER_EQUALITY;
2246 f.f_av_desc = ad_queryId;
2247 f.f_av_value = *queryid;
2249 op->ors_filter = &f;
2251 op->ors_tlimit = SLAP_NO_LIMIT;
2252 op->ors_limit = NULL;
2253 attrs[ 0 ].an_desc = ad_queryId;
2254 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2255 op->ors_attrs = attrs;
2256 op->ors_attrsonly = 0;
2258 op->o_req_dn = *ndn;
2259 op->o_req_ndn = *ndn;
2261 op->o_tag = LDAP_REQ_SEARCH;
2262 op->o_protocol = LDAP_VERSION3;
2263 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2265 op->o_dn = op->o_bd->be_rootdn;
2266 op->o_ndn = op->o_bd->be_rootndn;
2267 sc.sc_response = fetch_queryId_cb;
2268 op->o_callback = ≻
2270 rc = op->o_bd->be_search( op, &rs );
2271 if ( rc != LDAP_SUCCESS ) {
2275 vals = (BerVarray)op->o_callback->sc_private;
2276 if ( vals != NULL ) {
2279 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2280 struct berval val = vals[ i ];
2282 remove_query_and_data( op, cm, &val );
2284 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2285 ch_free( val.bv_val );
2289 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2292 return LDAP_SUCCESS;
2298 struct berval *query_uuid )
2300 struct search_info *si = op->o_callback->sc_private;
2301 slap_overinst *on = si->on;
2302 cache_manager *cm = on->on_bi.bi_private;
2305 struct berval crp_uuid;
2306 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2308 Connection conn = {0};
2309 OperationBuffer opbuf;
2310 void *thrctx = ldap_pvt_thread_pool_context();
2312 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2313 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2315 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2316 op_tmp = &opbuf.ob_op;
2317 op_tmp->o_bd = &cm->db;
2318 op_tmp->o_dn = cm->db.be_rootdn;
2319 op_tmp->o_ndn = cm->db.be_rootndn;
2321 Debug( pcache_debug, "UUID for query being added = %s\n",
2324 for ( e=si->head; e; e=si->head ) {
2325 si->head = e->e_private;
2326 e->e_private = NULL;
2327 while ( cm->cur_entries > (cm->max_entries) ) {
2328 BER_BVZERO( &crp_uuid );
2329 remove_query_and_data( op_tmp, cm, &crp_uuid );
2332 return_val = merge_entry(op_tmp, e, 0, query_uuid);
2333 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2334 cm->cur_entries += return_val;
2335 Debug( pcache_debug,
2336 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2337 cm->cur_entries, 0, 0 );
2339 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2346 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2347 slap_callback *cb = op->o_callback;
2348 struct search_info *si = cb->sc_private;
2349 slap_overinst *on = si->on;
2350 cache_manager *cm = on->on_bi.bi_private;
2351 query_manager* qm = cm->qm;
2353 if ( rs->sr_type == REP_RESULT ||
2354 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2356 if ( si->swap_saved_attrs ) {
2357 rs->sr_attrs = si->save_attrs;
2358 op->ors_attrs = si->save_attrs;
2360 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) &&
2361 si->caching_reason == PC_IGNORE )
2363 filter_free( si->query.filter );
2365 /* duplicate query, free it */
2367 for (;si->head; si->head=e) {
2368 e = si->head->e_private;
2369 si->head->e_private = NULL;
2370 entry_free(si->head);
2374 } else if ( si->caching_reason != PC_IGNORE ) {
2375 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2376 si->qtemp, si->caching_reason, 1 );
2379 switch ( si->caching_reason ) {
2381 cache_entries( op, &qc->q_uuid );
2384 si->pbi->bi_cq = qc;
2389 qc->q_sizelimit = rs->sr_nentries;
2399 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2400 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2401 cm->num_cached_queries++;
2402 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2403 cm->num_cached_queries, 0, 0 );
2404 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2406 /* If the consistency checker suspended itself,
2409 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2410 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2411 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2413 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2415 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2418 } else if ( si->count ) {
2419 /* duplicate query, free it */
2421 for (;si->head; si->head=e) {
2422 e = si->head->e_private;
2423 si->head->e_private = NULL;
2424 entry_free(si->head);
2429 filter_free( si->query.filter );
2432 op->o_callback = op->o_callback->sc_next;
2433 op->o_tmpfree( cb, op->o_tmpmemctx );
2436 return SLAP_CB_CONTINUE;
2444 struct search_info *si = op->o_callback->sc_private;
2446 if ( si->swap_saved_attrs ) {
2447 rs->sr_attrs = si->save_attrs;
2448 rs->sr_attr_flags = slap_attr_flags( si->save_attrs );
2449 op->ors_attrs = si->save_attrs;
2452 if ( rs->sr_type == REP_SEARCH ) {
2455 /* don't return more entries than requested by the client */
2456 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2457 si->slimit_exceeded = 1;
2460 /* If we haven't exceeded the limit for this query,
2461 * build a chain of answers to store. If we hit the
2462 * limit, empty the chain and ignore the rest.
2465 slap_overinst *on = si->on;
2466 cache_manager *cm = on->on_bi.bi_private;
2468 /* check if the entry contains undefined
2469 * attributes/objectClasses (ITS#5680) */
2470 if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2471 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2472 op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
2476 /* check for malformed entries: attrs with no values */
2478 Attribute *a = rs->sr_entry->e_attrs;
2479 for (; a; a=a->a_next) {
2480 if ( !a->a_numvals ) {
2481 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2482 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2483 a->a_desc->ad_cname.bv_val );
2489 if ( si->count < si->max ) {
2491 e = entry_dup( rs->sr_entry );
2492 if ( !si->head ) si->head = e;
2493 if ( si->tail ) si->tail->e_private = e;
2500 for (;si->head; si->head=e) {
2501 e = si->head->e_private;
2502 si->head->e_private = NULL;
2503 entry_free(si->head);
2508 if ( si->slimit_exceeded ) {
2511 } else if ( rs->sr_type == REP_RESULT ) {
2514 if ( rs->sr_err == LDAP_SUCCESS ) {
2515 si->caching_reason = PC_POSITIVE;
2517 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2518 && si->qtemp->limitttl )
2522 si->caching_reason = PC_SIZELIMIT;
2523 for (;si->head; si->head=e) {
2524 e = si->head->e_private;
2525 si->head->e_private = NULL;
2526 entry_free(si->head);
2530 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2531 rs->sr_err == LDAP_SUCCESS )
2533 si->caching_reason = PC_NEGATIVE;
2537 if ( si->slimit_exceeded ) {
2538 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2542 return SLAP_CB_CONTINUE;
2545 /* NOTE: this is a quick workaround to let pcache minimally interact
2546 * with pagedResults. A more articulated solutions would be to
2547 * perform the remote query without control and cache all results,
2548 * performing the pagedResults search only within the client
2549 * and the proxy. This requires pcache to understand pagedResults. */
2551 pcache_chk_controls(
2555 const char *non = "";
2556 const char *stripped = "";
2558 switch( op->o_pagedresults ) {
2559 case SLAP_CONTROL_NONCRITICAL:
2561 stripped = "; stripped";
2564 case SLAP_CONTROL_CRITICAL:
2565 Debug( pcache_debug, "%s: "
2566 "%scritical pagedResults control "
2567 "disabled with proxy cache%s.\n",
2568 op->o_log_prefix, non, stripped );
2570 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2574 rs->sr_err = SLAP_CB_CONTINUE;
2582 pc_setpw( Operation *op, struct berval *pwd, cache_manager *cm )
2584 struct berval vals[2];
2587 const char *text = NULL;
2588 BER_BVZERO( &vals[0] );
2589 slap_passwd_hash( pwd, &vals[0], &text );
2590 if ( BER_BVISEMPTY( &vals[0] )) {
2591 Debug( pcache_debug, "pc_setpw: hash failed %s\n",
2597 BER_BVZERO( &vals[1] );
2601 SlapReply sr = { REP_RESULT };
2602 slap_callback cb = { 0, slap_null_cb, 0, 0 };
2605 mod.sml_op = LDAP_MOD_REPLACE;
2607 mod.sml_desc = slap_schema.si_ad_userPassword;
2608 mod.sml_type = mod.sml_desc->ad_cname;
2609 mod.sml_values = vals;
2610 mod.sml_nvalues = NULL;
2611 mod.sml_numvals = 1;
2612 mod.sml_next = NULL;
2614 op->o_tag = LDAP_REQ_MODIFY;
2615 op->orm_modlist = &mod;
2617 op->o_dn = op->o_bd->be_rootdn;
2618 op->o_ndn = op->o_bd->be_rootndn;
2619 op->o_callback = &cb;
2620 Debug( pcache_debug, "pc_setpw: CACHING BIND for %s\n",
2621 op->o_req_dn.bv_val, 0, 0 );
2622 rc = op->o_bd->be_modify( op, &sr );
2623 ch_free( vals[0].bv_val );
2628 typedef struct bindcacheinfo {
2634 pc_bind_save( Operation *op, SlapReply *rs )
2636 if ( rs->sr_err == LDAP_SUCCESS ) {
2637 bindcacheinfo *bci = op->o_callback->sc_private;
2638 slap_overinst *on = bci->on;
2639 cache_manager *cm = on->on_bi.bi_private;
2640 CachedQuery *qc = bci->qc;
2643 ldap_pvt_thread_rdwr_wlock( &qc->rwlock );
2644 if ( qc->bind_refcnt-- ) {
2645 Operation op2 = *op;
2646 if ( pc_setpw( &op2, &op->orb_cred, cm ) == LDAP_SUCCESS )
2647 bci->qc->bindref_time = op->o_time + bci->qc->qtemp->bindttr;
2652 ldap_pvt_thread_rdwr_wunlock( &qc->rwlock );
2653 if ( delete ) free_query(qc);
2655 return SLAP_CB_CONTINUE;
2659 pc_bind_attrs( Operation *op, Entry *e, QueryTemplate *temp,
2660 struct berval *fbv )
2663 struct berval *vals, pres = BER_BVC("*");
2667 vals = op->o_tmpalloc( temp->bindnattrs * sizeof( struct berval ),
2670 for ( i=0; i<temp->bindnattrs; i++ ) {
2671 a = attr_find( e->e_attrs, temp->bindfattrs[i] );
2672 if ( a && a->a_vals ) {
2673 vals[i] = a->a_vals[0];
2674 len += a->a_vals[0].bv_len;
2679 fbv->bv_len = len + temp->bindftemp.bv_len;
2680 fbv->bv_val = op->o_tmpalloc( fbv->bv_len + 1, op->o_tmpmemctx );
2682 p1 = temp->bindftemp.bv_val;
2687 if ( p1[0] == '=' && p1[1] == ')' ) {
2688 AC_MEMCPY( p2, vals[i].bv_val, vals[i].bv_len );
2689 p2 += vals[i].bv_len;
2695 op->o_tmpfree( vals, op->o_tmpmemctx );
2697 /* FIXME: are we sure str2filter_x can't fail?
2698 * caller needs to check */
2700 Filter *f = str2filter_x( op, fbv->bv_val );
2701 assert( f != NULL );
2706 /* Check if the requested entry is from the cache and has a valid
2707 * ttr and password hash
2710 pc_bind_search( Operation *op, SlapReply *rs )
2712 if ( rs->sr_type == REP_SEARCH ) {
2713 bindinfo *pbi = op->o_callback->sc_private;
2715 /* We only care if this is an already cached result and we're
2716 * below the refresh time, or we're offline.
2719 if (( pbi->bi_cm->cc_paused & PCACHE_CC_OFFLINE ) ||
2720 op->o_time < pbi->bi_cq->bindref_time ) {
2723 /* See if a recognized password is hashed here */
2724 a = attr_find( rs->sr_entry->e_attrs,
2725 slap_schema.si_ad_userPassword );
2726 if ( a && a->a_vals[0].bv_val[0] == '{' &&
2727 lutil_passwd_scheme( a->a_vals[0].bv_val ))
2728 pbi->bi_flags |= BI_HASHED;
2730 Debug( pcache_debug, "pc_bind_search: cache is stale, "
2731 "reftime: %ld, current time: %ld\n",
2732 pbi->bi_cq->bindref_time, op->o_time, 0 );
2734 } else if ( pbi->bi_si ) {
2735 /* This search result is going into the cache */
2739 filter_free( pbi->bi_si->query.filter );
2740 f = pc_bind_attrs( op, rs->sr_entry, pbi->bi_templ, &fbv );
2741 op->o_tmpfree( fbv.bv_val, op->o_tmpmemctx );
2742 pbi->bi_si->query.filter = filter_dup( f, NULL );
2743 filter_free_x( op, f, 1 );
2749 /* We always want pc_bind_search to run after the search handlers */
2751 pc_bind_resp( Operation *op, SlapReply *rs )
2753 bindinfo *pbi = op->o_callback->sc_private;
2754 if ( !( pbi->bi_flags & BI_DIDCB )) {
2755 slap_callback *sc = op->o_callback;
2756 while ( sc && sc->sc_response != pcache_response )
2759 sc = op->o_callback;
2760 pbi->bi_cb.sc_next = sc->sc_next;
2761 sc->sc_next = &pbi->bi_cb;
2762 pbi->bi_flags |= BI_DIDCB;
2764 return SLAP_CB_CONTINUE;
2767 #ifdef PCACHE_CONTROL_PRIVDB
2773 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2774 cache_manager *cm = on->on_bi.bi_private;
2775 slap_callback *save_cb;
2778 /* skip if control is unset */
2779 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2780 return SLAP_CB_CONTINUE;
2783 /* The cache DB isn't open yet */
2784 if ( cm->defer_db_open ) {
2785 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2786 "pcachePrivDB: cacheDB not available" );
2790 /* FIXME: might be a little bit exaggerated... */
2791 if ( !be_isroot( op ) ) {
2792 save_cb = op->o_callback;
2793 op->o_callback = NULL;
2794 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2795 "pcachePrivDB: operation not allowed" );
2796 op->o_callback = save_cb;
2801 /* map tag to operation */
2802 type = slap_req2op( op->o_tag );
2803 if ( type != SLAP_OP_LAST ) {
2807 /* execute, if possible */
2808 func = &cm->db.be_bind;
2809 if ( func[ type ] != NULL ) {
2810 Operation op2 = *op;
2814 rc = func[ type ]( &op2, rs );
2815 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2816 op->o_conn->c_authz_cookie = cm->db.be_private;
2823 /* otherwise fall back to error */
2824 save_cb = op->o_callback;
2825 op->o_callback = NULL;
2826 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2827 "operation not supported with pcachePrivDB control" );
2828 op->o_callback = save_cb;
2832 #endif /* PCACHE_CONTROL_PRIVDB */
2839 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2840 cache_manager *cm = on->on_bi.bi_private;
2841 QueryTemplate *temp;
2843 slap_callback cb = { 0 }, *sc;
2849 #ifdef PCACHE_CONTROL_PRIVDB
2850 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL )
2851 return pcache_op_privdb( op, rs );
2852 #endif /* PCACHE_CONTROL_PRIVDB */
2854 /* Skip if we're not configured for Binds, or cache DB isn't open yet */
2855 if ( !cm->cache_binds || cm->defer_db_open )
2856 return SLAP_CB_CONTINUE;
2858 /* First find a matching template with Bind info */
2859 for ( temp=cm->qm->templates; temp; temp=temp->qmnext ) {
2860 if ( temp->bindttr && dnIsSuffix( &op->o_req_ndn, &temp->bindbase ))
2863 /* Didn't find a suitable template, just passthru */
2865 return SLAP_CB_CONTINUE;
2867 /* See if the entry is already locally cached. If so, we can
2868 * populate the query filter to retrieve the cached query. We
2869 * need to check the bindrefresh time in the query.
2872 op2.o_dn = op->o_bd->be_rootdn;
2873 op2.o_ndn = op->o_bd->be_rootndn;
2878 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL, NULL, 0, &e );
2879 if ( rc == LDAP_SUCCESS && e ) {
2880 bi.bi_flags |= BI_LOOKUP;
2881 op2.ors_filter = pc_bind_attrs( op, e, temp, &op2.ors_filterstr );
2882 be_entry_release_r( &op2, e );
2884 op2.ors_filter = temp->bindfilter;
2885 op2.ors_filterstr = temp->bindfilterstr;
2888 op2.o_bd = op->o_bd;
2889 op2.o_tag = LDAP_REQ_SEARCH;
2890 op2.ors_scope = LDAP_SCOPE_BASE;
2891 op2.ors_deref = LDAP_DEREF_NEVER;
2893 op2.ors_tlimit = SLAP_NO_LIMIT;
2894 op2.ors_limit = NULL;
2895 op2.ors_attrs = cm->qm->attr_sets[temp->attr_set_index].attrs;
2896 op2.ors_attrsonly = 0;
2898 /* We want to invoke search at the same level of the stack
2899 * as we're already at...
2906 bi.bi_cb.sc_response = pc_bind_search;
2907 bi.bi_cb.sc_cleanup = NULL;
2908 bi.bi_cb.sc_private = &bi;
2909 cb.sc_private = &bi;
2910 cb.sc_response = pc_bind_resp;
2911 op2.o_callback = &cb;
2912 overlay_op_walk( &op2, rs, op_search, on->on_info, on );
2914 /* OK, just bind locally */
2915 if ( bi.bi_flags & BI_HASHED ) {
2917 BackendDB *be = op->o_bd;
2920 Debug( pcache_debug, "pcache_op_bind: CACHED BIND for %s\n",
2921 op->o_req_dn.bv_val, 0, 0 );
2923 if ( op->o_bd->be_bind( op, rs ) == LDAP_SUCCESS ) {
2924 op->o_conn->c_authz_cookie = cm->db.be_private;
2927 ldap_pvt_thread_rdwr_wlock( &bi.bi_cq->rwlock );
2928 if ( !bi.bi_cq->bind_refcnt-- ) {
2931 ldap_pvt_thread_rdwr_wunlock( &bi.bi_cq->rwlock );
2932 if ( delete ) free_query( bi.bi_cq );
2936 /* We have a cached query to work with */
2938 sc = op->o_tmpalloc( sizeof(slap_callback) + sizeof(bindcacheinfo),
2940 sc->sc_response = pc_bind_save;
2941 sc->sc_cleanup = NULL;
2942 sc->sc_private = sc+1;
2943 bci = sc->sc_private;
2944 sc->sc_next = op->o_callback;
2945 op->o_callback = sc;
2949 return SLAP_CB_CONTINUE;
2952 static slap_response refresh_merge;
2959 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2960 cache_manager *cm = on->on_bi.bi_private;
2961 query_manager* qm = cm->qm;
2966 QueryTemplate *qtemp = NULL;
2967 bindinfo *pbi = NULL;
2970 CachedQuery *answerable = NULL;
2973 struct berval tempstr;
2975 #ifdef PCACHE_CONTROL_PRIVDB
2976 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2977 return pcache_op_privdb( op, rs );
2979 #endif /* PCACHE_CONTROL_PRIVDB */
2981 /* The cache DB isn't open yet */
2982 if ( cm->defer_db_open ) {
2983 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2984 "pcachePrivDB: cacheDB not available" );
2988 /* pickup runtime ACL changes */
2989 cm->db.be_acl = op->o_bd->be_acl;
2992 /* See if we're processing a Bind request
2993 * or a cache refresh */
2994 slap_callback *cb = op->o_callback;
2996 for ( ; cb; cb=cb->sc_next ) {
2997 if ( cb->sc_response == pc_bind_resp ) {
2998 pbi = cb->sc_private;
3001 if ( cb->sc_response == refresh_merge ) {
3002 /* This is a refresh, do not search the cache */
3003 return SLAP_CB_CONTINUE;
3008 /* FIXME: cannot cache/answer requests with pagedResults control */
3010 query.filter = op->ors_filter;
3013 query.base = pbi->bi_templ->bindbase;
3014 query.scope = pbi->bi_templ->bindscope;
3015 attr_set = pbi->bi_templ->attr_set_index;
3017 qtemp = pbi->bi_templ;
3018 if ( pbi->bi_flags & BI_LOOKUP )
3019 answerable = qm->qcfunc(op, qm, &query, qtemp);
3022 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1,
3025 if ( filter2template( op, op->ors_filter, &tempstr ))
3027 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3028 return SLAP_CB_CONTINUE;
3031 Debug( pcache_debug, "query template of incoming query = %s\n",
3032 tempstr.bv_val, 0, 0 );
3035 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
3037 query.base = op->o_req_ndn;
3038 query.scope = op->ors_scope;
3040 /* check for query containment */
3041 if (attr_set > -1) {
3042 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
3043 for (; qt; qt = qt->qtnext ) {
3044 /* find if template i can potentially answer tempstr */
3045 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
3049 Debug( pcache_debug, "Entering QC, querystr = %s\n",
3050 op->ors_filterstr.bv_val, 0, 0 );
3051 answerable = qm->qcfunc(op, qm, &query, qt);
3053 /* if != NULL, rlocks qtemp->t_rwlock */
3058 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3062 BackendDB *save_bd = op->o_bd;
3064 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
3065 answerable->answerable_cnt++;
3066 /* we only care about refcnts if we're refreshing */
3067 if ( answerable->refresh_time )
3068 answerable->refcnt++;
3069 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
3070 answerable->answerable_cnt, 0, 0 );
3071 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
3073 ldap_pvt_thread_rdwr_wlock(&answerable->rwlock);
3074 if ( BER_BVISNULL( &answerable->q_uuid )) {
3075 /* No entries cached, just an empty result set */
3077 send_ldap_result( op, rs );
3079 /* Let Bind know we used a cached query */
3081 answerable->bind_refcnt++;
3082 pbi->bi_cq = answerable;
3086 if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
3088 /* The cached entry was already processed by any
3089 * other overlays, so don't let it get processed again.
3091 * This loop removes over_back_response from the stack.
3093 if ( overlay_callback_after_backover( op, &cb, 0) == 0 ) {
3094 slap_callback **scp;
3095 for ( scp = &op->o_callback; *scp != NULL;
3096 scp = &(*scp)->sc_next ) {
3097 if ( (*scp)->sc_next == &cb ) {
3104 i = cm->db.bd_info->bi_op_search( op, rs );
3106 ldap_pvt_thread_rdwr_wunlock(&answerable->rwlock);
3107 /* locked by qtemp->qcfunc (query_containment) */
3108 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
3113 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
3115 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3116 if (cm->num_cached_queries >= cm->max_queries) {
3119 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3121 if (op->ors_attrsonly)
3126 struct search_info *si;
3128 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
3129 query.filter = filter_dup(op->ors_filter, NULL);
3131 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
3132 cb->sc_response = pcache_response;
3133 cb->sc_cleanup = pcache_op_cleanup;
3134 cb->sc_private = (cb+1);
3135 si = cb->sc_private;
3139 si->max = cm->num_entries_limit ;
3143 si->slimit_exceeded = 0;
3144 si->caching_reason = PC_IGNORE;
3145 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
3146 si->slimit = op->ors_slimit;
3147 op->ors_slimit = cm->num_entries_limit;
3151 si->swap_saved_attrs = 1;
3152 si->save_attrs = op->ors_attrs;
3157 op->ors_attrs = qtemp->t_attrs.attrs;
3159 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3160 cb->sc_next = op->o_callback;
3161 op->o_callback = cb;
3164 slap_callback **pcb;
3166 /* need to move the callback at the end, in case other
3167 * overlays are present, so that the final entry is
3168 * actually cached */
3170 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
3175 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
3179 return SLAP_CB_CONTINUE;
3184 AttributeName* attrs,
3192 for ( ; attrs[i].an_name.bv_val; i++ ) {
3193 /* only count valid attribute names
3194 * (searches ignore others, this overlay does the same) */
3195 if ( attrs[i].an_desc ) {
3201 /* recognize default or explicit single "*" */
3203 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_all_user_attrs ) ) )
3206 attrs = slap_anlist_all_user_attributes;
3208 /* recognize implicit (no valid attributes) or explicit single "1.1" */
3209 } else if ( count == 0 ||
3210 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) )
3216 for ( i = 0; i < num; i++ ) {
3220 if ( count > qm->attr_sets[i].count ) {
3221 if ( qm->attr_sets[i].count &&
3222 bvmatch( &qm->attr_sets[i].attrs[0].an_name, slap_bv_all_user_attrs )) {
3229 if ( !qm->attr_sets[i].count ) {
3235 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
3236 if ( !a2->an_desc && !bvmatch( &a2->an_name, slap_bv_all_user_attrs ) ) continue;
3238 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
3256 /* Refresh a cached query:
3257 * 1: Replay the query on the remote DB and merge each entry into
3258 * the local DB. Remember the DNs of each remote entry.
3259 * 2: Search the local DB for all entries matching this queryID.
3260 * Delete any entry whose DN is not in the list from (1).
3262 typedef struct dnlist {
3263 struct dnlist *next;
3268 typedef struct refresh_info {
3276 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
3278 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
3280 dn->dn.bv_len = bvdn->bv_len;
3281 dn->dn.bv_val = (char *)(dn+1);
3282 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
3283 dn->dn.bv_val[dn->dn.bv_len] = '\0';
3288 refresh_merge( Operation *op, SlapReply *rs )
3290 if ( rs->sr_type == REP_SEARCH ) {
3291 refresh_info *ri = op->o_callback->sc_private;
3297 ocb = op->o_callback;
3298 /* Find local entry, merge */
3299 op->o_bd = ri->ri_be;
3300 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
3301 if ( rc != LDAP_SUCCESS || e == NULL ) {
3302 /* No local entry, just add it. FIXME: we are not checking
3303 * the cache entry limit here
3305 merge_entry( op, rs->sr_entry, 1, &ri->ri_q->q_uuid );
3307 /* Entry exists, update it */
3310 Modifications *modlist, *mods = NULL;
3311 const char* text = NULL;
3312 char textbuf[SLAP_TEXT_BUFLEN];
3313 size_t textlen = sizeof(textbuf);
3314 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
3318 /* Get a copy of only the attrs we requested */
3319 for ( a=e->e_attrs; a; a=a->a_next ) {
3320 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
3321 *b = attr_alloc( a->a_desc );
3323 /* The actual values still belong to e */
3324 (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
3325 SLAP_ATTR_DONT_FREE_DATA;
3326 b = &((*b)->a_next);
3330 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
3331 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
3332 &mods, &modlist, 0 );
3333 be_entry_release_r( op, e );
3334 attrs_free( ne.e_attrs );
3335 slap_mods_free( modlist, 1 );
3336 /* mods is NULL if there are no changes */
3338 SlapReply rs2 = { REP_RESULT };
3339 struct berval dn = op->o_req_dn;
3340 struct berval ndn = op->o_req_ndn;
3341 op->o_tag = LDAP_REQ_MODIFY;
3342 op->orm_modlist = mods;
3343 op->o_req_dn = rs->sr_entry->e_name;
3344 op->o_req_ndn = rs->sr_entry->e_nname;
3345 op->o_callback = &cb;
3346 op->o_bd->be_modify( op, &rs2 );
3347 rs->sr_err = rs2.sr_err;
3348 rs_assert_done( &rs2 );
3349 slap_mods_free( mods, 1 );
3351 op->o_req_ndn = ndn;
3355 /* Add DN to list */
3356 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3358 if ( ri->ri_tail ) {
3359 ri->ri_tail->next = dnl;
3364 op->o_callback = ocb;
3370 refresh_purge( Operation *op, SlapReply *rs )
3372 if ( rs->sr_type == REP_SEARCH ) {
3373 refresh_info *ri = op->o_callback->sc_private;
3377 /* Did the entry exist on the remote? */
3378 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
3379 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
3380 dnlist *dnext = (*dn)->next;
3381 op->o_tmpfree( *dn, op->o_tmpmemctx );
3387 /* No, so put it on the list to delete */
3390 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3391 dnl->next = ri->ri_dels;
3393 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
3394 /* If ours is the only queryId, delete entry */
3395 dnl->delete = ( a->a_numvals == 1 );
3402 refresh_query( Operation *op, CachedQuery *query, slap_overinst *on )
3404 SlapReply rs = {REP_RESULT};
3405 slap_callback cb = { 0 };
3406 refresh_info ri = { 0 };
3407 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
3408 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3409 Filter filter = {LDAP_FILTER_EQUALITY};
3410 AttributeName attrs[ 2 ] = {{{ 0 }}};
3414 ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
3416 ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
3418 cb.sc_response = refresh_merge;
3419 cb.sc_private = &ri;
3422 ri.ri_be = op->o_bd;
3425 op->o_tag = LDAP_REQ_SEARCH;
3426 op->o_protocol = LDAP_VERSION3;
3427 op->o_callback = &cb;
3428 op->o_do_not_cache = 1;
3430 op->o_req_dn = query->qbase->base;
3431 op->o_req_ndn = query->qbase->base;
3432 op->ors_scope = query->scope;
3433 op->ors_deref = LDAP_DEREF_NEVER;
3434 op->ors_slimit = SLAP_NO_LIMIT;
3435 op->ors_tlimit = SLAP_NO_LIMIT;
3436 op->ors_limit = NULL;
3437 op->ors_filter = query->filter;
3438 filter2bv_x( op, query->filter, &op->ors_filterstr );
3439 op->ors_attrs = query->qtemp->t_attrs.attrs;
3440 op->ors_attrsonly = 0;
3442 op->o_bd = on->on_info->oi_origdb;
3443 rc = op->o_bd->be_search( op, &rs );
3445 op->o_bd = ri.ri_be;
3449 /* Get the DNs of all entries matching this query */
3450 cb.sc_response = refresh_purge;
3452 op->o_bd = ri.ri_be;
3453 op->o_req_dn = op->o_bd->be_suffix[0];
3454 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3455 op->ors_scope = LDAP_SCOPE_SUBTREE;
3456 op->ors_deref = LDAP_DEREF_NEVER;
3457 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
3458 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
3459 filter.f_ava = &ava;
3460 filter.f_av_desc = ad_queryId;
3461 filter.f_av_value = query->q_uuid;
3462 attrs[ 0 ].an_desc = ad_queryId;
3463 attrs[ 0 ].an_name = ad_queryId->ad_cname;
3464 op->ors_attrs = attrs;
3465 op->ors_attrsonly = 0;
3466 rs_reinit( &rs, REP_RESULT );
3467 rc = op->o_bd->be_search( op, &rs );
3468 if ( rc ) goto leave;
3470 while (( dn = ri.ri_dels )) {
3471 op->o_req_dn = dn->dn;
3472 op->o_req_ndn = dn->dn;
3473 rs_reinit( &rs, REP_RESULT );
3475 op->o_tag = LDAP_REQ_DELETE;
3476 op->o_bd->be_delete( op, &rs );
3479 struct berval vals[2];
3481 vals[0] = query->q_uuid;
3482 BER_BVZERO( &vals[1] );
3483 mod.sml_op = LDAP_MOD_DELETE;
3485 mod.sml_desc = ad_queryId;
3486 mod.sml_type = ad_queryId->ad_cname;
3487 mod.sml_values = vals;
3488 mod.sml_nvalues = NULL;
3489 mod.sml_numvals = 1;
3490 mod.sml_next = NULL;
3492 op->o_tag = LDAP_REQ_MODIFY;
3493 op->orm_modlist = &mod;
3494 op->o_bd->be_modify( op, &rs );
3496 ri.ri_dels = dn->next;
3497 op->o_tmpfree( dn, op->o_tmpmemctx );
3501 /* reset our local heap, we're done with it */
3502 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
3511 struct re_s *rtask = arg;
3512 slap_overinst *on = rtask->arg;
3513 cache_manager *cm = on->on_bi.bi_private;
3514 query_manager *qm = cm->qm;
3515 Connection conn = {0};
3516 OperationBuffer opbuf;
3519 CachedQuery *query, *qprev;
3520 int return_val, pause = PCACHE_CC_PAUSED;
3521 QueryTemplate *templ;
3523 /* Don't expire anything when we're offline */
3524 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
3525 pause = PCACHE_CC_OFFLINE;
3529 connection_fake_init( &conn, &opbuf, ctx );
3533 op->o_dn = cm->db.be_rootdn;
3534 op->o_ndn = cm->db.be_rootndn;
3538 for (templ = qm->templates; templ; templ=templ->qmnext) {
3540 if ( !templ->query_last ) continue;
3542 op->o_time = slap_get_time();
3543 if ( !templ->ttr ) {
3545 if ( templ->negttl && templ->negttl < ttl )
3546 ttl = templ->negttl;
3547 if ( templ->limitttl && templ->limitttl < ttl )
3548 ttl = templ->limitttl;
3549 /* The oldest timestamp that needs expiration checking */
3553 for ( query=templ->query_last; query; query=qprev ) {
3554 qprev = query->prev;
3555 if ( query->refresh_time && query->refresh_time < op->o_time ) {
3556 /* A refresh will extend the expiry if the query has been
3557 * referenced, but not if it's unreferenced. If the
3558 * expiration has been hit, then skip the refresh since
3559 * we're just going to discard the result anyway.
3561 if ( query->refcnt )
3562 query->expiry_time = op->o_time + templ->ttl;
3563 if ( query->expiry_time > op->o_time ) {
3564 refresh_query( op, query, on );
3569 if (query->expiry_time < op->o_time) {
3571 Debug( pcache_debug, "Lock CR index = %p\n",
3572 (void *) templ, 0, 0 );
3573 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
3574 if ( query == templ->query_last ) {
3576 remove_from_template(query, templ);
3577 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
3578 (void *) templ, templ->no_of_queries, 0 );
3579 Debug( pcache_debug, "Unlock CR index = %p\n",
3580 (void *) templ, 0, 0 );
3583 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3586 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
3587 remove_query(qm, query);
3588 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
3589 if ( BER_BVISNULL( &query->q_uuid ))
3592 return_val = remove_query_data(op, &query->q_uuid);
3593 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3595 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3596 cm->cur_entries -= return_val;
3597 cm->num_cached_queries--;
3598 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3599 cm->num_cached_queries, 0, 0 );
3600 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3601 Debug( pcache_debug,
3602 "STALE QUERY REMOVED, CACHE ="
3604 cm->cur_entries, 0, 0 );
3605 ldap_pvt_thread_rdwr_wlock( &query->rwlock );
3606 if ( query->bind_refcnt-- ) {
3611 ldap_pvt_thread_rdwr_wunlock( &query->rwlock );
3612 if ( rem ) free_query(query);
3613 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3614 } else if ( !templ->ttr && query->expiry_time > ttl ) {
3615 /* We don't need to check for refreshes, and this
3616 * query's expiry is too new, and all subsequent queries
3617 * will be newer yet. So stop looking.
3619 * If we have refreshes, then we always have to walk the
3620 * entire query list.
3628 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3629 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3630 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3632 /* If there were no queries, defer processing for a while */
3633 if ( cm->cc_paused != pause )
3634 cm->cc_paused = pause;
3635 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3637 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3642 #define MAX_ATTR_SETS 500
3655 static ConfigDriver pc_cf_gen;
3656 static ConfigLDAPadd pc_ldadd;
3657 static ConfigCfAdd pc_cfadd;
3659 static ConfigTable pccfg[] = {
3660 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3662 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3663 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3664 "DESC 'Proxy Cache basic parameters' "
3665 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3666 { "pcacheAttrset", "index> <attributes...",
3667 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3668 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3669 "DESC 'A set of attributes to cache' "
3670 "EQUALITY caseIgnoreMatch "
3671 "SYNTAX OMsDirectoryString )", NULL, NULL },
3672 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3674 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3675 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3676 "DESC 'Filter template, attrset, cache TTL, "
3677 "optional negative TTL, optional sizelimit TTL, "
3679 "EQUALITY caseIgnoreMatch "
3680 "SYNTAX OMsDirectoryString )", NULL, NULL },
3681 { "pcachePosition", "head|tail(default)",
3682 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3683 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3684 "DESC 'Response callback position in overlay stack' "
3685 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3686 { "pcacheMaxQueries", "queries",
3687 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3688 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3689 "DESC 'Maximum number of queries to cache' "
3690 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
3691 { "pcachePersist", "TRUE|FALSE",
3692 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3693 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3694 "DESC 'Save cached queries for hot restart' "
3695 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3696 { "pcacheValidate", "TRUE|FALSE",
3697 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3698 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3699 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3700 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3701 { "pcacheOffline", "TRUE|FALSE",
3702 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3703 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3704 "DESC 'Set cache to offline mode and disable expiration' "
3705 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3706 { "pcacheBind", "filter> <attrset-index> <TTR> <scope> <base",
3707 6, 6, 0, ARG_MAGIC|PC_BIND, pc_cf_gen,
3708 "( OLcfgOvAt:2.9 NAME 'olcPcacheBind' "
3709 "DESC 'Parameters for caching Binds' "
3710 "EQUALITY caseIgnoreMatch "
3711 "SYNTAX OMsDirectoryString )", NULL, NULL },
3712 { "pcache-", "private database args",
3713 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3716 /* Legacy keywords */
3717 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3719 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3721 { "proxyattrset", "index> <attributes...",
3722 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3724 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3725 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3727 { "response-callback", "head|tail(default)",
3728 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3730 { "proxyCacheQueries", "queries",
3731 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3733 { "proxySaveQueries", "TRUE|FALSE",
3734 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3736 { "proxyCheckCacheability", "TRUE|FALSE",
3737 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3740 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3743 static ConfigOCs pcocs[] = {
3744 { "( OLcfgOvOc:2.1 "
3745 "NAME 'olcPcacheConfig' "
3746 "DESC 'ProxyCache configuration' "
3747 "SUP olcOverlayConfig "
3748 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3749 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3750 "olcPcacheValidate $ olcPcacheOffline $ olcPcacheBind ) )",
3751 Cft_Overlay, pccfg, NULL, pc_cfadd },
3752 { "( OLcfgOvOc:2.2 "
3753 "NAME 'olcPcacheDatabase' "
3754 "DESC 'Cache database configuration' "
3755 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3759 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3762 pc_ldadd_cleanup( ConfigArgs *c )
3764 slap_overinst *on = c->ca_private;
3765 return pcache_db_open2( on, &c->reply );
3769 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3774 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3775 p->ce_bi->bi_cf_ocs != pcocs )
3776 return LDAP_CONSTRAINT_VIOLATION;
3778 on = (slap_overinst *)p->ce_bi;
3779 cm = on->on_bi.bi_private;
3781 /* Defer open if this is an LDAPadd */
3782 if ( CONFIG_ONLINE_ADD( ca ))
3783 ca->cleanup = pc_ldadd_cleanup;
3785 cm->defer_db_open = 0;
3786 ca->ca_private = on;
3787 return LDAP_SUCCESS;
3791 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3793 CfEntryInfo *pe = p->e_private;
3794 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3795 cache_manager *cm = on->on_bi.bi_private;
3798 /* FIXME: should not hardcode "olcDatabase" here */
3799 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3800 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3801 0, cm->db.bd_info->bi_type );
3802 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3805 bv.bv_val = ca->cr_msg;
3807 cm->defer_db_open = 0;
3809 /* We can only create this entry if the database is table-driven
3811 if ( cm->db.bd_info->bi_cf_ocs )
3812 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3819 pc_cf_gen( ConfigArgs *c )
3821 slap_overinst *on = (slap_overinst *)c->bi;
3822 cache_manager* cm = on->on_bi.bi_private;
3823 query_manager* qm = cm->qm;
3824 QueryTemplate* temp;
3825 AttributeName* attr_name;
3826 AttributeName* attrarray;
3827 const char* text=NULL;
3832 if ( c->op == SLAP_CONFIG_EMIT ) {
3836 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3837 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3838 cm->num_entries_limit, cm->cc_period );
3839 bv.bv_val = c->cr_msg;
3840 value_add_one( &c->rvalue_vals, &bv );
3843 for (i=0; i<cm->numattrsets; i++) {
3844 if ( !qm->attr_sets[i].count ) continue;
3846 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3848 /* count the attr length */
3849 for ( attr_name = qm->attr_sets[i].attrs;
3850 attr_name->an_name.bv_val; attr_name++ )
3852 bv.bv_len += attr_name->an_name.bv_len + 1;
3853 if ( attr_name->an_desc &&
3854 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3855 bv.bv_len += STRLENOF("undef:");
3859 bv.bv_val = ch_malloc( bv.bv_len+1 );
3860 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3861 for ( attr_name = qm->attr_sets[i].attrs;
3862 attr_name->an_name.bv_val; attr_name++ ) {
3864 if ( attr_name->an_desc &&
3865 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3866 ptr = lutil_strcopy( ptr, "undef:" );
3868 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3870 ber_bvarray_add( &c->rvalue_vals, &bv );
3872 if ( !c->rvalue_vals )
3876 for (temp=qm->templates; temp; temp=temp->qmnext) {
3877 /* HEADS-UP: always print all;
3878 * if optional == 0, ignore */
3879 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3880 " %d %ld %ld %ld %ld",
3881 temp->attr_set_index,
3886 bv.bv_len += temp->querystr.bv_len + 2;
3887 bv.bv_val = ch_malloc( bv.bv_len+1 );
3890 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3892 strcpy( ptr, c->cr_msg );
3893 ber_bvarray_add( &c->rvalue_vals, &bv );
3895 if ( !c->rvalue_vals )
3899 for (temp=qm->templates; temp; temp=temp->qmnext) {
3900 if ( !temp->bindttr ) continue;
3901 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3903 temp->attr_set_index,
3905 ldap_pvt_scope2str( temp->bindscope ));
3906 bv.bv_len += temp->bindbase.bv_len + temp->bindftemp.bv_len + 4;
3907 bv.bv_val = ch_malloc( bv.bv_len + 1 );
3910 ptr = lutil_strcopy( ptr, temp->bindftemp.bv_val );
3912 ptr = lutil_strcopy( ptr, c->cr_msg );
3914 ptr = lutil_strcopy( ptr, temp->bindbase.bv_val );
3917 ber_bvarray_add( &c->rvalue_vals, &bv );
3919 if ( !c->rvalue_vals )
3923 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3924 BER_BVSTR( &bv, "head" );
3926 BER_BVSTR( &bv, "tail" );
3928 value_add_one( &c->rvalue_vals, &bv );
3931 c->value_int = cm->max_queries;
3934 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3938 } else if ( c->op == LDAP_MOD_DELETE ) {
3941 case PC_ATTR: /* FIXME */
3946 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3947 /* If there were cached queries when we went offline,
3948 * restart the checker now.
3950 if ( cm->num_cached_queries ) {
3951 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3953 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3954 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3964 if ( cm->numattrsets > 0 ) {
3965 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive already provided" );
3966 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3970 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3971 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3973 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3976 if ( cm->numattrsets <= 0 ) {
3977 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3978 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3981 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3982 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3983 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3987 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3988 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3989 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3993 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3994 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3996 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3999 if ( cm->max_entries <= 0 ) {
4000 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
4001 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
4005 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
4006 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
4008 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4011 if ( cm->num_entries_limit <= 0 ) {
4012 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
4013 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4016 if ( cm->num_entries_limit > cm->max_entries ) {
4017 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
4018 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4022 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4023 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
4025 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4029 cm->cc_period = (time_t)t;
4030 Debug( pcache_debug,
4031 "Total # of attribute sets to be cached = %d.\n",
4032 cm->numattrsets, 0, 0 );
4033 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
4034 sizeof( struct attr_set ) );
4037 if ( cm->numattrsets == 0 ) {
4038 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4039 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4042 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
4043 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
4045 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4049 if ( num < 0 || num >= cm->numattrsets ) {
4050 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
4051 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4052 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4055 qm->attr_sets[num].flags |= PC_CONFIGURED;
4056 if ( c->argc == 2 ) {
4058 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4059 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
4060 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4063 } else if ( c->argc == 3 ) {
4064 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4065 qm->attr_sets[num].count = 1;
4066 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4067 sizeof( AttributeName ) );
4068 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4071 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4072 qm->attr_sets[num].count = 1;
4073 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4074 sizeof( AttributeName ) );
4075 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4078 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
4081 /* else: fallthru */
4083 } else if ( c->argc == 4 ) {
4084 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
4085 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
4087 qm->attr_sets[num].count = 2;
4088 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
4089 sizeof( AttributeName ) );
4090 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4091 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4094 /* else: fallthru */
4097 if ( c->argc > 2 ) {
4098 int all_user = 0, all_op = 0;
4100 qm->attr_sets[num].count = c->argc - 2;
4101 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
4102 sizeof( AttributeName ) );
4103 attr_name = qm->attr_sets[num].attrs;
4104 for ( i = 2; i < c->argc; i++ ) {
4105 attr_name->an_desc = NULL;
4106 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
4107 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4108 "invalid attr #%d \"%s\" in attrlist",
4109 i - 2, c->argv[i] );
4110 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4111 ch_free( qm->attr_sets[num].attrs );
4112 qm->attr_sets[num].attrs = NULL;
4113 qm->attr_sets[num].count = 0;
4116 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4118 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
4119 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4121 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4123 if ( strncasecmp( c->argv[i], "undef:", STRLENOF("undef:") ) == 0 ) {
4125 ber_str2bv( c->argv[i] + STRLENOF("undef:"), 0, 0, &bv );
4126 attr_name->an_desc = slap_bv2tmp_ad( &bv, NULL );
4128 } else if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
4129 strcpy( c->cr_msg, text );
4130 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4131 ch_free( qm->attr_sets[num].attrs );
4132 qm->attr_sets[num].attrs = NULL;
4133 qm->attr_sets[num].count = 0;
4136 attr_name->an_name = attr_name->an_desc->ad_cname;
4138 attr_name->an_oc = NULL;
4139 attr_name->an_flags = 0;
4140 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
4141 qm->attr_sets[num].flags |= PC_GOT_OC;
4143 BER_BVZERO( &attr_name->an_name );
4146 /* warn if list contains both "*" and "+" */
4147 if ( i > 4 && all_user && all_op ) {
4148 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4149 "warning: attribute list contains \"*\" and \"+\"" );
4150 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4155 if ( cm->numattrsets == 0 ) {
4156 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4157 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4160 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4161 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
4163 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4167 if ( i < 0 || i >= cm->numattrsets ||
4168 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4169 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
4170 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4171 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4175 AttributeName *attrs;
4177 cnt = template_attrs( c->argv[1], &qm->attr_sets[i], &attrs, &text );
4179 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4181 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4184 temp = ch_calloc( 1, sizeof( QueryTemplate ));
4185 temp->qmnext = qm->templates;
4186 qm->templates = temp;
4187 temp->t_attrs.attrs = attrs;
4188 temp->t_attrs.count = cnt;
4190 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
4191 temp->query = temp->query_last = NULL;
4192 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4193 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4194 "unable to parse template ttl=\"%s\"",
4196 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4198 ch_free( temp->t_attrs.attrs );
4202 temp->ttl = (time_t)t;
4203 temp->negttl = (time_t)0;
4204 temp->limitttl = (time_t)0;
4205 temp->ttr = (time_t)0;
4206 switch ( c->argc ) {
4208 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
4209 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4210 "unable to parse template ttr=\"%s\"",
4212 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4215 temp->ttr = (time_t)t;
4219 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4220 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4221 "unable to parse template sizelimit ttl=\"%s\"",
4223 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4226 temp->limitttl = (time_t)t;
4230 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
4231 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4232 "unable to parse template negative ttl=\"%s\"",
4234 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4237 temp->negttl = (time_t)t;
4241 temp->no_of_queries = 0;
4243 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
4244 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
4245 Debug( pcache_debug, " query template: %s\n",
4246 temp->querystr.bv_val, 0, 0 );
4247 temp->attr_set_index = i;
4248 qm->attr_sets[i].flags |= PC_REFERENCED;
4249 temp->qtnext = qm->attr_sets[i].templates;
4250 qm->attr_sets[i].templates = temp;
4251 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
4252 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
4253 for ( i=0; attrarray[i].an_name.bv_val; i++ )
4254 Debug( pcache_debug, "\t%s\n",
4255 attrarray[i].an_name.bv_val, 0, 0 );
4259 if ( !qm->templates ) {
4260 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcacheTemplate\" directive not provided yet" );
4261 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4264 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4265 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse Bind index #=\"%s\"",
4267 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4271 if ( i < 0 || i >= cm->numattrsets ||
4272 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4273 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind index %d invalid (%s%d)",
4274 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4275 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4278 { struct berval bv, tempbv;
4279 AttributeDescription **descs;
4281 ber_str2bv( c->argv[1], 0, 0, &bv );
4282 ndescs = ftemp_attrs( &bv, &tempbv, &descs, &text );
4284 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4286 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4289 for ( temp = qm->templates; temp; temp=temp->qmnext ) {
4290 if ( temp->attr_set_index == i && bvmatch( &tempbv,
4294 ch_free( tempbv.bv_val );
4297 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind template %s %d invalid",
4299 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4302 ber_dupbv( &temp->bindftemp, &bv );
4303 temp->bindfattrs = descs;
4304 temp->bindnattrs = ndescs;
4306 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4307 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4308 "unable to parse bind ttr=\"%s\"",
4310 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4312 ch_free( temp->bindfattrs );
4313 temp->bindfattrs = NULL;
4314 ch_free( temp->bindftemp.bv_val );
4315 BER_BVZERO( &temp->bindftemp );
4318 num = ldap_pvt_str2scope( c->argv[4] );
4320 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4321 "unable to parse bind scope=\"%s\"",
4323 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4327 struct berval dn, ndn;
4328 ber_str2bv( c->argv[5], 0, 0, &dn );
4329 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
4331 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4332 "invalid bind baseDN=\"%s\"",
4334 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4337 if ( temp->bindbase.bv_val )
4338 ch_free( temp->bindbase.bv_val );
4339 temp->bindbase = ndn;
4342 /* convert the template into dummy filter */
4344 char *eq = temp->bindftemp.bv_val, *e2;
4347 while ((eq = strchr(eq, '=' ))) {
4352 bv.bv_len = temp->bindftemp.bv_len + i;
4353 bv.bv_val = ch_malloc( bv.bv_len + 1 );
4354 for ( e2 = bv.bv_val, eq = temp->bindftemp.bv_val;
4365 f = str2filter( bv.bv_val );
4367 ch_free( bv.bv_val );
4368 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4369 "unable to parse bindfilter=\"%s\"", bv.bv_val );
4370 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4371 ch_free( temp->bindbase.bv_val );
4372 BER_BVZERO( &temp->bindbase );
4375 if ( temp->bindfilter )
4376 filter_free( temp->bindfilter );
4377 if ( temp->bindfilterstr.bv_val )
4378 ch_free( temp->bindfilterstr.bv_val );
4379 temp->bindfilterstr = bv;
4380 temp->bindfilter = f;
4382 temp->bindttr = (time_t)t;
4383 temp->bindscope = num;
4384 cm->cache_binds = 1;
4388 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
4389 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
4391 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
4392 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4395 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
4396 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4401 if ( c->value_int <= 0 ) {
4402 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
4403 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4406 cm->max_queries = c->value_int;
4410 cm->cc_paused |= PCACHE_CC_OFFLINE;
4412 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
4415 if ( cm->db.be_private == NULL ) {
4416 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4417 "private database must be defined before setting database specific options" );
4418 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4422 if ( cm->db.bd_info->bi_cf_ocs ) {
4425 char *argv0 = c->argv[ 0 ];
4427 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4429 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
4431 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4432 "private database does not recognize specific option '%s'",
4434 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4438 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
4440 c->bi = c->be->bd_info;
4442 rc = config_add_vals( ct, c );
4446 c->table = c2.table;
4449 c->argv[ 0 ] = argv0;
4451 } else if ( cm->db.be_config != NULL ) {
4452 char *argv0 = c->argv[ 0 ];
4454 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4455 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
4456 c->argv[ 0 ] = argv0;
4459 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4460 "no means to set private database specific options" );
4461 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4466 rc = SLAP_CONF_UNKNOWN;
4482 slap_overinst *on = (slap_overinst *)be->bd_info;
4483 cache_manager* cm = on->on_bi.bi_private;
4485 /* Something for the cache database? */
4486 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
4487 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
4489 return SLAP_CONF_UNKNOWN;
4497 slap_overinst *on = (slap_overinst *)be->bd_info;
4501 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
4502 on->on_bi.bi_private = cm;
4504 qm = (query_manager*)ch_malloc(sizeof(query_manager));
4507 cm->db.bd_info = NULL;
4508 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
4509 cm->db.be_private = NULL;
4510 cm->db.bd_self = &cm->db;
4512 cm->numattrsets = 0;
4513 cm->num_entries_limit = 5;
4514 cm->num_cached_queries = 0;
4515 cm->max_entries = 0;
4516 cm->cur_entries = 0;
4517 cm->max_queries = 10000;
4518 cm->save_queries = 0;
4519 cm->check_cacheability = 0;
4520 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4521 cm->defer_db_open = 1;
4522 cm->cache_binds = 0;
4523 cm->cc_period = 1000;
4526 #ifdef PCACHE_MONITOR
4527 cm->monitor_cb = NULL;
4528 #endif /* PCACHE_MONITOR */
4530 qm->attr_sets = NULL;
4531 qm->templates = NULL;
4533 qm->lru_bottom = NULL;
4535 qm->qcfunc = query_containment;
4536 qm->crfunc = cache_replacement;
4537 qm->addfunc = add_query;
4538 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
4540 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
4542 #ifndef PCACHE_MONITOR
4544 #else /* PCACHE_MONITOR */
4545 return pcache_monitor_db_init( be );
4546 #endif /* PCACHE_MONITOR */
4550 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
4552 assert( op->o_tag == LDAP_REQ_SEARCH );
4554 if ( rs->sr_type == REP_SEARCH ) {
4557 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
4561 assert( a->a_nvals != NULL );
4563 valsp = op->o_callback->sc_private;
4564 assert( *valsp == NULL );
4566 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
4574 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
4576 assert( op->o_tag == LDAP_REQ_SEARCH );
4578 if ( rs->sr_type == REP_SEARCH ) {
4579 int *countp = (int *)op->o_callback->sc_private;
4592 cache_manager *cm = on->on_bi.bi_private;
4593 query_manager* qm = cm->qm;
4596 rc = backend_startup_one( &cm->db, cr );
4598 cm->defer_db_open = 0;
4601 /* There is no runqueue in TOOL mode */
4602 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
4603 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4604 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
4605 consistency_check, on,
4606 "pcache_consistency", cm->db.be_suffix[0].bv_val );
4607 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4609 /* Cached database must have the rootdn */
4610 if ( BER_BVISNULL( &cm->db.be_rootndn )
4611 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
4613 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
4614 "underlying database of type \"%s\"\n"
4615 " serving naming context \"%s\"\n"
4616 " has no \"rootdn\", required by \"pcache\".\n",
4617 on->on_info->oi_orig->bi_type,
4618 cm->db.be_suffix[0].bv_val, 0 );
4622 if ( cm->save_queries ) {
4623 void *thrctx = ldap_pvt_thread_pool_context();
4624 Connection conn = { 0 };
4625 OperationBuffer opbuf;
4627 slap_callback cb = { 0 };
4628 SlapReply rs = { REP_RESULT };
4629 BerVarray vals = NULL;
4630 Filter f = { 0 }, f2 = { 0 };
4631 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
4632 AttributeName attrs[ 2 ] = {{{ 0 }}};
4634 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4639 op->o_tag = LDAP_REQ_SEARCH;
4640 op->o_protocol = LDAP_VERSION3;
4641 cb.sc_response = pcache_cachedquery_open_cb;
4642 cb.sc_private = &vals;
4643 op->o_callback = &cb;
4644 op->o_time = slap_get_time();
4645 op->o_do_not_cache = 1;
4646 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4648 op->o_dn = cm->db.be_rootdn;
4649 op->o_ndn = cm->db.be_rootndn;
4650 op->o_req_dn = cm->db.be_suffix[ 0 ];
4651 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
4653 op->ors_scope = LDAP_SCOPE_BASE;
4654 op->ors_deref = LDAP_DEREF_NEVER;
4656 op->ors_tlimit = SLAP_NO_LIMIT;
4657 op->ors_limit = NULL;
4658 ber_str2bv( "(pcacheQueryURL=*)", 0, 0, &op->ors_filterstr );
4659 f.f_choice = LDAP_FILTER_PRESENT;
4660 f.f_desc = ad_cachedQueryURL;
4661 op->ors_filter = &f;
4662 attrs[ 0 ].an_desc = ad_cachedQueryURL;
4663 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
4664 op->ors_attrs = attrs;
4665 op->ors_attrsonly = 0;
4667 rc = op->o_bd->be_search( op, &rs );
4668 if ( rc == LDAP_SUCCESS && vals != NULL ) {
4671 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
4672 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
4673 cm->num_cached_queries++;
4677 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4680 /* count cached entries */
4681 f.f_choice = LDAP_FILTER_NOT;
4683 f2.f_choice = LDAP_FILTER_EQUALITY;
4685 f2.f_av_desc = slap_schema.si_ad_objectClass;
4686 BER_BVSTR( &f2.f_av_value, "glue" );
4687 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
4689 op->ors_slimit = SLAP_NO_LIMIT;
4690 op->ors_scope = LDAP_SCOPE_SUBTREE;
4691 op->ors_attrs = slap_anlist_no_attrs;
4693 rs_reinit( &rs, REP_RESULT );
4694 op->o_callback->sc_response = pcache_cachedquery_count_cb;
4695 op->o_callback->sc_private = &rs.sr_nentries;
4697 rc = op->o_bd->be_search( op, &rs );
4699 cm->cur_entries = rs.sr_nentries;
4713 slap_overinst *on = (slap_overinst *)be->bd_info;
4714 cache_manager *cm = on->on_bi.bi_private;
4715 query_manager* qm = cm->qm;
4716 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
4718 /* check attr sets */
4719 for ( i = 0; i < cm->numattrsets; i++) {
4720 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
4721 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
4722 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
4726 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
4730 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
4731 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
4736 if ( ncf || rf || nrf ) {
4737 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
4738 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
4739 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
4746 /* need to inherit something from the original database... */
4747 cm->db.be_def_limit = be->be_def_limit;
4748 cm->db.be_limits = be->be_limits;
4749 cm->db.be_acl = be->be_acl;
4750 cm->db.be_dfltaccess = be->be_dfltaccess;
4752 if ( SLAP_DBMONITORING( be ) ) {
4753 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
4756 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
4759 if ( !cm->defer_db_open ) {
4760 rc = pcache_db_open2( on, cr );
4763 #ifdef PCACHE_MONITOR
4764 if ( rc == LDAP_SUCCESS ) {
4765 rc = pcache_monitor_db_open( be );
4767 #endif /* PCACHE_MONITOR */
4773 pcache_free_qbase( void *v )
4779 tavl_free( qb->scopes[i], NULL );
4789 slap_overinst *on = (slap_overinst *)be->bd_info;
4790 cache_manager *cm = on->on_bi.bi_private;
4791 query_manager *qm = cm->qm;
4795 /* stop the thread ... */
4797 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4798 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4799 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4801 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4802 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4806 if ( cm->save_queries ) {
4808 BerVarray vals = NULL;
4811 Connection conn = { 0 };
4812 OperationBuffer opbuf;
4814 slap_callback cb = { 0 };
4816 SlapReply rs = { REP_RESULT };
4817 Modifications mod = {{ 0 }};
4819 thrctx = ldap_pvt_thread_pool_context();
4821 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4824 mod.sml_numvals = 0;
4825 if ( qm->templates != NULL ) {
4826 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4827 for ( qc = tm->query; qc; qc = qc->next ) {
4830 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4831 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4839 op->o_dn = cm->db.be_rootdn;
4840 op->o_ndn = cm->db.be_rootndn;
4842 op->o_tag = LDAP_REQ_MODIFY;
4843 op->o_protocol = LDAP_VERSION3;
4844 cb.sc_response = slap_null_cb;
4845 op->o_callback = &cb;
4846 op->o_time = slap_get_time();
4847 op->o_do_not_cache = 1;
4848 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4850 op->o_req_dn = op->o_bd->be_suffix[0];
4851 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4853 mod.sml_op = LDAP_MOD_REPLACE;
4855 mod.sml_desc = ad_cachedQueryURL;
4856 mod.sml_type = ad_cachedQueryURL->ad_cname;
4857 mod.sml_values = vals;
4858 mod.sml_nvalues = NULL;
4859 mod.sml_next = NULL;
4860 Debug( pcache_debug,
4861 "%sSETTING CACHED QUERY URLS\n",
4862 vals == NULL ? "RE" : "", 0, 0 );
4864 op->orm_modlist = &mod;
4866 op->o_bd->be_modify( op, &rs );
4868 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4871 /* cleanup stuff inherited from the original database... */
4872 cm->db.be_limits = NULL;
4873 cm->db.be_acl = NULL;
4875 if ( cm->db.bd_info->bi_db_close ) {
4876 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4879 #ifdef PCACHE_MONITOR
4880 if ( rc == LDAP_SUCCESS ) {
4881 rc = pcache_monitor_db_close( be );
4883 #endif /* PCACHE_MONITOR */
4894 slap_overinst *on = (slap_overinst *)be->bd_info;
4895 cache_manager *cm = on->on_bi.bi_private;
4896 query_manager *qm = cm->qm;
4900 if ( cm->db.be_private != NULL ) {
4901 backend_stopdown_one( &cm->db );
4904 while ( (tm = qm->templates) != NULL ) {
4905 CachedQuery *qc, *qn;
4906 qm->templates = tm->qmnext;
4907 for ( qc = tm->query; qc; qc = qn ) {
4911 avl_free( tm->qbase, pcache_free_qbase );
4912 free( tm->querystr.bv_val );
4913 free( tm->bindfattrs );
4914 free( tm->bindftemp.bv_val );
4915 free( tm->bindfilterstr.bv_val );
4916 free( tm->bindbase.bv_val );
4917 filter_free( tm->bindfilter );
4918 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4919 free( tm->t_attrs.attrs );
4923 for ( i = 0; i < cm->numattrsets; i++ ) {
4926 /* Account of LDAP_NO_ATTRS */
4927 if ( !qm->attr_sets[i].count ) continue;
4929 for ( j = 0; !BER_BVISNULL( &qm->attr_sets[i].attrs[j].an_name ); j++ ) {
4930 if ( qm->attr_sets[i].attrs[j].an_desc &&
4931 ( qm->attr_sets[i].attrs[j].an_desc->ad_flags &
4932 SLAP_DESC_TEMPORARY ) ) {
4933 slap_sl_mfuncs.bmf_free( qm->attr_sets[i].attrs[j].an_desc, NULL );
4936 free( qm->attr_sets[i].attrs );
4938 free( qm->attr_sets );
4939 qm->attr_sets = NULL;
4941 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4942 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4946 #ifdef PCACHE_MONITOR
4947 pcache_monitor_db_destroy( be );
4948 #endif /* PCACHE_MONITOR */
4953 #ifdef PCACHE_CONTROL_PRIVDB
4955 Control ::= SEQUENCE {
4956 controlType LDAPOID,
4957 criticality BOOLEAN DEFAULT FALSE,
4958 controlValue OCTET STRING OPTIONAL }
4960 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4962 * criticality must be TRUE; controlValue must be absent.
4970 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4971 rs->sr_text = "privateDB control specified multiple times";
4972 return LDAP_PROTOCOL_ERROR;
4975 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4976 rs->sr_text = "privateDB control value not absent";
4977 return LDAP_PROTOCOL_ERROR;
4980 if ( !ctrl->ldctl_iscritical ) {
4981 rs->sr_text = "privateDB control criticality required";
4982 return LDAP_PROTOCOL_ERROR;
4985 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4987 return LDAP_SUCCESS;
4990 static char *extops[] = {
4991 LDAP_EXOP_MODIFY_PASSWD,
4994 #endif /* PCACHE_CONTROL_PRIVDB */
4996 static struct berval pcache_exop_MODIFY_PASSWD = BER_BVC( LDAP_EXOP_MODIFY_PASSWD );
4997 #ifdef PCACHE_EXOP_QUERY_DELETE
4998 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
5000 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
5001 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
5002 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
5005 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
5006 requestName [0] LDAPOID,
5007 requestValue [1] OCTET STRING OPTIONAL }
5009 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
5011 requestValue ::= SEQUENCE { CHOICE {
5013 entryDN [1] LDAPDN },
5014 queryID [2] OCTET STRING (SIZE(16))
5015 -- constrained to UUID }
5017 * Either baseDN or entryDN must be present, to allow database selection.
5019 * 1. if baseDN and queryID are present, then the query corresponding
5020 * to queryID is deleted;
5021 * 2. if baseDN is present and queryID is absent, then all queries
5023 * 3. if entryDN is present and queryID is absent, then all queries
5024 * corresponding to the queryID values present in entryDN are deleted;
5025 * 4. if entryDN and queryID are present, then all queries
5026 * corresponding to the queryID values present in entryDN are deleted,
5027 * but only if the value of queryID is contained in the entry;
5029 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
5030 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
5031 * or by removing the database files.
5033 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
5034 COMPONENTS OF LDAPResult,
5035 responseName [10] LDAPOID OPTIONAL,
5036 responseValue [11] OCTET STRING OPTIONAL }
5038 * responseName and responseValue must be absent.
5042 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
5043 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
5044 * - if ndn != NULL, it is set to the normalized DN in the request
5045 * corresponding to either the baseDN or the entryDN, according
5046 * to *tagp; memory is malloc'ed on the Operation's slab, and must
5047 * be freed by the caller.
5048 * - if uuid != NULL, it is set to point to the normalized UUID;
5049 * memory is malloc'ed on the Operation's slab, and must
5050 * be freed by the caller.
5053 pcache_parse_query_delete(
5057 struct berval *uuid,
5061 int rc = LDAP_SUCCESS;
5064 BerElementBuffer berbuf;
5065 BerElement *ber = (BerElement *)&berbuf;
5066 struct berval reqdata = BER_BVNULL;
5078 if ( in == NULL || in->bv_len == 0 ) {
5079 *text = "empty request data field in queryDelete exop";
5080 return LDAP_PROTOCOL_ERROR;
5083 ber_dupbv_x( &reqdata, in, ctx );
5085 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
5086 ber_init2( ber, &reqdata, 0 );
5088 tag = ber_scanf( ber, "{" /*}*/ );
5090 if ( tag == LBER_ERROR ) {
5091 Debug( LDAP_DEBUG_TRACE,
5092 "pcache_parse_query_delete: decoding error.\n",
5094 goto decoding_error;
5097 tag = ber_peek_tag( ber, &len );
5098 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
5099 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
5103 if ( ndn != NULL ) {
5106 tag = ber_scanf( ber, "m", &dn );
5107 if ( tag == LBER_ERROR ) {
5108 Debug( LDAP_DEBUG_TRACE,
5109 "pcache_parse_query_delete: DN parse failed.\n",
5111 goto decoding_error;
5114 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
5115 if ( rc != LDAP_SUCCESS ) {
5116 *text = "invalid DN in queryDelete exop request data";
5121 tag = ber_scanf( ber, "x" /* "m" */ );
5122 if ( tag == LBER_DEFAULT ) {
5123 goto decoding_error;
5127 tag = ber_peek_tag( ber, &len );
5130 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
5131 if ( uuid != NULL ) {
5133 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
5135 tag = ber_scanf( ber, "m", &bv );
5136 if ( tag == LBER_ERROR ) {
5137 Debug( LDAP_DEBUG_TRACE,
5138 "pcache_parse_query_delete: UUID parse failed.\n",
5140 goto decoding_error;
5143 if ( bv.bv_len != 16 ) {
5144 Debug( LDAP_DEBUG_TRACE,
5145 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5146 (unsigned long)bv.bv_len, 0, 0 );
5147 goto decoding_error;
5150 rc = lutil_uuidstr_from_normalized(
5151 bv.bv_val, bv.bv_len,
5152 uuidbuf, sizeof( uuidbuf ) );
5154 goto decoding_error;
5156 ber_str2bv( uuidbuf, rc, 1, uuid );
5160 tag = ber_skip_tag( ber, &len );
5161 if ( tag == LBER_DEFAULT ) {
5162 goto decoding_error;
5166 Debug( LDAP_DEBUG_TRACE,
5167 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5168 (unsigned long)len, 0, 0 );
5169 goto decoding_error;
5173 tag = ber_peek_tag( ber, &len );
5176 if ( tag != LBER_DEFAULT || len != 0 ) {
5178 Debug( LDAP_DEBUG_TRACE,
5179 "pcache_parse_query_delete: decoding error\n",
5181 rc = LDAP_PROTOCOL_ERROR;
5182 *text = "queryDelete data decoding error";
5185 if ( ndn && !BER_BVISNULL( ndn ) ) {
5186 slap_sl_free( ndn->bv_val, ctx );
5190 if ( uuid && !BER_BVISNULL( uuid ) ) {
5191 slap_sl_free( uuid->bv_val, ctx );
5196 if ( !BER_BVISNULL( &reqdata ) ) {
5197 ber_memfree_x( reqdata.bv_val, ctx );
5204 pcache_exop_query_delete(
5208 BackendDB *bd = op->o_bd;
5210 struct berval uuid = BER_BVNULL,
5212 char buf[ SLAP_TEXT_BUFLEN ];
5214 ber_tag_t tag = LBER_DEFAULT;
5216 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5220 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5221 &tag, &op->o_req_ndn, uuidp,
5222 &rs->sr_text, op->o_tmpmemctx );
5223 if ( rs->sr_err != LDAP_SUCCESS ) {
5227 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5228 assert( !BER_BVISNULL( &op->o_req_ndn ) );
5229 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
5231 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
5232 snprintf( &buf[ len ], sizeof( buf ) - len, " pcacheQueryId=\"%s\"", uuid.bv_val );
5235 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
5236 op->o_log_prefix, buf, 0 );
5238 op->o_req_dn = op->o_req_ndn;
5240 op->o_bd = select_backend( &op->o_req_ndn, 0 );
5241 if ( op->o_bd == NULL ) {
5242 send_ldap_error( op, rs, LDAP_NO_SUCH_OBJECT,
5243 "no global superior knowledge" );
5245 rs->sr_err = backend_check_restrictions( op, rs,
5246 (struct berval *)&pcache_exop_QUERY_DELETE );
5247 if ( rs->sr_err != LDAP_SUCCESS ) {
5251 if ( op->o_bd->be_extended == NULL ) {
5252 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
5253 "backend does not support extended operations" );
5257 op->o_bd->be_extended( op, rs );
5260 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
5261 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
5262 BER_BVZERO( &op->o_req_ndn );
5263 BER_BVZERO( &op->o_req_dn );
5266 if ( !BER_BVISNULL( &uuid ) ) {
5267 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5274 #endif /* PCACHE_EXOP_QUERY_DELETE */
5277 pcache_op_extended( Operation *op, SlapReply *rs )
5279 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5280 cache_manager *cm = on->on_bi.bi_private;
5282 #ifdef PCACHE_CONTROL_PRIVDB
5283 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
5284 return pcache_op_privdb( op, rs );
5286 #endif /* PCACHE_CONTROL_PRIVDB */
5288 #ifdef PCACHE_EXOP_QUERY_DELETE
5289 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
5290 struct berval uuid = BER_BVNULL;
5291 ber_tag_t tag = LBER_DEFAULT;
5293 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5294 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
5295 assert( rs->sr_err == LDAP_SUCCESS );
5297 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
5298 /* remove all queries related to the selected entry */
5299 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
5300 cm, &op->o_req_ndn, &uuid );
5302 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
5303 if ( !BER_BVISNULL( &uuid ) ) {
5304 /* remove the selected query */
5305 rs->sr_err = pcache_remove_query_from_cache( op,
5309 /* TODO: remove all queries */
5310 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
5311 rs->sr_text = "deletion of all queries not implemented";
5315 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5318 #endif /* PCACHE_EXOP_QUERY_DELETE */
5320 /* We only care if we're configured for Bind caching */
5321 if ( bvmatch( &op->ore_reqoid, &pcache_exop_MODIFY_PASSWD ) &&
5323 /* See if the local entry exists and has a password.
5324 * It's too much work to find the matching query, so
5325 * we just see if there's a hashed password to update.
5327 Operation op2 = *op;
5333 op2.o_dn = op->o_bd->be_rootdn;
5334 op2.o_ndn = op->o_bd->be_rootndn;
5335 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL,
5336 slap_schema.si_ad_userPassword, 0, &e );
5337 if ( rc == LDAP_SUCCESS && e ) {
5338 /* See if a recognized password is hashed here */
5339 Attribute *a = attr_find( e->e_attrs,
5340 slap_schema.si_ad_userPassword );
5341 if ( a && a->a_vals[0].bv_val[0] == '{' &&
5342 lutil_passwd_scheme( a->a_vals[0].bv_val )) {
5345 be_entry_release_r( &op2, e );
5349 rc = overlay_op_walk( op, rs, op_extended, on->on_info,
5351 if ( rc == LDAP_SUCCESS ) {
5352 req_pwdexop_s *qpw = &op->oq_pwdexop;
5354 /* We don't care if it succeeds or not */
5355 pc_setpw( &op2, &qpw->rs_new, cm );
5360 return SLAP_CB_CONTINUE;
5364 pcache_entry_release( Operation *op, Entry *e, int rw )
5366 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5367 cache_manager *cm = on->on_bi.bi_private;
5368 BackendDB *db = op->o_bd;
5372 rc = be_entry_release_rw( op, e, rw );
5377 #ifdef PCACHE_MONITOR
5380 pcache_monitor_update(
5386 cache_manager *cm = (cache_manager *) priv;
5387 query_manager *qm = cm->qm;
5390 BerVarray vals = NULL;
5392 attr_delete( &e->e_attrs, ad_cachedQueryURL );
5393 if ( ( SLAP_OPATTRS( rs->sr_attr_flags ) || ad_inlist( ad_cachedQueryURL, rs->sr_attrs ) )
5394 && qm->templates != NULL )
5398 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
5399 for ( qc = tm->query; qc; qc = qc->next ) {
5402 if ( query2url( op, qc, &bv, 1 ) == 0 ) {
5403 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
5409 if ( vals != NULL ) {
5410 attr_merge_normalize( e, ad_cachedQueryURL, vals, NULL );
5411 ber_bvarray_free_x( vals, op->o_tmpmemctx );
5417 char buf[ SLAP_TEXT_BUFLEN ];
5420 /* number of cached queries */
5421 a = attr_find( e->e_attrs, ad_numQueries );
5422 assert( a != NULL );
5425 bv.bv_len = snprintf( buf, sizeof( buf ), "%lu", cm->num_cached_queries );
5427 if ( a->a_nvals != a->a_vals ) {
5428 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5430 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5432 /* number of cached entries */
5433 a = attr_find( e->e_attrs, ad_numEntries );
5434 assert( a != NULL );
5437 bv.bv_len = snprintf( buf, sizeof( buf ), "%d", cm->cur_entries );
5439 if ( a->a_nvals != a->a_vals ) {
5440 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5442 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5445 return SLAP_CB_CONTINUE;
5449 pcache_monitor_free(
5453 struct berval values[ 2 ];
5454 Modification mod = { 0 };
5457 char textbuf[ SLAP_TEXT_BUFLEN ];
5461 /* NOTE: if slap_shutdown != 0, priv might have already been freed */
5464 /* Remove objectClass */
5465 mod.sm_op = LDAP_MOD_DELETE;
5466 mod.sm_desc = slap_schema.si_ad_objectClass;
5467 mod.sm_values = values;
5469 values[ 0 ] = oc_olmPCache->soc_cname;
5470 BER_BVZERO( &values[ 1 ] );
5472 rc = modify_delete_values( e, &mod, 1, &text,
5473 textbuf, sizeof( textbuf ) );
5474 /* don't care too much about return code... */
5477 mod.sm_values = NULL;
5478 mod.sm_desc = ad_cachedQueryURL;
5480 rc = modify_delete_values( e, &mod, 1, &text,
5481 textbuf, sizeof( textbuf ) );
5482 /* don't care too much about return code... */
5485 mod.sm_values = NULL;
5486 mod.sm_desc = ad_numQueries;
5488 rc = modify_delete_values( e, &mod, 1, &text,
5489 textbuf, sizeof( textbuf ) );
5490 /* don't care too much about return code... */
5493 mod.sm_values = NULL;
5494 mod.sm_desc = ad_numEntries;
5496 rc = modify_delete_values( e, &mod, 1, &text,
5497 textbuf, sizeof( textbuf ) );
5498 /* don't care too much about return code... */
5500 return SLAP_CB_CONTINUE;
5504 * call from within pcache_initialize()
5507 pcache_monitor_initialize( void )
5509 static int pcache_monitor_initialized = 0;
5511 if ( backend_info( "monitor" ) == NULL ) {
5515 if ( pcache_monitor_initialized++ ) {
5523 pcache_monitor_db_init( BackendDB *be )
5525 if ( pcache_monitor_initialize() == LDAP_SUCCESS ) {
5526 SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_MONITORING;
5533 pcache_monitor_db_open( BackendDB *be )
5535 slap_overinst *on = (slap_overinst *)be->bd_info;
5536 cache_manager *cm = on->on_bi.bi_private;
5537 Attribute *a, *next;
5538 monitor_callback_t *cb = NULL;
5541 monitor_extra_t *mbe;
5543 if ( !SLAP_DBMONITORING( be ) ) {
5547 mi = backend_info( "monitor" );
5548 if ( !mi || !mi->bi_extra ) {
5549 SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
5554 /* don't bother if monitor is not configured */
5555 if ( !mbe->is_configured() ) {
5556 static int warning = 0;
5558 if ( warning++ == 0 ) {
5559 Debug( LDAP_DEBUG_ANY, "pcache_monitor_db_open: "
5560 "monitoring disabled; "
5561 "configure monitor database to enable\n",
5568 /* alloc as many as required (plus 1 for objectClass) */
5569 a = attrs_alloc( 1 + 2 );
5575 a->a_desc = slap_schema.si_ad_objectClass;
5576 attr_valadd( a, &oc_olmPCache->soc_cname, NULL, 1 );
5580 struct berval bv = BER_BVC( "0" );
5582 next->a_desc = ad_numQueries;
5583 attr_valadd( next, &bv, NULL, 1 );
5584 next = next->a_next;
5586 next->a_desc = ad_numEntries;
5587 attr_valadd( next, &bv, NULL, 1 );
5588 next = next->a_next;
5591 cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
5592 cb->mc_update = pcache_monitor_update;
5593 cb->mc_free = pcache_monitor_free;
5594 cb->mc_private = (void *)cm;
5596 /* make sure the database is registered; then add monitor attributes */
5597 BER_BVZERO( &cm->monitor_ndn );
5598 rc = mbe->register_overlay( be, on, &cm->monitor_ndn );
5600 rc = mbe->register_entry_attrs( &cm->monitor_ndn, a, cb,
5617 /* store for cleanup */
5618 cm->monitor_cb = (void *)cb;
5620 /* we don't need to keep track of the attributes, because
5621 * bdb_monitor_free() takes care of everything */
5630 pcache_monitor_db_close( BackendDB *be )
5632 slap_overinst *on = (slap_overinst *)be->bd_info;
5633 cache_manager *cm = on->on_bi.bi_private;
5635 if ( cm->monitor_cb != NULL ) {
5636 BackendInfo *mi = backend_info( "monitor" );
5637 monitor_extra_t *mbe;
5639 if ( mi && &mi->bi_extra ) {
5641 mbe->unregister_entry_callback( &cm->monitor_ndn,
5642 (monitor_callback_t *)cm->monitor_cb,
5651 pcache_monitor_db_destroy( BackendDB *be )
5656 #endif /* PCACHE_MONITOR */
5658 static slap_overinst pcache;
5660 static char *obsolete_names[] = {
5665 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5667 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
5672 struct berval debugbv = BER_BVC("pcache");
5676 code = slap_loglevel_get( &debugbv, &pcache_debug );
5681 #ifdef PCACHE_CONTROL_PRIVDB
5682 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
5683 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
5684 parse_privdb_ctrl, &privDB_cid );
5685 if ( code != LDAP_SUCCESS ) {
5686 Debug( LDAP_DEBUG_ANY,
5687 "pcache_initialize: failed to register control %s (%d)\n",
5688 PCACHE_CONTROL_PRIVDB, code, 0 );
5691 #endif /* PCACHE_CONTROL_PRIVDB */
5693 #ifdef PCACHE_EXOP_QUERY_DELETE
5694 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
5695 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
5697 if ( code != LDAP_SUCCESS ) {
5698 Debug( LDAP_DEBUG_ANY,
5699 "pcache_initialize: unable to register queryDelete exop: %d.\n",
5703 #endif /* PCACHE_EXOP_QUERY_DELETE */
5705 argv[ 0 ] = "back-bdb/back-hdb monitor";
5710 for ( i = 0; s_oid[ i ].name; i++ ) {
5712 argv[ 1 ] = s_oid[ i ].name;
5713 argv[ 2 ] = s_oid[ i ].oid;
5715 if ( parse_oidm( &c, 0, NULL ) != 0 ) {
5716 Debug( LDAP_DEBUG_ANY, "pcache_initialize: "
5717 "unable to add objectIdentifier \"%s=%s\"\n",
5718 s_oid[ i ].name, s_oid[ i ].oid, 0 );
5723 for ( i = 0; s_ad[i].desc != NULL; i++ ) {
5724 code = register_at( s_ad[i].desc, s_ad[i].adp, 0 );
5726 Debug( LDAP_DEBUG_ANY,
5727 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
5730 (*s_ad[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
5733 for ( i = 0; s_oc[i].desc != NULL; i++ ) {
5734 code = register_oc( s_oc[i].desc, s_oc[i].ocp, 0 );
5736 Debug( LDAP_DEBUG_ANY,
5737 "pcache_initialize: register_oc #%d failed\n", i, 0, 0 );
5740 (*s_oc[i].ocp)->soc_flags |= SLAP_OC_HIDE;
5743 pcache.on_bi.bi_type = "pcache";
5744 pcache.on_bi.bi_obsolete_names = obsolete_names;
5745 pcache.on_bi.bi_db_init = pcache_db_init;
5746 pcache.on_bi.bi_db_config = pcache_db_config;
5747 pcache.on_bi.bi_db_open = pcache_db_open;
5748 pcache.on_bi.bi_db_close = pcache_db_close;
5749 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
5751 pcache.on_bi.bi_op_search = pcache_op_search;
5752 pcache.on_bi.bi_op_bind = pcache_op_bind;
5753 #ifdef PCACHE_CONTROL_PRIVDB
5754 pcache.on_bi.bi_op_compare = pcache_op_privdb;
5755 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
5756 pcache.on_bi.bi_op_modify = pcache_op_privdb;
5757 pcache.on_bi.bi_op_add = pcache_op_privdb;
5758 pcache.on_bi.bi_op_delete = pcache_op_privdb;
5759 #endif /* PCACHE_CONTROL_PRIVDB */
5760 pcache.on_bi.bi_extended = pcache_op_extended;
5762 pcache.on_bi.bi_entry_release_rw = pcache_entry_release;
5763 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
5765 pcache.on_bi.bi_cf_ocs = pcocs;
5767 code = config_register_schema( pccfg, pcocs );
5768 if ( code ) return code;
5770 return overlay_register( &pcache );
5773 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5774 int init_module(int argc, char *argv[]) {
5775 return pcache_initialize();
5779 #endif /* defined(SLAPD_OVER_PROXYCACHE) */