2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2013 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003-2009 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
36 #include "../back-monitor/back-monitor.h"
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, '=' );
463 AC_MEMCPY( t1, p1, i );
467 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
471 i = slap_bv2ad( &bv, &ad, text );
476 if ( *p2 == '<' || *p2 == '>' ) p2++;
477 if ( p2[1] != ')' ) {
479 while ( *p2 != ')' ) p2++;
484 descs = (AttributeDescription **)ch_realloc(descs,
485 (attr_cnt + 2)*sizeof(AttributeDescription *));
487 descs[attr_cnt++] = ad;
492 descs[attr_cnt] = NULL;
494 template->bv_val = temp2;
495 template->bv_len = t1 - temp2;
500 template_attrs( char *template, struct attr_set *set, AttributeName **ret,
511 AttributeDescription *ad;
512 AttributeName *attrs;
518 attrs = ch_calloc( set->count + 1, sizeof(AttributeName) );
519 for ( i=0; i < set->count; i++ )
520 attrs[i] = set->attrs[i];
522 alluser = an_find( attrs, slap_bv_all_user_attrs );
523 allop = an_find( attrs, slap_bv_all_operational_attrs );
526 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' ) p1++;
527 p2 = strchr( p1, '=' );
530 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
534 i = slap_bv2ad( &bv, &ad, text );
541 if ( ad == slap_schema.si_ad_objectClass )
544 if ( is_at_operational(ad->ad_type)) {
548 } else if ( alluser ) {
551 if ( !ad_inlist( ad, attrs )) {
552 attrs = (AttributeName *)ch_realloc(attrs,
553 (attr_cnt + 2)*sizeof(AttributeName));
555 attrs[attr_cnt].an_desc = ad;
556 attrs[attr_cnt].an_name = ad->ad_cname;
557 attrs[attr_cnt].an_oc = NULL;
558 attrs[attr_cnt].an_flags = 0;
559 BER_BVZERO( &attrs[attr_cnt+1].an_name );
567 *text = "couldn't parse template";
570 if ( !got_oc && !( set->flags & PC_GOT_OC )) {
571 attrs = (AttributeName *)ch_realloc(attrs,
572 (attr_cnt + 2)*sizeof(AttributeName));
574 ad = slap_schema.si_ad_objectClass;
575 attrs[attr_cnt].an_desc = ad;
576 attrs[attr_cnt].an_name = ad->ad_cname;
577 attrs[attr_cnt].an_oc = NULL;
578 attrs[attr_cnt].an_flags = 0;
579 BER_BVZERO( &attrs[attr_cnt+1].an_name );
587 * Turn an URL representing a formerly cached query into a cached query,
588 * and try to cache it
599 LDAPURLDesc *lud = NULL;
601 tempstr = BER_BVNULL,
606 unsigned long answerable_cnt;
609 #define GOT_UUID 0x1U
610 #define GOT_ATTRSET 0x2U
611 #define GOT_EXPIRY 0x4U
612 #define GOT_ANSWERABLE 0x8U
613 #define GOT_REFRESH 0x10U
614 #define GOT_ALL (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
617 rc = ldap_url_parse( url, &lud );
618 if ( rc != LDAP_URL_SUCCESS ) {
622 /* non-allowed fields */
623 if ( lud->lud_host != NULL ) {
628 if ( lud->lud_attrs != NULL ) {
634 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
639 /* required fields */
640 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
645 switch ( lud->lud_scope ) {
646 case LDAP_SCOPE_BASE:
647 case LDAP_SCOPE_ONELEVEL:
648 case LDAP_SCOPE_SUBTREE:
649 case LDAP_SCOPE_SUBORDINATE:
657 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
662 if ( lud->lud_exts == NULL ) {
667 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
668 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
669 struct berval tmpUUID;
670 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
672 if ( got & GOT_UUID ) {
677 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
678 if ( !BER_BVISEMPTY( &tmpUUID ) ) {
679 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
680 if ( rc != LDAP_SUCCESS ) {
686 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
687 if ( got & GOT_ATTRSET ) {
692 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
698 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
701 if ( got & GOT_EXPIRY ) {
706 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
710 expiry_time = (time_t)l;
713 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
714 if ( got & GOT_ANSWERABLE ) {
719 rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
723 got |= GOT_ANSWERABLE;
725 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
728 if ( got & GOT_REFRESH ) {
733 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
737 refresh_time = (time_t)l;
746 if ( got != GOT_ALL ) {
751 if ( !(got & GOT_REFRESH ))
754 /* ignore expired queries */
755 if ( expiry_time <= slap_get_time()) {
758 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
760 (void)remove_query_data( &op2, &uuid );
765 ber_str2bv( lud->lud_dn, 0, 0, &base );
766 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
767 if ( rc != LDAP_SUCCESS ) {
770 query.scope = lud->lud_scope;
771 query.filter = str2filter( lud->lud_filter );
772 if ( query.filter == NULL ) {
777 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
779 if ( filter2template( op, query.filter, &tempstr ) ) {
780 ch_free( tempstr.bv_val );
785 /* check for query containment */
786 qt = qm->attr_sets[attrset].templates;
787 for ( ; qt; qt = qt->qtnext ) {
788 /* find if template i can potentially answer tempstr */
789 if ( bvmatch( &qt->querystr, &tempstr ) ) {
799 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
801 cq->expiry_time = expiry_time;
802 cq->refresh_time = refresh_time;
804 cq->answerable_cnt = answerable_cnt;
807 /* it's now into cq->filter */
817 if ( query.filter != NULL ) filter_free( query.filter );
818 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
819 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
820 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
821 if ( lud != NULL ) ldap_free_urldesc( lud );
826 /* Return 1 for an added entry, else 0 */
832 struct berval* query_uuid )
835 Modifications* modlist = NULL;
836 const char* text = NULL;
838 char textbuf[SLAP_TEXT_BUFLEN];
839 size_t textlen = sizeof(textbuf);
841 SlapReply sreply = {REP_RESULT};
843 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
850 /* add queryId attribute */
851 attr_merge_one( e, ad_queryId, query_uuid, NULL );
853 /* append the attribute list from the fetched entry */
854 e->e_attrs->a_next = attr;
856 op->o_tag = LDAP_REQ_ADD;
857 op->o_protocol = LDAP_VERSION3;
858 op->o_callback = &cb;
859 op->o_time = slap_get_time();
860 op->o_do_not_cache = 1;
863 op->o_req_dn = e->e_name;
864 op->o_req_ndn = e->e_nname;
865 rc = op->o_bd->be_add( op, &sreply );
867 if ( rc != LDAP_SUCCESS ) {
868 if ( rc == LDAP_ALREADY_EXISTS ) {
869 rs_reinit( &sreply, REP_RESULT );
870 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
871 modlist->sml_op = LDAP_MOD_ADD;
872 op->o_tag = LDAP_REQ_MODIFY;
873 op->orm_modlist = modlist;
874 op->o_managedsait = SLAP_CONTROL_CRITICAL;
875 op->o_bd->be_modify( op, &sreply );
876 slap_mods_free( modlist, 1 );
877 } else if ( rc == LDAP_REFERRAL ||
878 rc == LDAP_NO_SUCH_OBJECT ) {
879 syncrepl_add_glue( op, e );
888 if ( op->ora_e == e )
896 /* Length-ordered sort on normalized DNs */
897 static int pcache_dn_cmp( const void *v1, const void *v2 )
899 const Qbase *q1 = v1, *q2 = v2;
901 int rc = q1->base.bv_len - q2->base.bv_len;
903 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
907 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
910 dif = bv1->bv_len - bv2->bv_len;
912 if ( dif > 0 ) len -= dif;
913 len = memcmp( bv1->bv_val, bv2->bv_val, len );
919 /* compare the current value in each filter */
920 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
922 int rc, weight1, weight2;
924 switch( f1->f_choice ) {
925 case LDAP_FILTER_AND:
929 case LDAP_FILTER_PRESENT:
932 case LDAP_FILTER_EQUALITY:
940 switch( f2->f_choice ) {
941 case LDAP_FILTER_AND:
945 case LDAP_FILTER_PRESENT:
948 case LDAP_FILTER_EQUALITY:
956 rc = weight1 - weight2;
960 rc = pcache_filter_cmp( f1->f_and, f2->f_and );
965 rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
968 if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
970 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
971 if ( !BER_BVISNULL( &f2->f_sub_initial )) {
972 rc = lex_bvcmp( &f1->f_sub_initial,
973 &f2->f_sub_initial );
977 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
981 if ( f1->f_sub_any ) {
982 if ( f2->f_sub_any ) {
983 rc = lex_bvcmp( f1->f_sub_any,
988 } else if ( f2->f_sub_any ) {
992 if ( !BER_BVISNULL( &f1->f_sub_final )) {
993 if ( !BER_BVISNULL( &f2->f_sub_final )) {
994 rc = lex_bvcmp( &f1->f_sub_final,
999 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
1003 rc = lex_bvcmp( &f1->f_mr_value,
1017 rc = pcache_filter_cmp( f1, f2 );
1027 /* compare filters in each query */
1028 static int pcache_query_cmp( const void *v1, const void *v2 )
1030 const CachedQuery *q1 = v1, *q2 =v2;
1031 return pcache_filter_cmp( q1->filter, q2->filter );
1034 /* add query on top of LRU list */
1036 add_query_on_top (query_manager* qm, CachedQuery* qc)
1038 CachedQuery* top = qm->lru_top;
1045 qm->lru_bottom = qc;
1049 Debug( pcache_debug, "Base of added query = %s\n",
1050 qc->qbase->base.bv_val, 0, 0 );
1053 /* remove_query from LRU list */
1056 remove_query (query_manager* qm, CachedQuery* qc)
1065 down = qc->lru_down;
1071 qm->lru_bottom = up;
1077 up->lru_down = down;
1079 qc->lru_up = qc->lru_down = NULL;
1082 /* find and remove string2 from string1
1083 * from start if position = 1,
1084 * from end if position = 3,
1085 * from anywhere if position = 2
1086 * string1 is overwritten if position = 2.
1090 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
1094 if ( !ber2->bv_val )
1096 if ( !ber1->bv_val )
1099 switch( position ) {
1101 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
1102 ber2->bv_val, ber2->bv_len )) {
1104 ber1->bv_val += ber2->bv_len;
1105 ber1->bv_len -= ber2->bv_len;
1110 ber1->bv_val[ber1->bv_len] = '\0';
1111 temp = strstr( ber1->bv_val, ber2->bv_val );
1113 strcpy( temp, temp+ber2->bv_len );
1114 ber1->bv_len -= ber2->bv_len;
1120 if ( ber1->bv_len >= ber2->bv_len &&
1121 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
1124 ber1->bv_len -= ber2->bv_len;
1132 static struct berval*
1133 merge_init_final(Operation *op, struct berval* init, struct berval* any,
1134 struct berval* final)
1136 struct berval* merged, *temp;
1137 int i, any_count, count;
1139 for (any_count=0; any && any[any_count].bv_val; any_count++)
1149 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
1154 ber_dupbv_x( temp, init, op->o_tmpmemctx );
1158 for (i=0; i<any_count; i++) {
1159 ber_dupbv_x( temp, any, op->o_tmpmemctx );
1164 ber_dupbv_x( temp, final, op->o_tmpmemctx );
1171 /* Each element in stored must be found in incoming. Incoming is overwritten.
1174 strings_containment(struct berval* stored, struct berval* incoming)
1176 struct berval* element;
1180 for ( element=stored; element->bv_val != NULL; element++ ) {
1181 for (j = k; incoming[j].bv_val != NULL; j++) {
1182 if (find_and_remove(&(incoming[j]), element, 2)) {
1199 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
1203 struct berval init_incoming;
1204 struct berval final_incoming;
1205 struct berval *remaining_incoming = NULL;
1207 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
1208 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
1211 init_incoming = incoming->f_sub_initial;
1212 final_incoming = incoming->f_sub_final;
1214 if (find_and_remove(&init_incoming,
1215 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
1216 &(stored->f_sub_final), 3))
1218 if (stored->f_sub_any == NULL) {
1222 remaining_incoming = merge_init_final(op, &init_incoming,
1223 incoming->f_sub_any, &final_incoming);
1224 rc = strings_containment(stored->f_sub_any, remaining_incoming);
1225 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
1232 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
1234 struct berval incoming_val[2];
1237 incoming_val[1] = incoming->f_av_value;
1239 if (find_and_remove(incoming_val+1,
1240 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
1241 &(stored->f_sub_final), 3)) {
1242 if (stored->f_sub_any == NULL){
1246 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
1247 BER_BVZERO( incoming_val+1 );
1248 rc = strings_containment(stored->f_sub_any, incoming_val);
1249 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1256 filter_first( Filter *f )
1258 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1263 typedef struct fstack {
1264 struct fstack *fs_next;
1269 static CachedQuery *
1270 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
1274 MatchingRule* mrule = NULL;
1275 int res=0, eqpass= 0;
1278 CachedQuery cq, *qc;
1279 fstack *stack = NULL, *fsp;
1284 /* substring matches sort to the end, and we just have to
1285 * walk the entire list.
1287 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1288 ptr = tavl_end( root, 1 );
1289 dir = TAVL_DIR_LEFT;
1291 ptr = tavl_find3( root, &cq, pcache_query_cmp, &ret );
1292 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1301 /* an incoming substr query can only be satisfied by a cached
1304 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1305 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1308 /* an incoming eq query can be satisfied by a cached eq or substr
1311 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1312 if ( eqpass == 0 ) {
1313 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1314 nextpass: eqpass = 1;
1315 ptr = tavl_end( root, 1 );
1316 dir = TAVL_DIR_LEFT;
1320 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1326 switch (fs->f_choice) {
1327 case LDAP_FILTER_EQUALITY:
1328 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1329 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1333 case LDAP_FILTER_GE:
1334 case LDAP_FILTER_LE:
1335 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1342 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1343 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1344 &(fi->f_ava->aa_value),
1345 &(fs->f_ava->aa_value), &text);
1346 if (rc != LDAP_SUCCESS) {
1349 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1352 switch (fs->f_choice) {
1353 case LDAP_FILTER_OR:
1354 case LDAP_FILTER_AND:
1356 /* save our stack position */
1357 fsp = op->o_tmpalloc(sizeof(fstack), op->o_tmpmemctx);
1358 fsp->fs_next = stack;
1359 fsp->fs_fs = fs->f_next;
1360 fsp->fs_fi = fi->f_next;
1367 case LDAP_FILTER_SUBSTRINGS:
1368 /* check if the equality query can be
1369 * answered with cached substring query */
1370 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1371 && substr_containment_equality( op,
1374 /* check if the substring query can be
1375 * answered with cached substring query */
1376 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1377 ) && substr_containment_substr( op,
1383 case LDAP_FILTER_PRESENT:
1388 case LDAP_FILTER_EQUALITY:
1394 case LDAP_FILTER_GE:
1395 if (mrule && ret >= 0)
1400 case LDAP_FILTER_LE:
1401 if (mrule && ret <= 0)
1406 case LDAP_FILTER_NOT:
1412 if (!fs && !fi && stack) {
1415 stack = fsp->fs_next;
1418 op->o_tmpfree(fsp, op->o_tmpmemctx);
1420 } while((res) && (fi != NULL) && (fs != NULL));
1424 ptr = tavl_next( ptr, dir );
1429 /* check whether query is contained in any of
1430 * the cached queries in template
1432 static CachedQuery *
1433 query_containment(Operation *op, query_manager *qm,
1435 QueryTemplate *templa)
1438 int depth = 0, tscope;
1439 Qbase qbase, *qbptr = NULL;
1442 if (query->filter != NULL) {
1445 Debug( pcache_debug, "Lock QC index = %p\n",
1446 (void *) templa, 0, 0 );
1447 qbase.base = query->base;
1449 first = filter_first( query->filter );
1451 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1454 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1456 tscope = query->scope;
1457 /* Find a matching scope:
1458 * match at depth 0 OK
1461 * subord at depth > 0 OK
1462 * subtree at any depth OK
1464 * subtree or subord at any depth OK
1466 * subtree or subord at any depth OK
1468 * subord at depth > 0 OK
1469 * subtree at any depth OK
1471 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1472 switch ( query->scope ) {
1473 case LDAP_SCOPE_BASE:
1474 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1475 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1476 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1478 case LDAP_SCOPE_ONE:
1479 if ( tscope == LDAP_SCOPE_BASE )
1480 tscope = LDAP_SCOPE_ONE;
1481 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1482 if ( !depth ) break;
1483 if ( tscope < LDAP_SCOPE_SUBTREE )
1484 tscope = LDAP_SCOPE_SUBTREE;
1486 case LDAP_SCOPE_SUBTREE:
1487 if ( tscope < LDAP_SCOPE_SUBTREE )
1488 tscope = LDAP_SCOPE_SUBTREE;
1489 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1491 case LDAP_SCOPE_CHILDREN:
1492 if ( tscope < LDAP_SCOPE_SUBTREE )
1493 tscope = LDAP_SCOPE_SUBTREE;
1496 if ( !qbptr->scopes[tscope] ) continue;
1499 qc = find_filter( op, qbptr->scopes[tscope],
1500 query->filter, first );
1502 if ( qc->q_sizelimit ) {
1503 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1506 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1507 if (qm->lru_top != qc) {
1508 remove_query(qm, qc);
1509 add_query_on_top(qm, qc);
1511 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1516 if ( be_issuffix( op->o_bd, &qbase.base ))
1519 dnParent( &qbase.base, &pdn );
1524 Debug( pcache_debug,
1525 "Not answerable: Unlock QC index=%p\n",
1526 (void *) templa, 0, 0 );
1527 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1533 free_query (CachedQuery* qc)
1535 free(qc->q_uuid.bv_val);
1536 filter_free(qc->filter);
1537 ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1538 ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1539 memset(qc, 0, sizeof(*qc));
1544 /* Add query to query cache, the returned Query is locked for writing */
1545 static CachedQuery *
1550 QueryTemplate *templ,
1551 pc_caching_reason_t why,
1554 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1558 time_t ttl = 0, ttr = 0;
1561 new_cached_query->qtemp = templ;
1562 BER_BVZERO( &new_cached_query->q_uuid );
1563 new_cached_query->q_sizelimit = 0;
1565 now = slap_get_time();
1570 ttr = now + templ->ttr;
1574 ttl = templ->negttl;
1578 ttl = templ->limitttl;
1585 new_cached_query->expiry_time = now + ttl;
1586 new_cached_query->refresh_time = ttr;
1587 new_cached_query->bindref_time = 0;
1589 new_cached_query->bind_refcnt = 0;
1590 new_cached_query->answerable_cnt = 0;
1591 new_cached_query->refcnt = 1;
1592 ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1594 new_cached_query->lru_up = NULL;
1595 new_cached_query->lru_down = NULL;
1596 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1597 (long) new_cached_query->expiry_time,
1598 pc_caching_reason_str[ why ], 0 );
1600 new_cached_query->scope = query->scope;
1601 new_cached_query->filter = query->filter;
1602 new_cached_query->first = first = filter_first( query->filter );
1604 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1606 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1608 qb.base = query->base;
1610 /* Adding a query */
1611 Debug( pcache_debug, "Lock AQ index = %p\n",
1612 (void *) templ, 0, 0 );
1613 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1614 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1616 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1617 qbase->base.bv_len = qb.base.bv_len;
1618 qbase->base.bv_val = (char *)(qbase+1);
1619 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1620 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1621 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1623 new_cached_query->next = templ->query;
1624 new_cached_query->prev = NULL;
1625 new_cached_query->qbase = qbase;
1626 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1627 pcache_query_cmp, avl_dup_error );
1630 if (templ->query == NULL)
1631 templ->query_last = new_cached_query;
1633 templ->query->prev = new_cached_query;
1634 templ->query = new_cached_query;
1635 templ->no_of_queries++;
1637 ldap_pvt_thread_mutex_destroy(&new_cached_query->answerable_cnt_mutex);
1639 ldap_pvt_thread_rdwr_wunlock(&new_cached_query->rwlock);
1640 ldap_pvt_thread_rdwr_destroy( &new_cached_query->rwlock );
1641 ch_free( new_cached_query );
1642 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1643 query->filter, first );
1644 filter_free( query->filter );
1645 query->filter = NULL;
1647 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1648 (void *) templ, templ->no_of_queries, 0 );
1650 /* Adding on top of LRU list */
1652 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1653 add_query_on_top(qm, new_cached_query);
1654 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1656 Debug( pcache_debug, "Unlock AQ index = %p \n",
1657 (void *) templ, 0, 0 );
1658 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1660 return rc == 0 ? new_cached_query : NULL;
1664 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1666 if (!qc->prev && !qc->next) {
1667 template->query_last = template->query = NULL;
1668 } else if (qc->prev == NULL) {
1669 qc->next->prev = NULL;
1670 template->query = qc->next;
1671 } else if (qc->next == NULL) {
1672 qc->prev->next = NULL;
1673 template->query_last = qc->prev;
1675 qc->next->prev = qc->prev;
1676 qc->prev->next = qc->next;
1678 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1679 qc->qbase->queries--;
1680 if ( qc->qbase->queries == 0 ) {
1681 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1682 ch_free( qc->qbase );
1686 template->no_of_queries--;
1689 /* remove bottom query of LRU list from the query cache */
1691 * NOTE: slight change in functionality.
1693 * - if result->bv_val is NULL, the query at the bottom of the LRU
1695 * - otherwise, the query whose UUID is *result is removed
1696 * - if not found, result->bv_val is zeroed
1699 cache_replacement(query_manager* qm, struct berval *result)
1701 CachedQuery* bottom;
1702 QueryTemplate *temp;
1704 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1705 if ( BER_BVISNULL( result ) ) {
1706 bottom = qm->lru_bottom;
1709 Debug ( pcache_debug,
1710 "Cache replacement invoked without "
1711 "any query in LRU list\n", 0, 0, 0 );
1712 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1717 for ( bottom = qm->lru_bottom;
1719 bottom = bottom->lru_up )
1721 if ( bvmatch( result, &bottom->q_uuid ) ) {
1727 Debug ( pcache_debug,
1728 "Could not find query with uuid=\"%s\""
1729 "in LRU list\n", result->bv_val, 0, 0 );
1730 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1731 BER_BVZERO( result );
1736 temp = bottom->qtemp;
1737 remove_query(qm, bottom);
1738 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1740 *result = bottom->q_uuid;
1741 BER_BVZERO( &bottom->q_uuid );
1743 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1744 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1745 remove_from_template(bottom, temp);
1746 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1747 (void *) temp, temp->no_of_queries, 0 );
1748 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1749 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1754 struct query_info *next;
1766 struct query_info *qi;
1769 if ( rs->sr_type != REP_SEARCH ) return 0;
1771 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1772 if ( attr == NULL ) return 0;
1774 count = attr->a_numvals;
1775 assert( count > 0 );
1776 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1777 qi->next = op->o_callback->sc_private;
1778 op->o_callback->sc_private = qi;
1779 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1780 qi->del = ( count == 1 );
1788 struct berval *query_uuid )
1790 struct query_info *qi, *qnext;
1791 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
1792 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1793 Filter filter = {LDAP_FILTER_EQUALITY};
1794 SlapReply sreply = {REP_RESULT};
1795 slap_callback cb = { NULL, remove_func, NULL, NULL };
1798 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1799 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1800 filter.f_ava = &ava;
1801 filter.f_av_desc = ad_queryId;
1802 filter.f_av_value = *query_uuid;
1804 op->o_tag = LDAP_REQ_SEARCH;
1805 op->o_protocol = LDAP_VERSION3;
1806 op->o_callback = &cb;
1807 op->o_time = slap_get_time();
1808 op->o_do_not_cache = 1;
1810 op->o_req_dn = op->o_bd->be_suffix[0];
1811 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1812 op->ors_scope = LDAP_SCOPE_SUBTREE;
1813 op->ors_deref = LDAP_DEREF_NEVER;
1814 op->ors_slimit = SLAP_NO_LIMIT;
1815 op->ors_tlimit = SLAP_NO_LIMIT;
1816 op->ors_limit = NULL;
1817 op->ors_filter = &filter;
1818 op->ors_filterstr.bv_val = filter_str;
1819 op->ors_filterstr.bv_len = strlen(filter_str);
1820 op->ors_attrs = NULL;
1821 op->ors_attrsonly = 0;
1823 op->o_bd->be_search( op, &sreply );
1825 for ( qi=cb.sc_private; qi; qi=qnext ) {
1828 op->o_req_dn = qi->xdn;
1829 op->o_req_ndn = qi->xdn;
1830 rs_reinit( &sreply, REP_RESULT );
1833 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1834 query_uuid->bv_val, 0, 0 );
1836 op->o_tag = LDAP_REQ_DELETE;
1838 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1844 struct berval vals[2];
1846 vals[0] = *query_uuid;
1847 vals[1].bv_val = NULL;
1849 mod.sml_op = LDAP_MOD_DELETE;
1851 mod.sml_desc = ad_queryId;
1852 mod.sml_type = ad_queryId->ad_cname;
1853 mod.sml_values = vals;
1854 mod.sml_nvalues = NULL;
1855 mod.sml_numvals = 1;
1856 mod.sml_next = NULL;
1857 Debug( pcache_debug,
1858 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1859 query_uuid->bv_val, 0, 0 );
1861 op->orm_modlist = &mod;
1863 op->o_bd->be_modify( op, &sreply );
1865 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1866 op->o_tmpfree( qi, op->o_tmpmemctx );
1873 AttributeName* attrs,
1882 struct berval *fstr )
1884 AttributeDescription *ad;
1887 switch ( f->f_choice ) {
1888 case LDAP_FILTER_EQUALITY:
1890 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1891 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1892 assert( ret == len );
1893 fstr->bv_len += len;
1896 case LDAP_FILTER_GE:
1898 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1899 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1900 assert( ret == len );
1901 fstr->bv_len += len;
1904 case LDAP_FILTER_LE:
1906 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1907 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1908 assert( ret == len );
1909 fstr->bv_len += len;
1912 case LDAP_FILTER_APPROX:
1914 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1915 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1916 assert( ret == len );
1917 fstr->bv_len += len;
1920 case LDAP_FILTER_SUBSTRINGS:
1922 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1923 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1924 assert( ret == len );
1925 fstr->bv_len += len;
1928 case LDAP_FILTER_PRESENT:
1930 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1931 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1932 assert( ret == len );
1933 fstr->bv_len += len;
1936 case LDAP_FILTER_AND:
1937 case LDAP_FILTER_OR:
1938 case LDAP_FILTER_NOT: {
1940 fstr->bv_val[fstr->bv_len++] = '(';
1941 switch ( f->f_choice ) {
1942 case LDAP_FILTER_AND:
1943 fstr->bv_val[fstr->bv_len] = '&';
1945 case LDAP_FILTER_OR:
1946 fstr->bv_val[fstr->bv_len] = '|';
1948 case LDAP_FILTER_NOT:
1949 fstr->bv_val[fstr->bv_len] = '!';
1954 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1955 rc = filter2template( op, f, fstr );
1958 fstr->bv_val[fstr->bv_len++] = ')';
1959 fstr->bv_val[fstr->bv_len] = '\0';
1965 /* a filter should at least have room for "()",
1966 * an "=" and for a 1-char attr */
1967 strcpy( fstr->bv_val, "(?=)" );
1968 fstr->bv_len += STRLENOF("(?=)");
1975 #define BI_HASHED 0x01
1976 #define BI_DIDCB 0x02
1977 #define BI_LOOKUP 0x04
1981 typedef struct bindinfo {
1982 cache_manager *bi_cm;
1984 QueryTemplate *bi_templ;
1985 struct search_info *bi_si;
1987 slap_callback bi_cb;
1990 struct search_info {
1993 QueryTemplate *qtemp;
1994 AttributeName* save_attrs; /* original attributes, saved for response */
1995 int swap_saved_attrs;
2000 int slimit_exceeded;
2001 pc_caching_reason_t caching_reason;
2007 remove_query_and_data(
2010 struct berval *uuid )
2012 query_manager* qm = cm->qm;
2014 qm->crfunc( qm, uuid );
2015 if ( !BER_BVISNULL( uuid ) ) {
2018 Debug( pcache_debug,
2019 "Removing query UUID %s\n",
2020 uuid->bv_val, 0, 0 );
2021 return_val = remove_query_data( op, uuid );
2022 Debug( pcache_debug,
2023 "QUERY REMOVED, SIZE=%d\n",
2025 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
2026 cm->cur_entries -= return_val;
2027 cm->num_cached_queries--;
2028 Debug( pcache_debug,
2029 "STORED QUERIES = %lu\n",
2030 cm->num_cached_queries, 0, 0 );
2031 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
2032 Debug( pcache_debug,
2033 "QUERY REMOVED, CACHE ="
2035 cm->cur_entries, 0, 0 );
2040 * Callback used to fetch queryId values based on entryUUID;
2041 * used by pcache_remove_entries_from_cache()
2044 fetch_queryId_cb( Operation *op, SlapReply *rs )
2048 /* only care about searchEntry responses */
2049 if ( rs->sr_type != REP_SEARCH ) {
2053 /* allow only one response per entryUUID */
2054 if ( op->o_callback->sc_private != NULL ) {
2060 /* copy all queryId values into callback's private data */
2061 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2063 BerVarray vals = NULL;
2065 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
2066 op->o_callback->sc_private = (void *)vals;
2070 /* clear entry if required */
2071 rs_flush_entry( op, rs, (slap_overinst *) op->o_bd->bd_info );
2077 * Call that allows to remove a set of entries from the cache,
2078 * by forcing the removal of all the related queries.
2081 pcache_remove_entries_from_cache(
2084 BerVarray entryUUIDs )
2086 Connection conn = { 0 };
2087 OperationBuffer opbuf;
2089 slap_callback sc = { 0 };
2091 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
2092 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2093 AttributeName attrs[ 2 ] = {{{ 0 }}};
2097 void *thrctx = ldap_pvt_thread_pool_context();
2099 connection_fake_init( &conn, &opbuf, thrctx );
2107 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2108 op->ors_scope = LDAP_SCOPE_SUBTREE;
2109 op->ors_deref = LDAP_DEREF_NEVER;
2110 f.f_choice = LDAP_FILTER_EQUALITY;
2112 ava.aa_desc = slap_schema.si_ad_entryUUID;
2113 op->ors_filter = &f;
2115 op->ors_tlimit = SLAP_NO_LIMIT;
2116 op->ors_limit = NULL;
2117 attrs[ 0 ].an_desc = ad_queryId;
2118 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2119 op->ors_attrs = attrs;
2120 op->ors_attrsonly = 0;
2122 op->o_req_dn = cm->db.be_suffix[ 0 ];
2123 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2125 op->o_tag = LDAP_REQ_SEARCH;
2126 op->o_protocol = LDAP_VERSION3;
2127 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2129 op->o_dn = op->o_bd->be_rootdn;
2130 op->o_ndn = op->o_bd->be_rootndn;
2131 sc.sc_response = fetch_queryId_cb;
2132 op->o_callback = ≻
2134 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
2135 BerVarray vals = NULL;
2136 SlapReply rs = { REP_RESULT };
2138 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
2139 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
2140 op->ors_filterstr.bv_val = filtbuf;
2141 ava.aa_value = entryUUIDs[ s ];
2143 rc = op->o_bd->be_search( op, &rs );
2144 if ( rc != LDAP_SUCCESS ) {
2148 vals = (BerVarray)op->o_callback->sc_private;
2149 if ( vals != NULL ) {
2152 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2153 struct berval val = vals[ i ];
2155 remove_query_and_data( op, cm, &val );
2157 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2158 ch_free( val.bv_val );
2162 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2163 op->o_callback->sc_private = NULL;
2171 * Call that allows to remove a query from the cache.
2174 pcache_remove_query_from_cache(
2177 struct berval *queryid )
2179 Operation op2 = *op;
2183 /* remove the selected query */
2184 remove_query_and_data( &op2, cm, queryid );
2186 return LDAP_SUCCESS;
2190 * Call that allows to remove a set of queries related to an entry
2191 * from the cache; if queryid is not null, the entry must belong to
2192 * the query indicated by queryid.
2195 pcache_remove_entry_queries_from_cache(
2199 struct berval *queryid )
2201 Connection conn = { 0 };
2202 OperationBuffer opbuf;
2204 slap_callback sc = { 0 };
2205 SlapReply rs = { REP_RESULT };
2207 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
2208 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2209 AttributeName attrs[ 2 ] = {{{ 0 }}};
2212 BerVarray vals = NULL;
2215 void *thrctx = ldap_pvt_thread_pool_context();
2217 connection_fake_init( &conn, &opbuf, thrctx );
2225 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2226 op->ors_scope = LDAP_SCOPE_BASE;
2227 op->ors_deref = LDAP_DEREF_NEVER;
2228 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
2229 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
2230 f.f_choice = LDAP_FILTER_PRESENT;
2231 f.f_desc = slap_schema.si_ad_objectClass;
2234 op->ors_filterstr.bv_len = snprintf( filter_str,
2235 sizeof( filter_str ), "(%s=%s)",
2236 ad_queryId->ad_cname.bv_val, queryid->bv_val );
2237 f.f_choice = LDAP_FILTER_EQUALITY;
2239 f.f_av_desc = ad_queryId;
2240 f.f_av_value = *queryid;
2242 op->ors_filter = &f;
2244 op->ors_tlimit = SLAP_NO_LIMIT;
2245 op->ors_limit = NULL;
2246 attrs[ 0 ].an_desc = ad_queryId;
2247 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2248 op->ors_attrs = attrs;
2249 op->ors_attrsonly = 0;
2251 op->o_req_dn = *ndn;
2252 op->o_req_ndn = *ndn;
2254 op->o_tag = LDAP_REQ_SEARCH;
2255 op->o_protocol = LDAP_VERSION3;
2256 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2258 op->o_dn = op->o_bd->be_rootdn;
2259 op->o_ndn = op->o_bd->be_rootndn;
2260 sc.sc_response = fetch_queryId_cb;
2261 op->o_callback = ≻
2263 rc = op->o_bd->be_search( op, &rs );
2264 if ( rc != LDAP_SUCCESS ) {
2268 vals = (BerVarray)op->o_callback->sc_private;
2269 if ( vals != NULL ) {
2272 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2273 struct berval val = vals[ i ];
2275 remove_query_and_data( op, cm, &val );
2277 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2278 ch_free( val.bv_val );
2282 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2285 return LDAP_SUCCESS;
2291 struct berval *query_uuid )
2293 struct search_info *si = op->o_callback->sc_private;
2294 slap_overinst *on = si->on;
2295 cache_manager *cm = on->on_bi.bi_private;
2298 struct berval crp_uuid;
2299 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2301 Connection conn = {0};
2302 OperationBuffer opbuf;
2303 void *thrctx = ldap_pvt_thread_pool_context();
2305 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2306 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2308 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2309 op_tmp = &opbuf.ob_op;
2310 op_tmp->o_bd = &cm->db;
2311 op_tmp->o_dn = cm->db.be_rootdn;
2312 op_tmp->o_ndn = cm->db.be_rootndn;
2314 Debug( pcache_debug, "UUID for query being added = %s\n",
2317 for ( e=si->head; e; e=si->head ) {
2318 si->head = e->e_private;
2319 e->e_private = NULL;
2320 while ( cm->cur_entries > (cm->max_entries) ) {
2321 BER_BVZERO( &crp_uuid );
2322 remove_query_and_data( op_tmp, cm, &crp_uuid );
2325 return_val = merge_entry(op_tmp, e, 0, query_uuid);
2326 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2327 cm->cur_entries += return_val;
2328 Debug( pcache_debug,
2329 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2330 cm->cur_entries, 0, 0 );
2332 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2339 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2340 slap_callback *cb = op->o_callback;
2341 struct search_info *si = cb->sc_private;
2342 slap_overinst *on = si->on;
2343 cache_manager *cm = on->on_bi.bi_private;
2344 query_manager* qm = cm->qm;
2346 if ( rs->sr_type == REP_RESULT ||
2347 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2349 if ( si->swap_saved_attrs ) {
2350 rs->sr_attrs = si->save_attrs;
2351 op->ors_attrs = si->save_attrs;
2353 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) &&
2354 si->caching_reason == PC_IGNORE )
2356 filter_free( si->query.filter );
2358 /* duplicate query, free it */
2360 for (;si->head; si->head=e) {
2361 e = si->head->e_private;
2362 si->head->e_private = NULL;
2363 entry_free(si->head);
2367 } else if ( si->caching_reason != PC_IGNORE ) {
2368 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2369 si->qtemp, si->caching_reason, 1 );
2372 switch ( si->caching_reason ) {
2374 cache_entries( op, &qc->q_uuid );
2377 si->pbi->bi_cq = qc;
2382 qc->q_sizelimit = rs->sr_nentries;
2392 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2393 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2394 cm->num_cached_queries++;
2395 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2396 cm->num_cached_queries, 0, 0 );
2397 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2399 /* If the consistency checker suspended itself,
2402 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2403 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2404 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2406 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2408 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2411 } else if ( si->count ) {
2412 /* duplicate query, free it */
2414 for (;si->head; si->head=e) {
2415 e = si->head->e_private;
2416 si->head->e_private = NULL;
2417 entry_free(si->head);
2422 filter_free( si->query.filter );
2425 op->o_callback = op->o_callback->sc_next;
2426 op->o_tmpfree( cb, op->o_tmpmemctx );
2429 return SLAP_CB_CONTINUE;
2437 struct search_info *si = op->o_callback->sc_private;
2439 if ( si->swap_saved_attrs ) {
2440 rs->sr_attrs = si->save_attrs;
2441 rs->sr_attr_flags = slap_attr_flags( si->save_attrs );
2442 op->ors_attrs = si->save_attrs;
2445 if ( rs->sr_type == REP_SEARCH ) {
2448 /* don't return more entries than requested by the client */
2449 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2450 si->slimit_exceeded = 1;
2453 /* If we haven't exceeded the limit for this query,
2454 * build a chain of answers to store. If we hit the
2455 * limit, empty the chain and ignore the rest.
2458 slap_overinst *on = si->on;
2459 cache_manager *cm = on->on_bi.bi_private;
2461 /* check if the entry contains undefined
2462 * attributes/objectClasses (ITS#5680) */
2463 if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2464 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2465 op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
2469 /* check for malformed entries: attrs with no values */
2471 Attribute *a = rs->sr_entry->e_attrs;
2472 for (; a; a=a->a_next) {
2473 if ( !a->a_numvals ) {
2474 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2475 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2476 a->a_desc->ad_cname.bv_val );
2482 if ( si->count < si->max ) {
2484 e = entry_dup( rs->sr_entry );
2485 if ( !si->head ) si->head = e;
2486 if ( si->tail ) si->tail->e_private = e;
2493 for (;si->head; si->head=e) {
2494 e = si->head->e_private;
2495 si->head->e_private = NULL;
2496 entry_free(si->head);
2501 if ( si->slimit_exceeded ) {
2504 } else if ( rs->sr_type == REP_RESULT ) {
2507 if ( rs->sr_err == LDAP_SUCCESS ) {
2508 si->caching_reason = PC_POSITIVE;
2510 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2511 && si->qtemp->limitttl )
2515 si->caching_reason = PC_SIZELIMIT;
2516 for (;si->head; si->head=e) {
2517 e = si->head->e_private;
2518 si->head->e_private = NULL;
2519 entry_free(si->head);
2523 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2524 rs->sr_err == LDAP_SUCCESS )
2526 si->caching_reason = PC_NEGATIVE;
2530 if ( si->slimit_exceeded ) {
2531 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2535 return SLAP_CB_CONTINUE;
2538 /* NOTE: this is a quick workaround to let pcache minimally interact
2539 * with pagedResults. A more articulated solutions would be to
2540 * perform the remote query without control and cache all results,
2541 * performing the pagedResults search only within the client
2542 * and the proxy. This requires pcache to understand pagedResults. */
2544 pcache_chk_controls(
2548 const char *non = "";
2549 const char *stripped = "";
2551 switch( op->o_pagedresults ) {
2552 case SLAP_CONTROL_NONCRITICAL:
2554 stripped = "; stripped";
2557 case SLAP_CONTROL_CRITICAL:
2558 Debug( pcache_debug, "%s: "
2559 "%scritical pagedResults control "
2560 "disabled with proxy cache%s.\n",
2561 op->o_log_prefix, non, stripped );
2563 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2567 rs->sr_err = SLAP_CB_CONTINUE;
2575 pc_setpw( Operation *op, struct berval *pwd, cache_manager *cm )
2577 struct berval vals[2];
2580 const char *text = NULL;
2581 BER_BVZERO( &vals[0] );
2582 slap_passwd_hash( pwd, &vals[0], &text );
2583 if ( BER_BVISEMPTY( &vals[0] )) {
2584 Debug( pcache_debug, "pc_setpw: hash failed %s\n",
2590 BER_BVZERO( &vals[1] );
2594 SlapReply sr = { REP_RESULT };
2595 slap_callback cb = { 0, slap_null_cb, 0, 0 };
2598 mod.sml_op = LDAP_MOD_REPLACE;
2600 mod.sml_desc = slap_schema.si_ad_userPassword;
2601 mod.sml_type = mod.sml_desc->ad_cname;
2602 mod.sml_values = vals;
2603 mod.sml_nvalues = NULL;
2604 mod.sml_numvals = 1;
2605 mod.sml_next = NULL;
2607 op->o_tag = LDAP_REQ_MODIFY;
2608 op->orm_modlist = &mod;
2610 op->o_dn = op->o_bd->be_rootdn;
2611 op->o_ndn = op->o_bd->be_rootndn;
2612 op->o_callback = &cb;
2613 Debug( pcache_debug, "pc_setpw: CACHING BIND for %s\n",
2614 op->o_req_dn.bv_val, 0, 0 );
2615 rc = op->o_bd->be_modify( op, &sr );
2616 ch_free( vals[0].bv_val );
2621 typedef struct bindcacheinfo {
2627 pc_bind_save( Operation *op, SlapReply *rs )
2629 if ( rs->sr_err == LDAP_SUCCESS ) {
2630 bindcacheinfo *bci = op->o_callback->sc_private;
2631 slap_overinst *on = bci->on;
2632 cache_manager *cm = on->on_bi.bi_private;
2633 CachedQuery *qc = bci->qc;
2636 ldap_pvt_thread_rdwr_wlock( &qc->rwlock );
2637 if ( qc->bind_refcnt-- ) {
2638 Operation op2 = *op;
2639 if ( pc_setpw( &op2, &op->orb_cred, cm ) == LDAP_SUCCESS )
2640 bci->qc->bindref_time = op->o_time + bci->qc->qtemp->bindttr;
2645 ldap_pvt_thread_rdwr_wunlock( &qc->rwlock );
2646 if ( delete ) free_query(qc);
2648 return SLAP_CB_CONTINUE;
2652 pc_bind_attrs( Operation *op, Entry *e, QueryTemplate *temp,
2653 struct berval *fbv )
2656 struct berval *vals, pres = BER_BVC("*");
2660 vals = op->o_tmpalloc( temp->bindnattrs * sizeof( struct berval ),
2663 for ( i=0; i<temp->bindnattrs; i++ ) {
2664 a = attr_find( e->e_attrs, temp->bindfattrs[i] );
2665 if ( a && a->a_vals ) {
2666 vals[i] = a->a_vals[0];
2667 len += a->a_vals[0].bv_len;
2672 fbv->bv_len = len + temp->bindftemp.bv_len;
2673 fbv->bv_val = op->o_tmpalloc( fbv->bv_len + 1, op->o_tmpmemctx );
2675 p1 = temp->bindftemp.bv_val;
2680 if ( p1[0] == '=' && p1[1] == ')' ) {
2681 AC_MEMCPY( p2, vals[i].bv_val, vals[i].bv_len );
2682 p2 += vals[i].bv_len;
2688 op->o_tmpfree( vals, op->o_tmpmemctx );
2690 /* FIXME: are we sure str2filter_x can't fail?
2691 * caller needs to check */
2693 Filter *f = str2filter_x( op, fbv->bv_val );
2694 assert( f != NULL );
2699 /* Check if the requested entry is from the cache and has a valid
2700 * ttr and password hash
2703 pc_bind_search( Operation *op, SlapReply *rs )
2705 if ( rs->sr_type == REP_SEARCH ) {
2706 bindinfo *pbi = op->o_callback->sc_private;
2708 /* We only care if this is an already cached result and we're
2709 * below the refresh time, or we're offline.
2712 if (( pbi->bi_cm->cc_paused & PCACHE_CC_OFFLINE ) ||
2713 op->o_time < pbi->bi_cq->bindref_time ) {
2716 /* See if a recognized password is hashed here */
2717 a = attr_find( rs->sr_entry->e_attrs,
2718 slap_schema.si_ad_userPassword );
2719 if ( a && a->a_vals[0].bv_val[0] == '{' &&
2720 lutil_passwd_scheme( a->a_vals[0].bv_val ))
2721 pbi->bi_flags |= BI_HASHED;
2723 Debug( pcache_debug, "pc_bind_search: cache is stale, "
2724 "reftime: %ld, current time: %ld\n",
2725 pbi->bi_cq->bindref_time, op->o_time, 0 );
2727 } else if ( pbi->bi_si ) {
2728 /* This search result is going into the cache */
2732 filter_free( pbi->bi_si->query.filter );
2733 f = pc_bind_attrs( op, rs->sr_entry, pbi->bi_templ, &fbv );
2734 op->o_tmpfree( fbv.bv_val, op->o_tmpmemctx );
2735 pbi->bi_si->query.filter = filter_dup( f, NULL );
2736 filter_free_x( op, f, 1 );
2742 /* We always want pc_bind_search to run after the search handlers */
2744 pc_bind_resp( Operation *op, SlapReply *rs )
2746 bindinfo *pbi = op->o_callback->sc_private;
2747 if ( !( pbi->bi_flags & BI_DIDCB )) {
2748 slap_callback *sc = op->o_callback;
2749 while ( sc && sc->sc_response != pcache_response )
2752 sc = op->o_callback;
2753 pbi->bi_cb.sc_next = sc->sc_next;
2754 sc->sc_next = &pbi->bi_cb;
2755 pbi->bi_flags |= BI_DIDCB;
2757 return SLAP_CB_CONTINUE;
2760 #ifdef PCACHE_CONTROL_PRIVDB
2766 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2767 cache_manager *cm = on->on_bi.bi_private;
2768 slap_callback *save_cb;
2771 /* skip if control is unset */
2772 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2773 return SLAP_CB_CONTINUE;
2776 /* The cache DB isn't open yet */
2777 if ( cm->defer_db_open ) {
2778 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2779 "pcachePrivDB: cacheDB not available" );
2783 /* FIXME: might be a little bit exaggerated... */
2784 if ( !be_isroot( op ) ) {
2785 save_cb = op->o_callback;
2786 op->o_callback = NULL;
2787 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2788 "pcachePrivDB: operation not allowed" );
2789 op->o_callback = save_cb;
2794 /* map tag to operation */
2795 type = slap_req2op( op->o_tag );
2796 if ( type != SLAP_OP_LAST ) {
2800 /* execute, if possible */
2801 func = &cm->db.be_bind;
2802 if ( func[ type ] != NULL ) {
2803 Operation op2 = *op;
2807 rc = func[ type ]( &op2, rs );
2808 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2809 op->o_conn->c_authz_cookie = cm->db.be_private;
2816 /* otherwise fall back to error */
2817 save_cb = op->o_callback;
2818 op->o_callback = NULL;
2819 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2820 "operation not supported with pcachePrivDB control" );
2821 op->o_callback = save_cb;
2825 #endif /* PCACHE_CONTROL_PRIVDB */
2832 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2833 cache_manager *cm = on->on_bi.bi_private;
2834 QueryTemplate *temp;
2836 slap_callback cb = { 0 }, *sc;
2842 #ifdef PCACHE_CONTROL_PRIVDB
2843 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL )
2844 return pcache_op_privdb( op, rs );
2845 #endif /* PCACHE_CONTROL_PRIVDB */
2847 /* Skip if we're not configured for Binds, or cache DB isn't open yet */
2848 if ( !cm->cache_binds || cm->defer_db_open )
2849 return SLAP_CB_CONTINUE;
2851 /* First find a matching template with Bind info */
2852 for ( temp=cm->qm->templates; temp; temp=temp->qmnext ) {
2853 if ( temp->bindttr && dnIsSuffix( &op->o_req_ndn, &temp->bindbase ))
2856 /* Didn't find a suitable template, just passthru */
2858 return SLAP_CB_CONTINUE;
2860 /* See if the entry is already locally cached. If so, we can
2861 * populate the query filter to retrieve the cached query. We
2862 * need to check the bindrefresh time in the query.
2865 op2.o_dn = op->o_bd->be_rootdn;
2866 op2.o_ndn = op->o_bd->be_rootndn;
2871 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL, NULL, 0, &e );
2872 if ( rc == LDAP_SUCCESS && e ) {
2873 bi.bi_flags |= BI_LOOKUP;
2874 op2.ors_filter = pc_bind_attrs( op, e, temp, &op2.ors_filterstr );
2875 be_entry_release_r( &op2, e );
2877 op2.ors_filter = temp->bindfilter;
2878 op2.ors_filterstr = temp->bindfilterstr;
2881 op2.o_bd = op->o_bd;
2882 op2.o_tag = LDAP_REQ_SEARCH;
2883 op2.ors_scope = LDAP_SCOPE_BASE;
2884 op2.ors_deref = LDAP_DEREF_NEVER;
2886 op2.ors_tlimit = SLAP_NO_LIMIT;
2887 op2.ors_limit = NULL;
2888 op2.ors_attrs = cm->qm->attr_sets[temp->attr_set_index].attrs;
2889 op2.ors_attrsonly = 0;
2891 /* We want to invoke search at the same level of the stack
2892 * as we're already at...
2899 bi.bi_cb.sc_response = pc_bind_search;
2900 bi.bi_cb.sc_cleanup = NULL;
2901 bi.bi_cb.sc_private = &bi;
2902 cb.sc_private = &bi;
2903 cb.sc_response = pc_bind_resp;
2904 op2.o_callback = &cb;
2905 overlay_op_walk( &op2, rs, op_search, on->on_info, on );
2907 /* OK, just bind locally */
2908 if ( bi.bi_flags & BI_HASHED ) {
2910 BackendDB *be = op->o_bd;
2913 Debug( pcache_debug, "pcache_op_bind: CACHED BIND for %s\n",
2914 op->o_req_dn.bv_val, 0, 0 );
2916 if ( op->o_bd->be_bind( op, rs ) == LDAP_SUCCESS ) {
2917 op->o_conn->c_authz_cookie = cm->db.be_private;
2920 ldap_pvt_thread_rdwr_wlock( &bi.bi_cq->rwlock );
2921 if ( !bi.bi_cq->bind_refcnt-- ) {
2924 ldap_pvt_thread_rdwr_wunlock( &bi.bi_cq->rwlock );
2925 if ( delete ) free_query( bi.bi_cq );
2929 /* We have a cached query to work with */
2931 sc = op->o_tmpalloc( sizeof(slap_callback) + sizeof(bindcacheinfo),
2933 sc->sc_response = pc_bind_save;
2934 sc->sc_cleanup = NULL;
2935 sc->sc_private = sc+1;
2936 bci = sc->sc_private;
2937 sc->sc_next = op->o_callback;
2938 op->o_callback = sc;
2942 return SLAP_CB_CONTINUE;
2945 static slap_response refresh_merge;
2952 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2953 cache_manager *cm = on->on_bi.bi_private;
2954 query_manager* qm = cm->qm;
2959 QueryTemplate *qtemp = NULL;
2960 bindinfo *pbi = NULL;
2963 CachedQuery *answerable = NULL;
2966 struct berval tempstr;
2968 #ifdef PCACHE_CONTROL_PRIVDB
2969 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2970 return pcache_op_privdb( op, rs );
2972 #endif /* PCACHE_CONTROL_PRIVDB */
2974 /* The cache DB isn't open yet */
2975 if ( cm->defer_db_open ) {
2976 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2977 "pcachePrivDB: cacheDB not available" );
2981 /* pickup runtime ACL changes */
2982 cm->db.be_acl = op->o_bd->be_acl;
2985 /* See if we're processing a Bind request
2986 * or a cache refresh */
2987 slap_callback *cb = op->o_callback;
2989 for ( ; cb; cb=cb->sc_next ) {
2990 if ( cb->sc_response == pc_bind_resp ) {
2991 pbi = cb->sc_private;
2994 if ( cb->sc_response == refresh_merge ) {
2995 /* This is a refresh, do not search the cache */
2996 return SLAP_CB_CONTINUE;
3001 /* FIXME: cannot cache/answer requests with pagedResults control */
3003 query.filter = op->ors_filter;
3006 query.base = pbi->bi_templ->bindbase;
3007 query.scope = pbi->bi_templ->bindscope;
3008 attr_set = pbi->bi_templ->attr_set_index;
3010 qtemp = pbi->bi_templ;
3011 if ( pbi->bi_flags & BI_LOOKUP )
3012 answerable = qm->qcfunc(op, qm, &query, qtemp);
3015 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1,
3018 if ( filter2template( op, op->ors_filter, &tempstr ))
3020 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3021 return SLAP_CB_CONTINUE;
3024 Debug( pcache_debug, "query template of incoming query = %s\n",
3025 tempstr.bv_val, 0, 0 );
3028 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
3030 query.base = op->o_req_ndn;
3031 query.scope = op->ors_scope;
3033 /* check for query containment */
3034 if (attr_set > -1) {
3035 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
3036 for (; qt; qt = qt->qtnext ) {
3037 /* find if template i can potentially answer tempstr */
3038 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
3042 Debug( pcache_debug, "Entering QC, querystr = %s\n",
3043 op->ors_filterstr.bv_val, 0, 0 );
3044 answerable = qm->qcfunc(op, qm, &query, qt);
3046 /* if != NULL, rlocks qtemp->t_rwlock */
3051 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3055 BackendDB *save_bd = op->o_bd;
3057 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
3058 answerable->answerable_cnt++;
3059 /* we only care about refcnts if we're refreshing */
3060 if ( answerable->refresh_time )
3061 answerable->refcnt++;
3062 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
3063 answerable->answerable_cnt, 0, 0 );
3064 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
3066 ldap_pvt_thread_rdwr_wlock(&answerable->rwlock);
3067 if ( BER_BVISNULL( &answerable->q_uuid )) {
3068 /* No entries cached, just an empty result set */
3070 send_ldap_result( op, rs );
3072 /* Let Bind know we used a cached query */
3074 answerable->bind_refcnt++;
3075 pbi->bi_cq = answerable;
3079 if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
3081 /* The cached entry was already processed by any
3082 * other overlays, so don't let it get processed again.
3084 * This loop removes over_back_response from the stack.
3086 if ( overlay_callback_after_backover( op, &cb, 0) == 0 ) {
3087 slap_callback **scp;
3088 for ( scp = &op->o_callback; *scp != NULL;
3089 scp = &(*scp)->sc_next ) {
3090 if ( (*scp)->sc_next == &cb ) {
3097 i = cm->db.bd_info->bi_op_search( op, rs );
3099 ldap_pvt_thread_rdwr_wunlock(&answerable->rwlock);
3100 /* locked by qtemp->qcfunc (query_containment) */
3101 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
3106 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
3108 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3109 if (cm->num_cached_queries >= cm->max_queries) {
3112 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3114 if (op->ors_attrsonly)
3119 struct search_info *si;
3121 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
3122 query.filter = filter_dup(op->ors_filter, NULL);
3124 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
3125 cb->sc_response = pcache_response;
3126 cb->sc_cleanup = pcache_op_cleanup;
3127 cb->sc_private = (cb+1);
3128 si = cb->sc_private;
3132 si->max = cm->num_entries_limit ;
3136 si->slimit_exceeded = 0;
3137 si->caching_reason = PC_IGNORE;
3138 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
3139 si->slimit = op->ors_slimit;
3140 op->ors_slimit = cm->num_entries_limit;
3144 si->swap_saved_attrs = 1;
3145 si->save_attrs = op->ors_attrs;
3150 op->ors_attrs = qtemp->t_attrs.attrs;
3152 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3153 cb->sc_next = op->o_callback;
3154 op->o_callback = cb;
3157 slap_callback **pcb;
3159 /* need to move the callback at the end, in case other
3160 * overlays are present, so that the final entry is
3161 * actually cached */
3163 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
3168 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
3172 return SLAP_CB_CONTINUE;
3177 AttributeName* attrs,
3185 for ( ; attrs[i].an_name.bv_val; i++ ) {
3186 /* only count valid attribute names
3187 * (searches ignore others, this overlay does the same) */
3188 if ( attrs[i].an_desc ) {
3194 /* recognize default or explicit single "*" */
3196 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_all_user_attrs ) ) )
3199 attrs = slap_anlist_all_user_attributes;
3201 /* recognize implicit (no valid attributes) or explicit single "1.1" */
3202 } else if ( count == 0 ||
3203 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) )
3209 for ( i = 0; i < num; i++ ) {
3213 if ( count > qm->attr_sets[i].count ) {
3214 if ( qm->attr_sets[i].count &&
3215 bvmatch( &qm->attr_sets[i].attrs[0].an_name, slap_bv_all_user_attrs )) {
3222 if ( !qm->attr_sets[i].count ) {
3228 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
3229 if ( !a2->an_desc && !bvmatch( &a2->an_name, slap_bv_all_user_attrs ) ) continue;
3231 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
3249 /* Refresh a cached query:
3250 * 1: Replay the query on the remote DB and merge each entry into
3251 * the local DB. Remember the DNs of each remote entry.
3252 * 2: Search the local DB for all entries matching this queryID.
3253 * Delete any entry whose DN is not in the list from (1).
3255 typedef struct dnlist {
3256 struct dnlist *next;
3261 typedef struct refresh_info {
3269 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
3271 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
3273 dn->dn.bv_len = bvdn->bv_len;
3274 dn->dn.bv_val = (char *)(dn+1);
3275 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
3276 dn->dn.bv_val[dn->dn.bv_len] = '\0';
3281 refresh_merge( Operation *op, SlapReply *rs )
3283 if ( rs->sr_type == REP_SEARCH ) {
3284 refresh_info *ri = op->o_callback->sc_private;
3290 ocb = op->o_callback;
3291 /* Find local entry, merge */
3292 op->o_bd = ri->ri_be;
3293 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
3294 if ( rc != LDAP_SUCCESS || e == NULL ) {
3295 /* No local entry, just add it. FIXME: we are not checking
3296 * the cache entry limit here
3298 merge_entry( op, rs->sr_entry, 1, &ri->ri_q->q_uuid );
3300 /* Entry exists, update it */
3303 Modifications *modlist, *mods = NULL;
3304 const char* text = NULL;
3305 char textbuf[SLAP_TEXT_BUFLEN];
3306 size_t textlen = sizeof(textbuf);
3307 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
3311 /* Get a copy of only the attrs we requested */
3312 for ( a=e->e_attrs; a; a=a->a_next ) {
3313 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
3314 *b = attr_alloc( a->a_desc );
3316 /* The actual values still belong to e */
3317 (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
3318 SLAP_ATTR_DONT_FREE_DATA;
3319 b = &((*b)->a_next);
3323 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
3324 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
3325 &mods, &modlist, 0 );
3326 be_entry_release_r( op, e );
3327 attrs_free( ne.e_attrs );
3328 slap_mods_free( modlist, 1 );
3329 /* mods is NULL if there are no changes */
3331 SlapReply rs2 = { REP_RESULT };
3332 struct berval dn = op->o_req_dn;
3333 struct berval ndn = op->o_req_ndn;
3334 op->o_tag = LDAP_REQ_MODIFY;
3335 op->orm_modlist = mods;
3336 op->o_req_dn = rs->sr_entry->e_name;
3337 op->o_req_ndn = rs->sr_entry->e_nname;
3338 op->o_callback = &cb;
3339 op->o_bd->be_modify( op, &rs2 );
3340 rs->sr_err = rs2.sr_err;
3341 rs_assert_done( &rs2 );
3342 slap_mods_free( mods, 1 );
3344 op->o_req_ndn = ndn;
3348 /* Add DN to list */
3349 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3351 if ( ri->ri_tail ) {
3352 ri->ri_tail->next = dnl;
3357 op->o_callback = ocb;
3363 refresh_purge( Operation *op, SlapReply *rs )
3365 if ( rs->sr_type == REP_SEARCH ) {
3366 refresh_info *ri = op->o_callback->sc_private;
3370 /* Did the entry exist on the remote? */
3371 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
3372 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
3373 dnlist *dnext = (*dn)->next;
3374 op->o_tmpfree( *dn, op->o_tmpmemctx );
3380 /* No, so put it on the list to delete */
3383 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3384 dnl->next = ri->ri_dels;
3386 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
3387 /* If ours is the only queryId, delete entry */
3388 dnl->delete = ( a->a_numvals == 1 );
3395 refresh_query( Operation *op, CachedQuery *query, slap_overinst *on )
3397 SlapReply rs = {REP_RESULT};
3398 slap_callback cb = { 0 };
3399 refresh_info ri = { 0 };
3400 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
3401 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3402 Filter filter = {LDAP_FILTER_EQUALITY};
3403 AttributeName attrs[ 2 ] = {{{ 0 }}};
3407 ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
3409 ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
3411 cb.sc_response = refresh_merge;
3412 cb.sc_private = &ri;
3415 ri.ri_be = op->o_bd;
3418 op->o_tag = LDAP_REQ_SEARCH;
3419 op->o_protocol = LDAP_VERSION3;
3420 op->o_callback = &cb;
3421 op->o_do_not_cache = 1;
3423 op->o_req_dn = query->qbase->base;
3424 op->o_req_ndn = query->qbase->base;
3425 op->ors_scope = query->scope;
3426 op->ors_deref = LDAP_DEREF_NEVER;
3427 op->ors_slimit = SLAP_NO_LIMIT;
3428 op->ors_tlimit = SLAP_NO_LIMIT;
3429 op->ors_limit = NULL;
3430 op->ors_filter = query->filter;
3431 filter2bv_x( op, query->filter, &op->ors_filterstr );
3432 op->ors_attrs = query->qtemp->t_attrs.attrs;
3433 op->ors_attrsonly = 0;
3435 op->o_bd = on->on_info->oi_origdb;
3436 rc = op->o_bd->be_search( op, &rs );
3438 op->o_bd = ri.ri_be;
3442 /* Get the DNs of all entries matching this query */
3443 cb.sc_response = refresh_purge;
3445 op->o_bd = ri.ri_be;
3446 op->o_req_dn = op->o_bd->be_suffix[0];
3447 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3448 op->ors_scope = LDAP_SCOPE_SUBTREE;
3449 op->ors_deref = LDAP_DEREF_NEVER;
3450 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
3451 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
3452 filter.f_ava = &ava;
3453 filter.f_av_desc = ad_queryId;
3454 filter.f_av_value = query->q_uuid;
3455 attrs[ 0 ].an_desc = ad_queryId;
3456 attrs[ 0 ].an_name = ad_queryId->ad_cname;
3457 op->ors_attrs = attrs;
3458 op->ors_attrsonly = 0;
3459 rs_reinit( &rs, REP_RESULT );
3460 rc = op->o_bd->be_search( op, &rs );
3461 if ( rc ) goto leave;
3463 while (( dn = ri.ri_dels )) {
3464 op->o_req_dn = dn->dn;
3465 op->o_req_ndn = dn->dn;
3466 rs_reinit( &rs, REP_RESULT );
3468 op->o_tag = LDAP_REQ_DELETE;
3469 op->o_bd->be_delete( op, &rs );
3472 struct berval vals[2];
3474 vals[0] = query->q_uuid;
3475 BER_BVZERO( &vals[1] );
3476 mod.sml_op = LDAP_MOD_DELETE;
3478 mod.sml_desc = ad_queryId;
3479 mod.sml_type = ad_queryId->ad_cname;
3480 mod.sml_values = vals;
3481 mod.sml_nvalues = NULL;
3482 mod.sml_numvals = 1;
3483 mod.sml_next = NULL;
3485 op->o_tag = LDAP_REQ_MODIFY;
3486 op->orm_modlist = &mod;
3487 op->o_bd->be_modify( op, &rs );
3489 ri.ri_dels = dn->next;
3490 op->o_tmpfree( dn, op->o_tmpmemctx );
3494 /* reset our local heap, we're done with it */
3495 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
3504 struct re_s *rtask = arg;
3505 slap_overinst *on = rtask->arg;
3506 cache_manager *cm = on->on_bi.bi_private;
3507 query_manager *qm = cm->qm;
3508 Connection conn = {0};
3509 OperationBuffer opbuf;
3512 CachedQuery *query, *qprev;
3513 int return_val, pause = PCACHE_CC_PAUSED;
3514 QueryTemplate *templ;
3516 /* Don't expire anything when we're offline */
3517 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
3518 pause = PCACHE_CC_OFFLINE;
3522 connection_fake_init( &conn, &opbuf, ctx );
3526 op->o_dn = cm->db.be_rootdn;
3527 op->o_ndn = cm->db.be_rootndn;
3531 for (templ = qm->templates; templ; templ=templ->qmnext) {
3533 if ( !templ->query_last ) continue;
3535 op->o_time = slap_get_time();
3536 if ( !templ->ttr ) {
3538 if ( templ->negttl && templ->negttl < ttl )
3539 ttl = templ->negttl;
3540 if ( templ->limitttl && templ->limitttl < ttl )
3541 ttl = templ->limitttl;
3542 /* The oldest timestamp that needs expiration checking */
3546 for ( query=templ->query_last; query; query=qprev ) {
3547 qprev = query->prev;
3548 if ( query->refresh_time && query->refresh_time < op->o_time ) {
3549 /* A refresh will extend the expiry if the query has been
3550 * referenced, but not if it's unreferenced. If the
3551 * expiration has been hit, then skip the refresh since
3552 * we're just going to discard the result anyway.
3554 if ( query->refcnt )
3555 query->expiry_time = op->o_time + templ->ttl;
3556 if ( query->expiry_time > op->o_time ) {
3557 refresh_query( op, query, on );
3562 if (query->expiry_time < op->o_time) {
3564 Debug( pcache_debug, "Lock CR index = %p\n",
3565 (void *) templ, 0, 0 );
3566 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
3567 if ( query == templ->query_last ) {
3569 remove_from_template(query, templ);
3570 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
3571 (void *) templ, templ->no_of_queries, 0 );
3572 Debug( pcache_debug, "Unlock CR index = %p\n",
3573 (void *) templ, 0, 0 );
3576 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3579 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
3580 remove_query(qm, query);
3581 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
3582 if ( BER_BVISNULL( &query->q_uuid ))
3585 return_val = remove_query_data(op, &query->q_uuid);
3586 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3588 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3589 cm->cur_entries -= return_val;
3590 cm->num_cached_queries--;
3591 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3592 cm->num_cached_queries, 0, 0 );
3593 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3594 Debug( pcache_debug,
3595 "STALE QUERY REMOVED, CACHE ="
3597 cm->cur_entries, 0, 0 );
3598 ldap_pvt_thread_rdwr_wlock( &query->rwlock );
3599 if ( query->bind_refcnt-- ) {
3604 ldap_pvt_thread_rdwr_wunlock( &query->rwlock );
3605 if ( rem ) free_query(query);
3606 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3607 } else if ( !templ->ttr && query->expiry_time > ttl ) {
3608 /* We don't need to check for refreshes, and this
3609 * query's expiry is too new, and all subsequent queries
3610 * will be newer yet. So stop looking.
3612 * If we have refreshes, then we always have to walk the
3613 * entire query list.
3621 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3622 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3623 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3625 /* If there were no queries, defer processing for a while */
3626 if ( cm->cc_paused != pause )
3627 cm->cc_paused = pause;
3628 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3630 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3635 #define MAX_ATTR_SETS 500
3648 static ConfigDriver pc_cf_gen;
3649 static ConfigLDAPadd pc_ldadd;
3650 static ConfigCfAdd pc_cfadd;
3652 static ConfigTable pccfg[] = {
3653 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3655 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3656 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3657 "DESC 'Proxy Cache basic parameters' "
3658 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3659 { "pcacheAttrset", "index> <attributes...",
3660 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3661 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3662 "DESC 'A set of attributes to cache' "
3663 "EQUALITY caseIgnoreMatch "
3664 "SYNTAX OMsDirectoryString )", NULL, NULL },
3665 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3667 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3668 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3669 "DESC 'Filter template, attrset, cache TTL, "
3670 "optional negative TTL, optional sizelimit TTL, "
3672 "EQUALITY caseIgnoreMatch "
3673 "SYNTAX OMsDirectoryString )", NULL, NULL },
3674 { "pcachePosition", "head|tail(default)",
3675 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3676 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3677 "DESC 'Response callback position in overlay stack' "
3678 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3679 { "pcacheMaxQueries", "queries",
3680 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3681 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3682 "DESC 'Maximum number of queries to cache' "
3683 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
3684 { "pcachePersist", "TRUE|FALSE",
3685 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3686 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3687 "DESC 'Save cached queries for hot restart' "
3688 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3689 { "pcacheValidate", "TRUE|FALSE",
3690 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3691 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3692 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3693 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3694 { "pcacheOffline", "TRUE|FALSE",
3695 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3696 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3697 "DESC 'Set cache to offline mode and disable expiration' "
3698 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3699 { "pcacheBind", "filter> <attrset-index> <TTR> <scope> <base",
3700 6, 6, 0, ARG_MAGIC|PC_BIND, pc_cf_gen,
3701 "( OLcfgOvAt:2.9 NAME 'olcPcacheBind' "
3702 "DESC 'Parameters for caching Binds' "
3703 "EQUALITY caseIgnoreMatch "
3704 "SYNTAX OMsDirectoryString )", NULL, NULL },
3705 { "pcache-", "private database args",
3706 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3709 /* Legacy keywords */
3710 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3712 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3714 { "proxyattrset", "index> <attributes...",
3715 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3717 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3718 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3720 { "response-callback", "head|tail(default)",
3721 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3723 { "proxyCacheQueries", "queries",
3724 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3726 { "proxySaveQueries", "TRUE|FALSE",
3727 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3729 { "proxyCheckCacheability", "TRUE|FALSE",
3730 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3733 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3736 static ConfigOCs pcocs[] = {
3737 { "( OLcfgOvOc:2.1 "
3738 "NAME 'olcPcacheConfig' "
3739 "DESC 'ProxyCache configuration' "
3740 "SUP olcOverlayConfig "
3741 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3742 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3743 "olcPcacheValidate $ olcPcacheOffline $ olcPcacheBind ) )",
3744 Cft_Overlay, pccfg, NULL, pc_cfadd },
3745 { "( OLcfgOvOc:2.2 "
3746 "NAME 'olcPcacheDatabase' "
3747 "DESC 'Cache database configuration' "
3748 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3752 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3755 pc_ldadd_cleanup( ConfigArgs *c )
3757 slap_overinst *on = c->ca_private;
3758 return pcache_db_open2( on, &c->reply );
3762 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3767 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3768 p->ce_bi->bi_cf_ocs != pcocs )
3769 return LDAP_CONSTRAINT_VIOLATION;
3771 on = (slap_overinst *)p->ce_bi;
3772 cm = on->on_bi.bi_private;
3774 /* Defer open if this is an LDAPadd */
3775 if ( CONFIG_ONLINE_ADD( ca ))
3776 ca->cleanup = pc_ldadd_cleanup;
3778 cm->defer_db_open = 0;
3779 ca->ca_private = on;
3780 return LDAP_SUCCESS;
3784 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3786 CfEntryInfo *pe = p->e_private;
3787 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3788 cache_manager *cm = on->on_bi.bi_private;
3791 /* FIXME: should not hardcode "olcDatabase" here */
3792 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3793 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3794 0, cm->db.bd_info->bi_type );
3795 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3798 bv.bv_val = ca->cr_msg;
3800 cm->defer_db_open = 0;
3802 /* We can only create this entry if the database is table-driven
3804 if ( cm->db.bd_info->bi_cf_ocs )
3805 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3812 pc_cf_gen( ConfigArgs *c )
3814 slap_overinst *on = (slap_overinst *)c->bi;
3815 cache_manager* cm = on->on_bi.bi_private;
3816 query_manager* qm = cm->qm;
3817 QueryTemplate* temp;
3818 AttributeName* attr_name;
3819 AttributeName* attrarray;
3820 const char* text=NULL;
3825 if ( c->op == SLAP_CONFIG_EMIT ) {
3829 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3830 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3831 cm->num_entries_limit, cm->cc_period );
3832 bv.bv_val = c->cr_msg;
3833 value_add_one( &c->rvalue_vals, &bv );
3836 for (i=0; i<cm->numattrsets; i++) {
3837 if ( !qm->attr_sets[i].count ) continue;
3839 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3841 /* count the attr length */
3842 for ( attr_name = qm->attr_sets[i].attrs;
3843 attr_name->an_name.bv_val; attr_name++ )
3845 bv.bv_len += attr_name->an_name.bv_len + 1;
3846 if ( attr_name->an_desc &&
3847 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3848 bv.bv_len += STRLENOF("undef:");
3852 bv.bv_val = ch_malloc( bv.bv_len+1 );
3853 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3854 for ( attr_name = qm->attr_sets[i].attrs;
3855 attr_name->an_name.bv_val; attr_name++ ) {
3857 if ( attr_name->an_desc &&
3858 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3859 ptr = lutil_strcopy( ptr, "undef:" );
3861 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3863 ber_bvarray_add( &c->rvalue_vals, &bv );
3865 if ( !c->rvalue_vals )
3869 for (temp=qm->templates; temp; temp=temp->qmnext) {
3870 /* HEADS-UP: always print all;
3871 * if optional == 0, ignore */
3872 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3873 " %d %ld %ld %ld %ld",
3874 temp->attr_set_index,
3879 bv.bv_len += temp->querystr.bv_len + 2;
3880 bv.bv_val = ch_malloc( bv.bv_len+1 );
3883 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3885 strcpy( ptr, c->cr_msg );
3886 ber_bvarray_add( &c->rvalue_vals, &bv );
3888 if ( !c->rvalue_vals )
3892 for (temp=qm->templates; temp; temp=temp->qmnext) {
3893 if ( !temp->bindttr ) continue;
3894 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3896 temp->attr_set_index,
3898 ldap_pvt_scope2str( temp->bindscope ));
3899 bv.bv_len += temp->bindbase.bv_len + temp->bindftemp.bv_len + 4;
3900 bv.bv_val = ch_malloc( bv.bv_len + 1 );
3903 ptr = lutil_strcopy( ptr, temp->bindftemp.bv_val );
3905 ptr = lutil_strcopy( ptr, c->cr_msg );
3907 ptr = lutil_strcopy( ptr, temp->bindbase.bv_val );
3910 ber_bvarray_add( &c->rvalue_vals, &bv );
3912 if ( !c->rvalue_vals )
3916 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3917 BER_BVSTR( &bv, "head" );
3919 BER_BVSTR( &bv, "tail" );
3921 value_add_one( &c->rvalue_vals, &bv );
3924 c->value_int = cm->max_queries;
3927 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3931 } else if ( c->op == LDAP_MOD_DELETE ) {
3934 case PC_ATTR: /* FIXME */
3939 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3940 /* If there were cached queries when we went offline,
3941 * restart the checker now.
3943 if ( cm->num_cached_queries ) {
3944 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3946 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3947 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3957 if ( cm->numattrsets > 0 ) {
3958 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive already provided" );
3959 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3963 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3964 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3966 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3969 if ( cm->numattrsets <= 0 ) {
3970 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3971 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3974 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3975 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3976 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3980 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3981 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3982 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3986 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3987 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3989 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3992 if ( cm->max_entries <= 0 ) {
3993 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3994 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
3998 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
3999 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
4001 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4004 if ( cm->num_entries_limit <= 0 ) {
4005 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
4006 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4009 if ( cm->num_entries_limit > cm->max_entries ) {
4010 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
4011 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4015 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4016 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
4018 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4022 cm->cc_period = (time_t)t;
4023 Debug( pcache_debug,
4024 "Total # of attribute sets to be cached = %d.\n",
4025 cm->numattrsets, 0, 0 );
4026 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
4027 sizeof( struct attr_set ) );
4030 if ( cm->numattrsets == 0 ) {
4031 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4032 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4035 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
4036 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
4038 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4042 if ( num < 0 || num >= cm->numattrsets ) {
4043 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
4044 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4045 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4048 qm->attr_sets[num].flags |= PC_CONFIGURED;
4049 if ( c->argc == 2 ) {
4051 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4052 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
4053 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4056 } else if ( c->argc == 3 ) {
4057 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4058 qm->attr_sets[num].count = 1;
4059 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4060 sizeof( AttributeName ) );
4061 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4064 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_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_OPERATIONAL_ATTRIBUTES );
4071 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
4074 /* else: fallthru */
4076 } else if ( c->argc == 4 ) {
4077 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
4078 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
4080 qm->attr_sets[num].count = 2;
4081 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
4082 sizeof( AttributeName ) );
4083 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4084 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4087 /* else: fallthru */
4090 if ( c->argc > 2 ) {
4091 int all_user = 0, all_op = 0;
4093 qm->attr_sets[num].count = c->argc - 2;
4094 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
4095 sizeof( AttributeName ) );
4096 attr_name = qm->attr_sets[num].attrs;
4097 for ( i = 2; i < c->argc; i++ ) {
4098 attr_name->an_desc = NULL;
4099 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
4100 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4101 "invalid attr #%d \"%s\" in attrlist",
4102 i - 2, c->argv[i] );
4103 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4104 ch_free( qm->attr_sets[num].attrs );
4105 qm->attr_sets[num].attrs = NULL;
4106 qm->attr_sets[num].count = 0;
4109 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4111 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
4112 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4114 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4116 if ( strncasecmp( c->argv[i], "undef:", STRLENOF("undef:") ) == 0 ) {
4118 ber_str2bv( c->argv[i] + STRLENOF("undef:"), 0, 0, &bv );
4119 attr_name->an_desc = slap_bv2tmp_ad( &bv, NULL );
4121 } else if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
4122 strcpy( c->cr_msg, text );
4123 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4124 ch_free( qm->attr_sets[num].attrs );
4125 qm->attr_sets[num].attrs = NULL;
4126 qm->attr_sets[num].count = 0;
4129 attr_name->an_name = attr_name->an_desc->ad_cname;
4131 attr_name->an_oc = NULL;
4132 attr_name->an_flags = 0;
4133 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
4134 qm->attr_sets[num].flags |= PC_GOT_OC;
4136 BER_BVZERO( &attr_name->an_name );
4139 /* warn if list contains both "*" and "+" */
4140 if ( i > 4 && all_user && all_op ) {
4141 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4142 "warning: attribute list contains \"*\" and \"+\"" );
4143 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4148 if ( cm->numattrsets == 0 ) {
4149 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4150 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4153 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4154 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
4156 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4160 if ( i < 0 || i >= cm->numattrsets ||
4161 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4162 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
4163 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4164 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4168 AttributeName *attrs;
4170 cnt = template_attrs( c->argv[1], &qm->attr_sets[i], &attrs, &text );
4172 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4174 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4177 temp = ch_calloc( 1, sizeof( QueryTemplate ));
4178 temp->qmnext = qm->templates;
4179 qm->templates = temp;
4180 temp->t_attrs.attrs = attrs;
4181 temp->t_attrs.count = cnt;
4183 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
4184 temp->query = temp->query_last = NULL;
4185 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4186 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4187 "unable to parse template ttl=\"%s\"",
4189 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4191 ch_free( temp->t_attrs.attrs );
4195 temp->ttl = (time_t)t;
4196 temp->negttl = (time_t)0;
4197 temp->limitttl = (time_t)0;
4198 temp->ttr = (time_t)0;
4199 switch ( c->argc ) {
4201 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
4202 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4203 "unable to parse template ttr=\"%s\"",
4205 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4208 temp->ttr = (time_t)t;
4212 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4213 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4214 "unable to parse template sizelimit ttl=\"%s\"",
4216 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4219 temp->limitttl = (time_t)t;
4223 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
4224 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4225 "unable to parse template negative ttl=\"%s\"",
4227 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4230 temp->negttl = (time_t)t;
4234 temp->no_of_queries = 0;
4236 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
4237 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
4238 Debug( pcache_debug, " query template: %s\n",
4239 temp->querystr.bv_val, 0, 0 );
4240 temp->attr_set_index = i;
4241 qm->attr_sets[i].flags |= PC_REFERENCED;
4242 temp->qtnext = qm->attr_sets[i].templates;
4243 qm->attr_sets[i].templates = temp;
4244 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
4245 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
4246 for ( i=0; attrarray[i].an_name.bv_val; i++ )
4247 Debug( pcache_debug, "\t%s\n",
4248 attrarray[i].an_name.bv_val, 0, 0 );
4252 if ( !qm->templates ) {
4253 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcacheTemplate\" directive not provided yet" );
4254 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4257 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4258 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse Bind index #=\"%s\"",
4260 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4264 if ( i < 0 || i >= cm->numattrsets ||
4265 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4266 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind index %d invalid (%s%d)",
4267 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4268 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4271 { struct berval bv, tempbv;
4272 AttributeDescription **descs;
4274 ber_str2bv( c->argv[1], 0, 0, &bv );
4275 ndescs = ftemp_attrs( &bv, &tempbv, &descs, &text );
4277 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4279 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4282 for ( temp = qm->templates; temp; temp=temp->qmnext ) {
4283 if ( temp->attr_set_index == i && bvmatch( &tempbv,
4287 ch_free( tempbv.bv_val );
4290 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind template %s %d invalid",
4292 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4295 ber_dupbv( &temp->bindftemp, &bv );
4296 temp->bindfattrs = descs;
4297 temp->bindnattrs = ndescs;
4299 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4300 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4301 "unable to parse bind ttr=\"%s\"",
4303 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4305 ch_free( temp->bindfattrs );
4306 temp->bindfattrs = NULL;
4307 ch_free( temp->bindftemp.bv_val );
4308 BER_BVZERO( &temp->bindftemp );
4311 num = ldap_pvt_str2scope( c->argv[4] );
4313 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4314 "unable to parse bind scope=\"%s\"",
4316 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4320 struct berval dn, ndn;
4321 ber_str2bv( c->argv[5], 0, 0, &dn );
4322 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
4324 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4325 "invalid bind baseDN=\"%s\"",
4327 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4330 if ( temp->bindbase.bv_val )
4331 ch_free( temp->bindbase.bv_val );
4332 temp->bindbase = ndn;
4335 /* convert the template into dummy filter */
4337 char *eq = temp->bindftemp.bv_val, *e2;
4340 while ((eq = strchr(eq, '=' ))) {
4345 bv.bv_len = temp->bindftemp.bv_len + i;
4346 bv.bv_val = ch_malloc( bv.bv_len + 1 );
4347 for ( e2 = bv.bv_val, eq = temp->bindftemp.bv_val;
4358 f = str2filter( bv.bv_val );
4360 ch_free( bv.bv_val );
4361 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4362 "unable to parse bindfilter=\"%s\"", bv.bv_val );
4363 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4364 ch_free( temp->bindbase.bv_val );
4365 BER_BVZERO( &temp->bindbase );
4368 if ( temp->bindfilter )
4369 filter_free( temp->bindfilter );
4370 if ( temp->bindfilterstr.bv_val )
4371 ch_free( temp->bindfilterstr.bv_val );
4372 temp->bindfilterstr = bv;
4373 temp->bindfilter = f;
4375 temp->bindttr = (time_t)t;
4376 temp->bindscope = num;
4377 cm->cache_binds = 1;
4381 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
4382 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
4384 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
4385 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4388 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
4389 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4394 if ( c->value_int <= 0 ) {
4395 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
4396 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4399 cm->max_queries = c->value_int;
4403 cm->cc_paused |= PCACHE_CC_OFFLINE;
4405 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
4408 if ( cm->db.be_private == NULL ) {
4409 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4410 "private database must be defined before setting database specific options" );
4411 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4415 if ( cm->db.bd_info->bi_cf_ocs ) {
4418 char *argv0 = c->argv[ 0 ];
4420 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4422 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
4424 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4425 "private database does not recognize specific option '%s'",
4427 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4431 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
4433 c->bi = c->be->bd_info;
4435 rc = config_add_vals( ct, c );
4439 c->table = c2.table;
4442 c->argv[ 0 ] = argv0;
4444 } else if ( cm->db.be_config != NULL ) {
4445 char *argv0 = c->argv[ 0 ];
4447 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4448 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
4449 c->argv[ 0 ] = argv0;
4452 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4453 "no means to set private database specific options" );
4454 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4459 rc = SLAP_CONF_UNKNOWN;
4475 slap_overinst *on = (slap_overinst *)be->bd_info;
4476 cache_manager* cm = on->on_bi.bi_private;
4478 /* Something for the cache database? */
4479 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
4480 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
4482 return SLAP_CONF_UNKNOWN;
4490 slap_overinst *on = (slap_overinst *)be->bd_info;
4494 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
4495 on->on_bi.bi_private = cm;
4497 qm = (query_manager*)ch_malloc(sizeof(query_manager));
4500 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
4501 cm->db.be_private = NULL;
4502 cm->db.bd_self = &cm->db;
4504 cm->numattrsets = 0;
4505 cm->num_entries_limit = 5;
4506 cm->num_cached_queries = 0;
4507 cm->max_entries = 0;
4508 cm->cur_entries = 0;
4509 cm->max_queries = 10000;
4510 cm->save_queries = 0;
4511 cm->check_cacheability = 0;
4512 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4513 cm->defer_db_open = 1;
4514 cm->cache_binds = 0;
4515 cm->cc_period = 1000;
4518 #ifdef PCACHE_MONITOR
4519 cm->monitor_cb = NULL;
4520 #endif /* PCACHE_MONITOR */
4522 qm->attr_sets = NULL;
4523 qm->templates = NULL;
4525 qm->lru_bottom = NULL;
4527 qm->qcfunc = query_containment;
4528 qm->crfunc = cache_replacement;
4529 qm->addfunc = add_query;
4530 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
4532 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
4534 #ifndef PCACHE_MONITOR
4536 #else /* PCACHE_MONITOR */
4537 return pcache_monitor_db_init( be );
4538 #endif /* PCACHE_MONITOR */
4542 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
4544 assert( op->o_tag == LDAP_REQ_SEARCH );
4546 if ( rs->sr_type == REP_SEARCH ) {
4549 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
4553 assert( a->a_nvals != NULL );
4555 valsp = op->o_callback->sc_private;
4556 assert( *valsp == NULL );
4558 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
4566 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
4568 assert( op->o_tag == LDAP_REQ_SEARCH );
4570 if ( rs->sr_type == REP_SEARCH ) {
4571 int *countp = (int *)op->o_callback->sc_private;
4584 cache_manager *cm = on->on_bi.bi_private;
4585 query_manager* qm = cm->qm;
4588 rc = backend_startup_one( &cm->db, cr );
4590 cm->defer_db_open = 0;
4593 /* There is no runqueue in TOOL mode */
4594 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
4595 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4596 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
4597 consistency_check, on,
4598 "pcache_consistency", cm->db.be_suffix[0].bv_val );
4599 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4601 /* Cached database must have the rootdn */
4602 if ( BER_BVISNULL( &cm->db.be_rootndn )
4603 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
4605 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
4606 "underlying database of type \"%s\"\n"
4607 " serving naming context \"%s\"\n"
4608 " has no \"rootdn\", required by \"pcache\".\n",
4609 on->on_info->oi_orig->bi_type,
4610 cm->db.be_suffix[0].bv_val, 0 );
4614 if ( cm->save_queries ) {
4615 void *thrctx = ldap_pvt_thread_pool_context();
4616 Connection conn = { 0 };
4617 OperationBuffer opbuf;
4619 slap_callback cb = { 0 };
4620 SlapReply rs = { REP_RESULT };
4621 BerVarray vals = NULL;
4622 Filter f = { 0 }, f2 = { 0 };
4623 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
4624 AttributeName attrs[ 2 ] = {{{ 0 }}};
4626 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4631 op->o_tag = LDAP_REQ_SEARCH;
4632 op->o_protocol = LDAP_VERSION3;
4633 cb.sc_response = pcache_cachedquery_open_cb;
4634 cb.sc_private = &vals;
4635 op->o_callback = &cb;
4636 op->o_time = slap_get_time();
4637 op->o_do_not_cache = 1;
4638 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4640 op->o_dn = cm->db.be_rootdn;
4641 op->o_ndn = cm->db.be_rootndn;
4642 op->o_req_dn = cm->db.be_suffix[ 0 ];
4643 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
4645 op->ors_scope = LDAP_SCOPE_BASE;
4646 op->ors_deref = LDAP_DEREF_NEVER;
4648 op->ors_tlimit = SLAP_NO_LIMIT;
4649 op->ors_limit = NULL;
4650 ber_str2bv( "(pcacheQueryURL=*)", 0, 0, &op->ors_filterstr );
4651 f.f_choice = LDAP_FILTER_PRESENT;
4652 f.f_desc = ad_cachedQueryURL;
4653 op->ors_filter = &f;
4654 attrs[ 0 ].an_desc = ad_cachedQueryURL;
4655 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
4656 op->ors_attrs = attrs;
4657 op->ors_attrsonly = 0;
4659 rc = op->o_bd->be_search( op, &rs );
4660 if ( rc == LDAP_SUCCESS && vals != NULL ) {
4663 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
4664 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
4665 cm->num_cached_queries++;
4669 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4672 /* count cached entries */
4673 f.f_choice = LDAP_FILTER_NOT;
4675 f2.f_choice = LDAP_FILTER_EQUALITY;
4677 f2.f_av_desc = slap_schema.si_ad_objectClass;
4678 BER_BVSTR( &f2.f_av_value, "glue" );
4679 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
4681 op->ors_slimit = SLAP_NO_LIMIT;
4682 op->ors_scope = LDAP_SCOPE_SUBTREE;
4683 op->ors_attrs = slap_anlist_no_attrs;
4685 rs_reinit( &rs, REP_RESULT );
4686 op->o_callback->sc_response = pcache_cachedquery_count_cb;
4687 op->o_callback->sc_private = &rs.sr_nentries;
4689 rc = op->o_bd->be_search( op, &rs );
4691 cm->cur_entries = rs.sr_nentries;
4705 slap_overinst *on = (slap_overinst *)be->bd_info;
4706 cache_manager *cm = on->on_bi.bi_private;
4707 query_manager* qm = cm->qm;
4708 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
4710 /* check attr sets */
4711 for ( i = 0; i < cm->numattrsets; i++) {
4712 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
4713 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
4714 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
4718 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
4722 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
4723 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
4728 if ( ncf || rf || nrf ) {
4729 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
4730 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
4731 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
4738 /* need to inherit something from the original database... */
4739 cm->db.be_def_limit = be->be_def_limit;
4740 cm->db.be_limits = be->be_limits;
4741 cm->db.be_acl = be->be_acl;
4742 cm->db.be_dfltaccess = be->be_dfltaccess;
4744 if ( SLAP_DBMONITORING( be ) ) {
4745 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
4748 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
4751 if ( !cm->defer_db_open ) {
4752 rc = pcache_db_open2( on, cr );
4755 #ifdef PCACHE_MONITOR
4756 if ( rc == LDAP_SUCCESS ) {
4757 rc = pcache_monitor_db_open( be );
4759 #endif /* PCACHE_MONITOR */
4765 pcache_free_qbase( void *v )
4771 tavl_free( qb->scopes[i], NULL );
4781 slap_overinst *on = (slap_overinst *)be->bd_info;
4782 cache_manager *cm = on->on_bi.bi_private;
4783 query_manager *qm = cm->qm;
4787 /* stop the thread ... */
4789 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4790 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4791 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4793 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4794 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4797 if ( cm->save_queries ) {
4799 BerVarray vals = NULL;
4802 Connection conn = { 0 };
4803 OperationBuffer opbuf;
4805 slap_callback cb = { 0 };
4807 SlapReply rs = { REP_RESULT };
4808 Modifications mod = {{ 0 }};
4810 thrctx = ldap_pvt_thread_pool_context();
4812 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4815 mod.sml_numvals = 0;
4816 if ( qm->templates != NULL ) {
4817 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4818 for ( qc = tm->query; qc; qc = qc->next ) {
4821 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4822 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4830 op->o_dn = cm->db.be_rootdn;
4831 op->o_ndn = cm->db.be_rootndn;
4833 op->o_tag = LDAP_REQ_MODIFY;
4834 op->o_protocol = LDAP_VERSION3;
4835 cb.sc_response = slap_null_cb;
4836 op->o_callback = &cb;
4837 op->o_time = slap_get_time();
4838 op->o_do_not_cache = 1;
4839 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4841 op->o_req_dn = op->o_bd->be_suffix[0];
4842 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4844 mod.sml_op = LDAP_MOD_REPLACE;
4846 mod.sml_desc = ad_cachedQueryURL;
4847 mod.sml_type = ad_cachedQueryURL->ad_cname;
4848 mod.sml_values = vals;
4849 mod.sml_nvalues = NULL;
4850 mod.sml_next = NULL;
4851 Debug( pcache_debug,
4852 "%sSETTING CACHED QUERY URLS\n",
4853 vals == NULL ? "RE" : "", 0, 0 );
4855 op->orm_modlist = &mod;
4857 op->o_bd->be_modify( op, &rs );
4859 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4862 /* cleanup stuff inherited from the original database... */
4863 cm->db.be_limits = NULL;
4864 cm->db.be_acl = NULL;
4867 if ( cm->db.bd_info->bi_db_close ) {
4868 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4870 while ( (tm = qm->templates) != NULL ) {
4871 CachedQuery *qc, *qn;
4872 qm->templates = tm->qmnext;
4873 for ( qc = tm->query; qc; qc = qn ) {
4877 avl_free( tm->qbase, pcache_free_qbase );
4878 free( tm->querystr.bv_val );
4879 free( tm->bindfattrs );
4880 free( tm->bindftemp.bv_val );
4881 free( tm->bindfilterstr.bv_val );
4882 free( tm->bindbase.bv_val );
4883 filter_free( tm->bindfilter );
4884 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4885 free( tm->t_attrs.attrs );
4889 for ( i = 0; i < cm->numattrsets; i++ ) {
4892 /* Account of LDAP_NO_ATTRS */
4893 if ( !qm->attr_sets[i].count ) continue;
4895 for ( j = 0; !BER_BVISNULL( &qm->attr_sets[i].attrs[j].an_name ); j++ ) {
4896 if ( qm->attr_sets[i].attrs[j].an_desc &&
4897 ( qm->attr_sets[i].attrs[j].an_desc->ad_flags &
4898 SLAP_DESC_TEMPORARY ) ) {
4899 slap_sl_mfuncs.bmf_free( qm->attr_sets[i].attrs[j].an_desc, NULL );
4902 free( qm->attr_sets[i].attrs );
4904 free( qm->attr_sets );
4905 qm->attr_sets = NULL;
4907 #ifdef PCACHE_MONITOR
4908 if ( rc == LDAP_SUCCESS ) {
4909 rc = pcache_monitor_db_close( be );
4911 #endif /* PCACHE_MONITOR */
4922 slap_overinst *on = (slap_overinst *)be->bd_info;
4923 cache_manager *cm = on->on_bi.bi_private;
4924 query_manager *qm = cm->qm;
4926 if ( cm->db.be_private != NULL ) {
4927 backend_stopdown_one( &cm->db );
4930 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4931 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4935 #ifdef PCACHE_MONITOR
4936 pcache_monitor_db_destroy( be );
4937 #endif /* PCACHE_MONITOR */
4942 #ifdef PCACHE_CONTROL_PRIVDB
4944 Control ::= SEQUENCE {
4945 controlType LDAPOID,
4946 criticality BOOLEAN DEFAULT FALSE,
4947 controlValue OCTET STRING OPTIONAL }
4949 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4951 * criticality must be TRUE; controlValue must be absent.
4959 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4960 rs->sr_text = "privateDB control specified multiple times";
4961 return LDAP_PROTOCOL_ERROR;
4964 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4965 rs->sr_text = "privateDB control value not absent";
4966 return LDAP_PROTOCOL_ERROR;
4969 if ( !ctrl->ldctl_iscritical ) {
4970 rs->sr_text = "privateDB control criticality required";
4971 return LDAP_PROTOCOL_ERROR;
4974 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4976 return LDAP_SUCCESS;
4979 static char *extops[] = {
4980 LDAP_EXOP_MODIFY_PASSWD,
4983 #endif /* PCACHE_CONTROL_PRIVDB */
4985 static struct berval pcache_exop_MODIFY_PASSWD = BER_BVC( LDAP_EXOP_MODIFY_PASSWD );
4986 #ifdef PCACHE_EXOP_QUERY_DELETE
4987 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4989 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4990 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4991 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
4994 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
4995 requestName [0] LDAPOID,
4996 requestValue [1] OCTET STRING OPTIONAL }
4998 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
5000 requestValue ::= SEQUENCE { CHOICE {
5002 entryDN [1] LDAPDN },
5003 queryID [2] OCTET STRING (SIZE(16))
5004 -- constrained to UUID }
5006 * Either baseDN or entryDN must be present, to allow database selection.
5008 * 1. if baseDN and queryID are present, then the query corresponding
5009 * to queryID is deleted;
5010 * 2. if baseDN is present and queryID is absent, then all queries
5012 * 3. if entryDN is present and queryID is absent, then all queries
5013 * corresponding to the queryID values present in entryDN are deleted;
5014 * 4. if entryDN and queryID are present, then all queries
5015 * corresponding to the queryID values present in entryDN are deleted,
5016 * but only if the value of queryID is contained in the entry;
5018 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
5019 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
5020 * or by removing the database files.
5022 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
5023 COMPONENTS OF LDAPResult,
5024 responseName [10] LDAPOID OPTIONAL,
5025 responseValue [11] OCTET STRING OPTIONAL }
5027 * responseName and responseValue must be absent.
5031 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
5032 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
5033 * - if ndn != NULL, it is set to the normalized DN in the request
5034 * corresponding to either the baseDN or the entryDN, according
5035 * to *tagp; memory is malloc'ed on the Operation's slab, and must
5036 * be freed by the caller.
5037 * - if uuid != NULL, it is set to point to the normalized UUID;
5038 * memory is malloc'ed on the Operation's slab, and must
5039 * be freed by the caller.
5042 pcache_parse_query_delete(
5046 struct berval *uuid,
5050 int rc = LDAP_SUCCESS;
5053 BerElementBuffer berbuf;
5054 BerElement *ber = (BerElement *)&berbuf;
5055 struct berval reqdata = BER_BVNULL;
5067 if ( in == NULL || in->bv_len == 0 ) {
5068 *text = "empty request data field in queryDelete exop";
5069 return LDAP_PROTOCOL_ERROR;
5072 ber_dupbv_x( &reqdata, in, ctx );
5074 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
5075 ber_init2( ber, &reqdata, 0 );
5077 tag = ber_scanf( ber, "{" /*}*/ );
5079 if ( tag == LBER_ERROR ) {
5080 Debug( LDAP_DEBUG_TRACE,
5081 "pcache_parse_query_delete: decoding error.\n",
5083 goto decoding_error;
5086 tag = ber_peek_tag( ber, &len );
5087 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
5088 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
5092 if ( ndn != NULL ) {
5095 tag = ber_scanf( ber, "m", &dn );
5096 if ( tag == LBER_ERROR ) {
5097 Debug( LDAP_DEBUG_TRACE,
5098 "pcache_parse_query_delete: DN parse failed.\n",
5100 goto decoding_error;
5103 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
5104 if ( rc != LDAP_SUCCESS ) {
5105 *text = "invalid DN in queryDelete exop request data";
5110 tag = ber_scanf( ber, "x" /* "m" */ );
5111 if ( tag == LBER_DEFAULT ) {
5112 goto decoding_error;
5116 tag = ber_peek_tag( ber, &len );
5119 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
5120 if ( uuid != NULL ) {
5122 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
5124 tag = ber_scanf( ber, "m", &bv );
5125 if ( tag == LBER_ERROR ) {
5126 Debug( LDAP_DEBUG_TRACE,
5127 "pcache_parse_query_delete: UUID parse failed.\n",
5129 goto decoding_error;
5132 if ( bv.bv_len != 16 ) {
5133 Debug( LDAP_DEBUG_TRACE,
5134 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5135 (unsigned long)bv.bv_len, 0, 0 );
5136 goto decoding_error;
5139 rc = lutil_uuidstr_from_normalized(
5140 bv.bv_val, bv.bv_len,
5141 uuidbuf, sizeof( uuidbuf ) );
5143 goto decoding_error;
5145 ber_str2bv( uuidbuf, rc, 1, uuid );
5149 tag = ber_skip_tag( ber, &len );
5150 if ( tag == LBER_DEFAULT ) {
5151 goto decoding_error;
5155 Debug( LDAP_DEBUG_TRACE,
5156 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5157 (unsigned long)len, 0, 0 );
5158 goto decoding_error;
5162 tag = ber_peek_tag( ber, &len );
5165 if ( tag != LBER_DEFAULT || len != 0 ) {
5167 Debug( LDAP_DEBUG_TRACE,
5168 "pcache_parse_query_delete: decoding error\n",
5170 rc = LDAP_PROTOCOL_ERROR;
5171 *text = "queryDelete data decoding error";
5174 if ( ndn && !BER_BVISNULL( ndn ) ) {
5175 slap_sl_free( ndn->bv_val, ctx );
5179 if ( uuid && !BER_BVISNULL( uuid ) ) {
5180 slap_sl_free( uuid->bv_val, ctx );
5185 if ( !BER_BVISNULL( &reqdata ) ) {
5186 ber_memfree_x( reqdata.bv_val, ctx );
5193 pcache_exop_query_delete(
5197 BackendDB *bd = op->o_bd;
5199 struct berval uuid = BER_BVNULL,
5201 char buf[ SLAP_TEXT_BUFLEN ];
5203 ber_tag_t tag = LBER_DEFAULT;
5205 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5209 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5210 &tag, &op->o_req_ndn, uuidp,
5211 &rs->sr_text, op->o_tmpmemctx );
5212 if ( rs->sr_err != LDAP_SUCCESS ) {
5216 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5217 assert( !BER_BVISNULL( &op->o_req_ndn ) );
5218 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
5220 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
5221 snprintf( &buf[ len ], sizeof( buf ) - len, " pcacheQueryId=\"%s\"", uuid.bv_val );
5224 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
5225 op->o_log_prefix, buf, 0 );
5227 op->o_req_dn = op->o_req_ndn;
5229 op->o_bd = select_backend( &op->o_req_ndn, 0 );
5230 if ( op->o_bd == NULL ) {
5231 send_ldap_error( op, rs, LDAP_NO_SUCH_OBJECT,
5232 "no global superior knowledge" );
5234 rs->sr_err = backend_check_restrictions( op, rs,
5235 (struct berval *)&pcache_exop_QUERY_DELETE );
5236 if ( rs->sr_err != LDAP_SUCCESS ) {
5240 if ( op->o_bd->be_extended == NULL ) {
5241 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
5242 "backend does not support extended operations" );
5246 op->o_bd->be_extended( op, rs );
5249 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
5250 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
5251 BER_BVZERO( &op->o_req_ndn );
5252 BER_BVZERO( &op->o_req_dn );
5255 if ( !BER_BVISNULL( &uuid ) ) {
5256 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5263 #endif /* PCACHE_EXOP_QUERY_DELETE */
5266 pcache_op_extended( Operation *op, SlapReply *rs )
5268 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5269 cache_manager *cm = on->on_bi.bi_private;
5271 #ifdef PCACHE_CONTROL_PRIVDB
5272 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
5273 return pcache_op_privdb( op, rs );
5275 #endif /* PCACHE_CONTROL_PRIVDB */
5277 #ifdef PCACHE_EXOP_QUERY_DELETE
5278 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
5279 struct berval uuid = BER_BVNULL;
5280 ber_tag_t tag = LBER_DEFAULT;
5282 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5283 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
5284 assert( rs->sr_err == LDAP_SUCCESS );
5286 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
5287 /* remove all queries related to the selected entry */
5288 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
5289 cm, &op->o_req_ndn, &uuid );
5291 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
5292 if ( !BER_BVISNULL( &uuid ) ) {
5293 /* remove the selected query */
5294 rs->sr_err = pcache_remove_query_from_cache( op,
5298 /* TODO: remove all queries */
5299 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
5300 rs->sr_text = "deletion of all queries not implemented";
5304 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5307 #endif /* PCACHE_EXOP_QUERY_DELETE */
5309 /* We only care if we're configured for Bind caching */
5310 if ( bvmatch( &op->ore_reqoid, &pcache_exop_MODIFY_PASSWD ) &&
5312 /* See if the local entry exists and has a password.
5313 * It's too much work to find the matching query, so
5314 * we just see if there's a hashed password to update.
5316 Operation op2 = *op;
5322 op2.o_dn = op->o_bd->be_rootdn;
5323 op2.o_ndn = op->o_bd->be_rootndn;
5324 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL,
5325 slap_schema.si_ad_userPassword, 0, &e );
5326 if ( rc == LDAP_SUCCESS && e ) {
5327 /* See if a recognized password is hashed here */
5328 Attribute *a = attr_find( e->e_attrs,
5329 slap_schema.si_ad_userPassword );
5330 if ( a && a->a_vals[0].bv_val[0] == '{' &&
5331 lutil_passwd_scheme( a->a_vals[0].bv_val )) {
5334 be_entry_release_r( &op2, e );
5338 rc = overlay_op_walk( op, rs, op_extended, on->on_info,
5340 if ( rc == LDAP_SUCCESS ) {
5341 req_pwdexop_s *qpw = &op->oq_pwdexop;
5343 /* We don't care if it succeeds or not */
5344 pc_setpw( &op2, &qpw->rs_new, cm );
5349 return SLAP_CB_CONTINUE;
5353 pcache_entry_release( Operation *op, Entry *e, int rw )
5355 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5356 cache_manager *cm = on->on_bi.bi_private;
5357 BackendDB *db = op->o_bd;
5361 rc = be_entry_release_rw( op, e, rw );
5366 #ifdef PCACHE_MONITOR
5369 pcache_monitor_update(
5375 cache_manager *cm = (cache_manager *) priv;
5376 query_manager *qm = cm->qm;
5379 BerVarray vals = NULL;
5381 attr_delete( &e->e_attrs, ad_cachedQueryURL );
5382 if ( ( SLAP_OPATTRS( rs->sr_attr_flags ) || ad_inlist( ad_cachedQueryURL, rs->sr_attrs ) )
5383 && qm->templates != NULL )
5387 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
5388 for ( qc = tm->query; qc; qc = qc->next ) {
5391 if ( query2url( op, qc, &bv, 1 ) == 0 ) {
5392 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
5398 if ( vals != NULL ) {
5399 attr_merge_normalize( e, ad_cachedQueryURL, vals, NULL );
5400 ber_bvarray_free_x( vals, op->o_tmpmemctx );
5406 char buf[ SLAP_TEXT_BUFLEN ];
5409 /* number of cached queries */
5410 a = attr_find( e->e_attrs, ad_numQueries );
5411 assert( a != NULL );
5414 bv.bv_len = snprintf( buf, sizeof( buf ), "%lu", cm->num_cached_queries );
5416 if ( a->a_nvals != a->a_vals ) {
5417 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5419 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5421 /* number of cached entries */
5422 a = attr_find( e->e_attrs, ad_numEntries );
5423 assert( a != NULL );
5426 bv.bv_len = snprintf( buf, sizeof( buf ), "%d", cm->cur_entries );
5428 if ( a->a_nvals != a->a_vals ) {
5429 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5431 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5434 return SLAP_CB_CONTINUE;
5438 pcache_monitor_free(
5442 struct berval values[ 2 ];
5443 Modification mod = { 0 };
5446 char textbuf[ SLAP_TEXT_BUFLEN ];
5450 /* NOTE: if slap_shutdown != 0, priv might have already been freed */
5453 /* Remove objectClass */
5454 mod.sm_op = LDAP_MOD_DELETE;
5455 mod.sm_desc = slap_schema.si_ad_objectClass;
5456 mod.sm_values = values;
5458 values[ 0 ] = oc_olmPCache->soc_cname;
5459 BER_BVZERO( &values[ 1 ] );
5461 rc = modify_delete_values( e, &mod, 1, &text,
5462 textbuf, sizeof( textbuf ) );
5463 /* don't care too much about return code... */
5466 mod.sm_values = NULL;
5467 mod.sm_desc = ad_cachedQueryURL;
5469 rc = modify_delete_values( e, &mod, 1, &text,
5470 textbuf, sizeof( textbuf ) );
5471 /* don't care too much about return code... */
5474 mod.sm_values = NULL;
5475 mod.sm_desc = ad_numQueries;
5477 rc = modify_delete_values( e, &mod, 1, &text,
5478 textbuf, sizeof( textbuf ) );
5479 /* don't care too much about return code... */
5482 mod.sm_values = NULL;
5483 mod.sm_desc = ad_numEntries;
5485 rc = modify_delete_values( e, &mod, 1, &text,
5486 textbuf, sizeof( textbuf ) );
5487 /* don't care too much about return code... */
5489 return SLAP_CB_CONTINUE;
5493 * call from within pcache_initialize()
5496 pcache_monitor_initialize( void )
5498 static int pcache_monitor_initialized = 0;
5500 if ( backend_info( "monitor" ) == NULL ) {
5504 if ( pcache_monitor_initialized++ ) {
5512 pcache_monitor_db_init( BackendDB *be )
5514 if ( pcache_monitor_initialize() == LDAP_SUCCESS ) {
5515 SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_MONITORING;
5522 pcache_monitor_db_open( BackendDB *be )
5524 slap_overinst *on = (slap_overinst *)be->bd_info;
5525 cache_manager *cm = on->on_bi.bi_private;
5526 Attribute *a, *next;
5527 monitor_callback_t *cb = NULL;
5530 monitor_extra_t *mbe;
5532 if ( !SLAP_DBMONITORING( be ) ) {
5536 mi = backend_info( "monitor" );
5537 if ( !mi || !mi->bi_extra ) {
5538 SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
5543 /* don't bother if monitor is not configured */
5544 if ( !mbe->is_configured() ) {
5545 static int warning = 0;
5547 if ( warning++ == 0 ) {
5548 Debug( LDAP_DEBUG_ANY, "pcache_monitor_db_open: "
5549 "monitoring disabled; "
5550 "configure monitor database to enable\n",
5557 /* alloc as many as required (plus 1 for objectClass) */
5558 a = attrs_alloc( 1 + 2 );
5564 a->a_desc = slap_schema.si_ad_objectClass;
5565 attr_valadd( a, &oc_olmPCache->soc_cname, NULL, 1 );
5569 struct berval bv = BER_BVC( "0" );
5571 next->a_desc = ad_numQueries;
5572 attr_valadd( next, &bv, NULL, 1 );
5573 next = next->a_next;
5575 next->a_desc = ad_numEntries;
5576 attr_valadd( next, &bv, NULL, 1 );
5577 next = next->a_next;
5580 cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
5581 cb->mc_update = pcache_monitor_update;
5582 cb->mc_free = pcache_monitor_free;
5583 cb->mc_private = (void *)cm;
5585 /* make sure the database is registered; then add monitor attributes */
5586 BER_BVZERO( &cm->monitor_ndn );
5587 rc = mbe->register_overlay( be, on, &cm->monitor_ndn );
5589 rc = mbe->register_entry_attrs( &cm->monitor_ndn, a, cb,
5606 /* store for cleanup */
5607 cm->monitor_cb = (void *)cb;
5609 /* we don't need to keep track of the attributes, because
5610 * bdb_monitor_free() takes care of everything */
5619 pcache_monitor_db_close( BackendDB *be )
5621 slap_overinst *on = (slap_overinst *)be->bd_info;
5622 cache_manager *cm = on->on_bi.bi_private;
5624 if ( cm->monitor_cb != NULL ) {
5625 BackendInfo *mi = backend_info( "monitor" );
5626 monitor_extra_t *mbe;
5628 if ( mi && &mi->bi_extra ) {
5630 mbe->unregister_entry_callback( &cm->monitor_ndn,
5631 (monitor_callback_t *)cm->monitor_cb,
5640 pcache_monitor_db_destroy( BackendDB *be )
5645 #endif /* PCACHE_MONITOR */
5647 static slap_overinst pcache;
5649 static char *obsolete_names[] = {
5654 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5656 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
5661 struct berval debugbv = BER_BVC("pcache");
5665 code = slap_loglevel_get( &debugbv, &pcache_debug );
5670 #ifdef PCACHE_CONTROL_PRIVDB
5671 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
5672 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
5673 parse_privdb_ctrl, &privDB_cid );
5674 if ( code != LDAP_SUCCESS ) {
5675 Debug( LDAP_DEBUG_ANY,
5676 "pcache_initialize: failed to register control %s (%d)\n",
5677 PCACHE_CONTROL_PRIVDB, code, 0 );
5680 #endif /* PCACHE_CONTROL_PRIVDB */
5682 #ifdef PCACHE_EXOP_QUERY_DELETE
5683 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
5684 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
5686 if ( code != LDAP_SUCCESS ) {
5687 Debug( LDAP_DEBUG_ANY,
5688 "pcache_initialize: unable to register queryDelete exop: %d.\n",
5692 #endif /* PCACHE_EXOP_QUERY_DELETE */
5694 argv[ 0 ] = "back-bdb/back-hdb monitor";
5699 for ( i = 0; s_oid[ i ].name; i++ ) {
5701 argv[ 1 ] = s_oid[ i ].name;
5702 argv[ 2 ] = s_oid[ i ].oid;
5704 if ( parse_oidm( &c, 0, NULL ) != 0 ) {
5705 Debug( LDAP_DEBUG_ANY, "pcache_initialize: "
5706 "unable to add objectIdentifier \"%s=%s\"\n",
5707 s_oid[ i ].name, s_oid[ i ].oid, 0 );
5712 for ( i = 0; s_ad[i].desc != NULL; i++ ) {
5713 code = register_at( s_ad[i].desc, s_ad[i].adp, 0 );
5715 Debug( LDAP_DEBUG_ANY,
5716 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
5719 (*s_ad[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
5722 for ( i = 0; s_oc[i].desc != NULL; i++ ) {
5723 code = register_oc( s_oc[i].desc, s_oc[i].ocp, 0 );
5725 Debug( LDAP_DEBUG_ANY,
5726 "pcache_initialize: register_oc #%d failed\n", i, 0, 0 );
5729 (*s_oc[i].ocp)->soc_flags |= SLAP_OC_HIDE;
5732 pcache.on_bi.bi_type = "pcache";
5733 pcache.on_bi.bi_obsolete_names = obsolete_names;
5734 pcache.on_bi.bi_db_init = pcache_db_init;
5735 pcache.on_bi.bi_db_config = pcache_db_config;
5736 pcache.on_bi.bi_db_open = pcache_db_open;
5737 pcache.on_bi.bi_db_close = pcache_db_close;
5738 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
5740 pcache.on_bi.bi_op_search = pcache_op_search;
5741 pcache.on_bi.bi_op_bind = pcache_op_bind;
5742 #ifdef PCACHE_CONTROL_PRIVDB
5743 pcache.on_bi.bi_op_compare = pcache_op_privdb;
5744 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
5745 pcache.on_bi.bi_op_modify = pcache_op_privdb;
5746 pcache.on_bi.bi_op_add = pcache_op_privdb;
5747 pcache.on_bi.bi_op_delete = pcache_op_privdb;
5748 #endif /* PCACHE_CONTROL_PRIVDB */
5749 pcache.on_bi.bi_extended = pcache_op_extended;
5751 pcache.on_bi.bi_entry_release_rw = pcache_entry_release;
5752 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
5754 pcache.on_bi.bi_cf_ocs = pcocs;
5756 code = config_register_schema( pccfg, pcocs );
5757 if ( code ) return code;
5759 return overlay_register( &pcache );
5762 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5763 int init_module(int argc, char *argv[]) {
5764 return pcache_initialize();
5768 #endif /* defined(SLAPD_OVER_PROXYCACHE) */