2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2018 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003-2009 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
36 #include "../back-monitor/back-monitor.h"
41 * Control that allows to access the private DB
42 * instead of the public one
44 #define PCACHE_CONTROL_PRIVDB "1.3.6.1.4.1.4203.666.11.9.5.1"
47 * Extended Operation that allows to remove a query from the cache
49 #define PCACHE_EXOP_QUERY_DELETE "1.3.6.1.4.1.4203.666.11.9.6.1"
54 #define PCACHE_MONITOR
56 /* query cache structs */
59 typedef struct Query_s {
60 Filter* filter; /* Search Filter */
61 struct berval base; /* Search Base */
62 int scope; /* Search scope */
65 struct query_template_s;
67 typedef struct Qbase_s {
68 TAvlnode *scopes[4]; /* threaded AVL trees of cached queries */
73 /* struct representing a cached query */
74 typedef struct cached_query_s {
79 struct berval q_uuid; /* query identifier */
81 struct query_template_s *qtemp; /* template of the query */
82 time_t expiry_time; /* time till the query is considered invalid */
83 time_t refresh_time; /* time till the query is refreshed */
84 time_t bindref_time; /* time till the bind is refreshed */
85 int bind_refcnt; /* number of bind operation referencing this query */
86 unsigned long answerable_cnt; /* how many times it was answerable */
87 int refcnt; /* references since last refresh */
88 ldap_pvt_thread_mutex_t answerable_cnt_mutex;
89 struct cached_query_s *next; /* next query in the template */
90 struct cached_query_s *prev; /* previous query in the template */
91 struct cached_query_s *lru_up; /* previous query in the LRU list */
92 struct cached_query_s *lru_down; /* next query in the LRU list */
93 ldap_pvt_thread_rdwr_t rwlock;
99 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>,x-refresh=<refresh>
101 * <base> ::= CachedQuery.qbase->base
102 * <scope> ::= CachedQuery.scope
103 * <filter> ::= filter2bv(CachedQuery.filter)
104 * <uuid> ::= CachedQuery.q_uuid
105 * <attrset> ::= CachedQuery.qtemp->attr_set_index
106 * <expiry> ::= CachedQuery.expiry_time
107 * <refresh> ::= CachedQuery.refresh_time
109 * quick hack: parse URI, call add_query() and then fix
110 * CachedQuery.expiry_time and CachedQuery.q_uuid
112 * NOTE: if the <attrset> changes, all stored URLs will be invalidated.
116 * Represents a set of projected attributes.
120 struct query_template_s *templates;
121 AttributeName* attrs; /* specifies the set */
123 #define PC_CONFIGURED (0x1)
124 #define PC_REFERENCED (0x2)
125 #define PC_GOT_OC (0x4)
126 int count; /* number of attributes */
129 /* struct representing a query template
130 * e.g. template string = &(cn=)(mail=)
132 typedef struct query_template_s {
133 struct query_template_s *qtnext;
134 struct query_template_s *qmnext;
137 CachedQuery* query; /* most recent query cached for the template */
138 CachedQuery* query_last; /* oldest query cached for the template */
139 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
140 struct berval querystr; /* Filter string corresponding to the QT */
141 struct berval bindbase; /* base DN for Bind request */
142 struct berval bindfilterstr; /* Filter string for Bind request */
143 struct berval bindftemp; /* bind filter template */
145 AttributeDescription **bindfattrs; /* attrs to substitute in ftemp */
147 int bindnattrs; /* number of bindfattrs */
149 int attr_set_index; /* determines the projected attributes */
150 int no_of_queries; /* Total number of queries in the template */
151 time_t ttl; /* TTL for the queries of this template */
152 time_t negttl; /* TTL for negative results */
153 time_t limitttl; /* TTL for sizelimit exceeding results */
154 time_t ttr; /* time to refresh */
155 time_t bindttr; /* TTR for cached binds */
156 struct attr_set t_attrs; /* filter attrs + attr_set */
164 } pc_caching_reason_t;
166 static const char *pc_caching_reason_str[] = {
175 struct query_manager_s;
177 /* prototypes for functions for 1) query containment
178 * 2) query addition, 3) cache replacement
180 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
181 Query*, QueryTemplate*);
182 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
183 Query*, QueryTemplate*, pc_caching_reason_t, int wlock);
184 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
186 /* LDAP query cache */
187 typedef struct query_manager_s {
188 struct attr_set* attr_sets; /* possible sets of projected attributes */
189 QueryTemplate* templates; /* cacheable templates */
191 CachedQuery* lru_top; /* top and bottom of LRU list */
192 CachedQuery* lru_bottom;
194 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
196 /* Query cache methods */
197 QCfunc *qcfunc; /* Query containment*/
198 CRfunc *crfunc; /* cache replacement */
199 AddQueryfunc *addfunc; /* add query */
202 /* LDAP query cache manager */
203 typedef struct cache_manager_s {
204 BackendDB db; /* underlying database */
205 unsigned long num_cached_queries; /* total number of cached queries */
206 unsigned long max_queries; /* upper bound on # of cached queries */
207 int save_queries; /* save cached queries across restarts */
208 int check_cacheability; /* check whether a query is cacheable */
209 int numattrsets; /* number of attribute sets */
210 int cur_entries; /* current number of entries cached */
211 int max_entries; /* max number of entries cached */
212 int num_entries_limit; /* max # of entries in a cacheable query */
214 char response_cb; /* install the response callback
215 * at the tail of the callback list */
216 #define PCACHE_RESPONSE_CB_HEAD 0
217 #define PCACHE_RESPONSE_CB_TAIL 1
218 char defer_db_open; /* defer open for online add */
219 char cache_binds; /* cache binds or just passthru */
221 time_t cc_period; /* interval between successive consistency checks (sec) */
222 #define PCACHE_CC_PAUSED 1
223 #define PCACHE_CC_OFFLINE 2
227 ldap_pvt_thread_mutex_t cache_mutex;
229 query_manager* qm; /* query cache managed by the cache manager */
231 #ifdef PCACHE_MONITOR
233 struct berval monitor_ndn;
234 #endif /* PCACHE_MONITOR */
237 #ifdef PCACHE_MONITOR
238 static int pcache_monitor_db_init( BackendDB *be );
239 static int pcache_monitor_db_open( BackendDB *be );
240 static int pcache_monitor_db_close( BackendDB *be );
241 static int pcache_monitor_db_destroy( BackendDB *be );
242 #endif /* PCACHE_MONITOR */
244 static int pcache_debug;
246 #ifdef PCACHE_CONTROL_PRIVDB
247 static int privDB_cid;
248 #endif /* PCACHE_CONTROL_PRIVDB */
250 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
252 #ifdef PCACHE_MONITOR
253 static AttributeDescription *ad_numQueries, *ad_numEntries;
254 static ObjectClass *oc_olmPCache;
255 #endif /* PCACHE_MONITOR */
261 { "PCacheOID", "1.3.6.1.4.1.4203.666.11.9.1" },
262 { "PCacheAttributes", "PCacheOID:1" },
263 { "PCacheObjectClasses", "PCacheOID:2" },
270 AttributeDescription **adp;
272 { "( PCacheAttributes:1 "
273 "NAME 'pcacheQueryID' "
274 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
275 "EQUALITY octetStringMatch "
276 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
277 "NO-USER-MODIFICATION "
278 "USAGE directoryOperation )",
280 { "( PCacheAttributes:2 "
281 "NAME 'pcacheQueryURL' "
282 "DESC 'URI describing a cached query' "
283 "EQUALITY caseExactMatch "
284 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
285 "NO-USER-MODIFICATION "
286 "USAGE directoryOperation )",
287 &ad_cachedQueryURL },
288 #ifdef PCACHE_MONITOR
289 { "( PCacheAttributes:3 "
290 "NAME 'pcacheNumQueries' "
291 "DESC 'Number of cached queries' "
292 "EQUALITY integerMatch "
293 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
294 "NO-USER-MODIFICATION "
295 "USAGE directoryOperation )",
297 { "( PCacheAttributes:4 "
298 "NAME 'pcacheNumEntries' "
299 "DESC 'Number of cached entries' "
300 "EQUALITY integerMatch "
301 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
302 "NO-USER-MODIFICATION "
303 "USAGE directoryOperation )",
305 #endif /* PCACHE_MONITOR */
314 #ifdef PCACHE_MONITOR
315 /* augments an existing object, so it must be AUXILIARY */
316 { "( PCacheObjectClasses:1 "
317 "NAME ( 'olmPCache' ) "
321 "$ pcacheNumQueries "
322 "$ pcacheNumEntries "
325 #endif /* PCACHE_MONITOR */
334 struct berval *fstr );
341 QueryTemplate *templ,
342 pc_caching_reason_t why,
348 struct berval *query_uuid );
351 * Turn a cached query into its URL representation
354 query2url( Operation *op, CachedQuery *q, struct berval *urlbv, int dolock )
356 struct berval bv_scope,
358 char attrset_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
359 expiry_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
360 refresh_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
361 answerable_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
363 ber_len_t attrset_len,
369 ldap_pvt_thread_rdwr_rlock( &q->rwlock );
372 ldap_pvt_scope2bv( q->scope, &bv_scope );
373 filter2bv_x( op, q->filter, &bv_filter );
374 attrset_len = sprintf( attrset_buf,
375 "%lu", (unsigned long)q->qtemp->attr_set_index );
376 expiry_len = sprintf( expiry_buf,
377 "%lu", (unsigned long)q->expiry_time );
378 answerable_len = snprintf( answerable_buf, sizeof( answerable_buf ),
379 "%lu", q->answerable_cnt );
380 if ( q->refresh_time )
381 refresh_len = sprintf( refresh_buf,
382 "%lu", (unsigned long)q->refresh_time );
386 urlbv->bv_len = STRLENOF( "ldap:///" )
387 + q->qbase->base.bv_len
392 + STRLENOF( "?x-uuid=" )
394 + STRLENOF( ",x-attrset=" )
396 + STRLENOF( ",x-expiry=" )
398 + STRLENOF( ",x-answerable=" )
401 urlbv->bv_len += STRLENOF( ",x-refresh=" )
404 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
405 ptr = lutil_strcopy( ptr, "ldap:///" );
406 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
407 ptr = lutil_strcopy( ptr, "??" );
408 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
409 ptr = lutil_strcopy( ptr, "?" );
410 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
411 ptr = lutil_strcopy( ptr, "?x-uuid=" );
412 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
413 ptr = lutil_strcopy( ptr, ",x-attrset=" );
414 ptr = lutil_strcopy( ptr, attrset_buf );
415 ptr = lutil_strcopy( ptr, ",x-expiry=" );
416 ptr = lutil_strcopy( ptr, expiry_buf );
417 ptr = lutil_strcopy( ptr, ",x-answerable=" );
418 ptr = lutil_strcopy( ptr, answerable_buf );
420 ptr = lutil_strcopy( ptr, ",x-refresh=" );
421 ptr = lutil_strcopy( ptr, refresh_buf );
424 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
427 ldap_pvt_thread_rdwr_runlock( &q->rwlock );
433 /* Find and record the empty filter clauses */
436 ftemp_attrs( struct berval *ftemp, struct berval *template,
437 AttributeDescription ***ret, const char **text )
443 AttributeDescription *ad;
444 AttributeDescription **descs = NULL;
447 temp2 = ch_malloc( ftemp->bv_len + 1 );
454 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' )
457 p2 = strchr( p1, '=' );
466 AC_MEMCPY( t1, p1, i );
470 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
474 i = slap_bv2ad( &bv, &ad, text );
480 if ( *p2 == '<' || *p2 == '>' ) p2++;
481 if ( p2[1] != ')' ) {
483 while ( *p2 != ')' ) p2++;
488 descs = (AttributeDescription **)ch_realloc(descs,
489 (attr_cnt + 2)*sizeof(AttributeDescription *));
491 descs[attr_cnt++] = ad;
496 descs[attr_cnt] = NULL;
498 template->bv_val = temp2;
499 template->bv_len = t1 - temp2;
504 template_attrs( char *template, struct attr_set *set, AttributeName **ret,
515 AttributeDescription *ad;
516 AttributeName *attrs;
522 attrs = ch_calloc( set->count + 1, sizeof(AttributeName) );
523 for ( i=0; i < set->count; i++ )
524 attrs[i] = set->attrs[i];
526 alluser = an_find( attrs, slap_bv_all_user_attrs );
527 allop = an_find( attrs, slap_bv_all_operational_attrs );
530 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' ) p1++;
531 p2 = strchr( p1, '=' );
534 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
538 i = slap_bv2ad( &bv, &ad, text );
545 if ( ad == slap_schema.si_ad_objectClass )
548 if ( is_at_operational(ad->ad_type)) {
552 } else if ( alluser ) {
555 if ( !ad_inlist( ad, attrs )) {
556 attrs = (AttributeName *)ch_realloc(attrs,
557 (attr_cnt + 2)*sizeof(AttributeName));
559 attrs[attr_cnt].an_desc = ad;
560 attrs[attr_cnt].an_name = ad->ad_cname;
561 attrs[attr_cnt].an_oc = NULL;
562 attrs[attr_cnt].an_flags = 0;
563 BER_BVZERO( &attrs[attr_cnt+1].an_name );
571 *text = "couldn't parse template";
575 if ( !got_oc && !( set->flags & PC_GOT_OC )) {
576 attrs = (AttributeName *)ch_realloc(attrs,
577 (attr_cnt + 2)*sizeof(AttributeName));
579 ad = slap_schema.si_ad_objectClass;
580 attrs[attr_cnt].an_desc = ad;
581 attrs[attr_cnt].an_name = ad->ad_cname;
582 attrs[attr_cnt].an_oc = NULL;
583 attrs[attr_cnt].an_flags = 0;
584 BER_BVZERO( &attrs[attr_cnt+1].an_name );
592 * Turn an URL representing a formerly cached query into a cached query,
593 * and try to cache it
604 LDAPURLDesc *lud = NULL;
606 tempstr = BER_BVNULL,
611 unsigned long answerable_cnt;
614 #define GOT_UUID 0x1U
615 #define GOT_ATTRSET 0x2U
616 #define GOT_EXPIRY 0x4U
617 #define GOT_ANSWERABLE 0x8U
618 #define GOT_REFRESH 0x10U
619 #define GOT_ALL (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
622 rc = ldap_url_parse( url, &lud );
623 if ( rc != LDAP_URL_SUCCESS ) {
627 /* non-allowed fields */
628 if ( lud->lud_host != NULL ) {
633 if ( lud->lud_attrs != NULL ) {
639 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
644 /* required fields */
645 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
650 switch ( lud->lud_scope ) {
651 case LDAP_SCOPE_BASE:
652 case LDAP_SCOPE_ONELEVEL:
653 case LDAP_SCOPE_SUBTREE:
654 case LDAP_SCOPE_SUBORDINATE:
662 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
667 if ( lud->lud_exts == NULL ) {
672 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
673 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
674 struct berval tmpUUID;
675 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
677 if ( got & GOT_UUID ) {
682 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
683 if ( !BER_BVISEMPTY( &tmpUUID ) ) {
684 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
685 if ( rc != LDAP_SUCCESS ) {
691 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
692 if ( got & GOT_ATTRSET ) {
697 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
703 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
706 if ( got & GOT_EXPIRY ) {
711 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
715 expiry_time = (time_t)l;
718 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
719 if ( got & GOT_ANSWERABLE ) {
724 rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
728 got |= GOT_ANSWERABLE;
730 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
733 if ( got & GOT_REFRESH ) {
738 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
742 refresh_time = (time_t)l;
751 if ( got != GOT_ALL ) {
756 if ( !(got & GOT_REFRESH ))
759 /* ignore expired queries */
760 if ( expiry_time <= slap_get_time()) {
763 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
765 (void)remove_query_data( &op2, &uuid );
770 ber_str2bv( lud->lud_dn, 0, 0, &base );
771 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
772 if ( rc != LDAP_SUCCESS ) {
775 query.scope = lud->lud_scope;
776 query.filter = str2filter( lud->lud_filter );
777 if ( query.filter == NULL ) {
782 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
784 if ( filter2template( op, query.filter, &tempstr ) ) {
785 ch_free( tempstr.bv_val );
790 /* check for query containment */
791 qt = qm->attr_sets[attrset].templates;
792 for ( ; qt; qt = qt->qtnext ) {
793 /* find if template i can potentially answer tempstr */
794 if ( bvmatch( &qt->querystr, &tempstr ) ) {
804 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
806 cq->expiry_time = expiry_time;
807 cq->refresh_time = refresh_time;
809 cq->answerable_cnt = answerable_cnt;
812 /* it's now into cq->filter */
822 if ( query.filter != NULL ) filter_free( query.filter );
823 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
824 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
825 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
826 if ( lud != NULL ) ldap_free_urldesc( lud );
831 /* Return 1 for an added entry, else 0 */
837 struct berval* query_uuid )
840 Modifications* modlist = NULL;
841 const char* text = NULL;
843 char textbuf[SLAP_TEXT_BUFLEN];
844 size_t textlen = sizeof(textbuf);
846 SlapReply sreply = {REP_RESULT};
848 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
855 /* add queryId attribute */
856 attr_merge_one( e, ad_queryId, query_uuid, NULL );
858 /* append the attribute list from the fetched entry */
859 e->e_attrs->a_next = attr;
861 op->o_tag = LDAP_REQ_ADD;
862 op->o_protocol = LDAP_VERSION3;
863 op->o_callback = &cb;
864 op->o_time = slap_get_time();
865 op->o_do_not_cache = 1;
868 op->o_req_dn = e->e_name;
869 op->o_req_ndn = e->e_nname;
870 rc = op->o_bd->be_add( op, &sreply );
872 if ( rc != LDAP_SUCCESS ) {
873 if ( rc == LDAP_ALREADY_EXISTS ) {
874 rs_reinit( &sreply, REP_RESULT );
875 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
876 modlist->sml_op = LDAP_MOD_ADD;
877 op->o_tag = LDAP_REQ_MODIFY;
878 op->orm_modlist = modlist;
879 op->o_managedsait = SLAP_CONTROL_CRITICAL;
880 op->o_bd->be_modify( op, &sreply );
881 slap_mods_free( modlist, 1 );
882 } else if ( rc == LDAP_REFERRAL ||
883 rc == LDAP_NO_SUCH_OBJECT ) {
884 syncrepl_add_glue( op, e );
893 if ( op->ora_e == e )
901 /* Length-ordered sort on normalized DNs */
902 static int pcache_dn_cmp( const void *v1, const void *v2 )
904 const Qbase *q1 = v1, *q2 = v2;
906 int rc = q1->base.bv_len - q2->base.bv_len;
908 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
912 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
915 dif = bv1->bv_len - bv2->bv_len;
917 if ( dif > 0 ) len -= dif;
918 len = memcmp( bv1->bv_val, bv2->bv_val, len );
924 /* compare the current value in each filter */
925 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
927 int rc, weight1, weight2;
929 switch( f1->f_choice ) {
930 case LDAP_FILTER_AND:
934 case LDAP_FILTER_PRESENT:
937 case LDAP_FILTER_EQUALITY:
945 switch( f2->f_choice ) {
946 case LDAP_FILTER_AND:
950 case LDAP_FILTER_PRESENT:
953 case LDAP_FILTER_EQUALITY:
961 rc = weight1 - weight2;
965 rc = pcache_filter_cmp( f1->f_and, f2->f_and );
970 rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
973 if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
975 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
976 if ( !BER_BVISNULL( &f2->f_sub_initial )) {
977 rc = lex_bvcmp( &f1->f_sub_initial,
978 &f2->f_sub_initial );
982 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
986 if ( f1->f_sub_any ) {
987 if ( f2->f_sub_any ) {
988 rc = lex_bvcmp( f1->f_sub_any,
993 } else if ( f2->f_sub_any ) {
997 if ( !BER_BVISNULL( &f1->f_sub_final )) {
998 if ( !BER_BVISNULL( &f2->f_sub_final )) {
999 rc = lex_bvcmp( &f1->f_sub_final,
1004 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
1008 rc = lex_bvcmp( &f1->f_mr_value,
1022 rc = pcache_filter_cmp( f1, f2 );
1032 /* compare filters in each query */
1033 static int pcache_query_cmp( const void *v1, const void *v2 )
1035 const CachedQuery *q1 = v1, *q2 =v2;
1036 return pcache_filter_cmp( q1->filter, q2->filter );
1039 /* add query on top of LRU list */
1041 add_query_on_top (query_manager* qm, CachedQuery* qc)
1043 CachedQuery* top = qm->lru_top;
1050 qm->lru_bottom = qc;
1054 Debug( pcache_debug, "Base of added query = %s\n",
1055 qc->qbase->base.bv_val, 0, 0 );
1058 /* remove_query from LRU list */
1061 remove_query (query_manager* qm, CachedQuery* qc)
1070 down = qc->lru_down;
1076 qm->lru_bottom = up;
1082 up->lru_down = down;
1084 qc->lru_up = qc->lru_down = NULL;
1087 /* find and remove string2 from string1
1088 * from start if position = 1,
1089 * from end if position = 3,
1090 * from anywhere if position = 2
1091 * string1 is overwritten if position = 2.
1095 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
1099 if ( !ber2->bv_val )
1101 if ( !ber1->bv_val )
1104 switch( position ) {
1106 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
1107 ber2->bv_val, ber2->bv_len )) {
1109 ber1->bv_val += ber2->bv_len;
1110 ber1->bv_len -= ber2->bv_len;
1115 ber1->bv_val[ber1->bv_len] = '\0';
1116 temp = strstr( ber1->bv_val, ber2->bv_val );
1118 strcpy( temp, temp+ber2->bv_len );
1119 ber1->bv_len -= ber2->bv_len;
1125 if ( ber1->bv_len >= ber2->bv_len &&
1126 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
1129 ber1->bv_len -= ber2->bv_len;
1137 static struct berval*
1138 merge_init_final(Operation *op, struct berval* init, struct berval* any,
1139 struct berval* final)
1141 struct berval* merged, *temp;
1142 int i, any_count, count;
1144 for (any_count=0; any && any[any_count].bv_val; any_count++)
1154 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
1159 ber_dupbv_x( temp, init, op->o_tmpmemctx );
1163 for (i=0; i<any_count; i++) {
1164 ber_dupbv_x( temp, any, op->o_tmpmemctx );
1169 ber_dupbv_x( temp, final, op->o_tmpmemctx );
1176 /* Each element in stored must be found in incoming. Incoming is overwritten.
1179 strings_containment(struct berval* stored, struct berval* incoming)
1181 struct berval* element;
1185 for ( element=stored; element->bv_val != NULL; element++ ) {
1186 for (j = k; incoming[j].bv_val != NULL; j++) {
1187 if (find_and_remove(&(incoming[j]), element, 2)) {
1204 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
1208 struct berval init_incoming;
1209 struct berval final_incoming;
1210 struct berval *remaining_incoming = NULL;
1212 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
1213 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
1216 init_incoming = incoming->f_sub_initial;
1217 final_incoming = incoming->f_sub_final;
1219 if (find_and_remove(&init_incoming,
1220 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
1221 &(stored->f_sub_final), 3))
1223 if (stored->f_sub_any == NULL) {
1227 remaining_incoming = merge_init_final(op, &init_incoming,
1228 incoming->f_sub_any, &final_incoming);
1229 rc = strings_containment(stored->f_sub_any, remaining_incoming);
1230 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
1237 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
1239 struct berval incoming_val[2];
1242 incoming_val[1] = incoming->f_av_value;
1244 if (find_and_remove(incoming_val+1,
1245 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
1246 &(stored->f_sub_final), 3)) {
1247 if (stored->f_sub_any == NULL){
1251 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
1252 BER_BVZERO( incoming_val+1 );
1253 rc = strings_containment(stored->f_sub_any, incoming_val);
1254 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1261 filter_first( Filter *f )
1263 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1268 typedef struct fstack {
1269 struct fstack *fs_next;
1274 static CachedQuery *
1275 find_filter( Operation *op, TAvlnode *root, Filter *inputf, Filter *first )
1279 MatchingRule* mrule = NULL;
1280 int res=0, eqpass= 0;
1283 CachedQuery cq, *qc;
1284 fstack *stack = NULL, *fsp;
1289 /* substring matches sort to the end, and we just have to
1290 * walk the entire list.
1292 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1293 ptr = tavl_end( root, 1 );
1294 dir = TAVL_DIR_LEFT;
1296 ptr = tavl_find3( root, &cq, pcache_query_cmp, &ret );
1297 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1306 /* an incoming substr query can only be satisfied by a cached
1309 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1310 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1313 /* an incoming eq query can be satisfied by a cached eq or substr
1316 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1317 if ( eqpass == 0 ) {
1318 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1319 nextpass: eqpass = 1;
1320 ptr = tavl_end( root, 1 );
1321 dir = TAVL_DIR_LEFT;
1325 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1331 switch (fs->f_choice) {
1332 case LDAP_FILTER_EQUALITY:
1333 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1334 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1338 case LDAP_FILTER_GE:
1339 case LDAP_FILTER_LE:
1340 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1347 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1348 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1349 &(fi->f_ava->aa_value),
1350 &(fs->f_ava->aa_value), &text);
1351 if (rc != LDAP_SUCCESS) {
1354 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1357 switch (fs->f_choice) {
1358 case LDAP_FILTER_OR:
1359 case LDAP_FILTER_AND:
1361 /* save our stack position */
1362 fsp = op->o_tmpalloc(sizeof(fstack), op->o_tmpmemctx);
1363 fsp->fs_next = stack;
1364 fsp->fs_fs = fs->f_next;
1365 fsp->fs_fi = fi->f_next;
1372 case LDAP_FILTER_SUBSTRINGS:
1373 /* check if the equality query can be
1374 * answered with cached substring query */
1375 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1376 && substr_containment_equality( op,
1379 /* check if the substring query can be
1380 * answered with cached substring query */
1381 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1382 ) && substr_containment_substr( op,
1388 case LDAP_FILTER_PRESENT:
1393 case LDAP_FILTER_EQUALITY:
1399 case LDAP_FILTER_GE:
1400 if (mrule && ret >= 0)
1405 case LDAP_FILTER_LE:
1406 if (mrule && ret <= 0)
1411 case LDAP_FILTER_NOT:
1417 if (!fs && !fi && stack) {
1420 stack = fsp->fs_next;
1423 op->o_tmpfree(fsp, op->o_tmpmemctx);
1425 } while((res) && (fi != NULL) && (fs != NULL));
1429 ptr = tavl_next( ptr, dir );
1434 /* check whether query is contained in any of
1435 * the cached queries in template
1437 static CachedQuery *
1438 query_containment(Operation *op, query_manager *qm,
1440 QueryTemplate *templa)
1443 int depth = 0, tscope;
1444 Qbase qbase, *qbptr = NULL;
1447 if (query->filter != NULL) {
1450 Debug( pcache_debug, "Lock QC index = %p\n",
1451 (void *) templa, 0, 0 );
1452 qbase.base = query->base;
1454 first = filter_first( query->filter );
1456 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1459 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1461 tscope = query->scope;
1462 /* Find a matching scope:
1463 * match at depth 0 OK
1466 * subord at depth > 0 OK
1467 * subtree at any depth OK
1469 * subtree or subord at any depth OK
1471 * subtree or subord at any depth OK
1473 * subord at depth > 0 OK
1474 * subtree at any depth OK
1476 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1477 switch ( query->scope ) {
1478 case LDAP_SCOPE_BASE:
1479 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1480 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1481 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1483 case LDAP_SCOPE_ONE:
1484 if ( tscope == LDAP_SCOPE_BASE )
1485 tscope = LDAP_SCOPE_ONE;
1486 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1487 if ( !depth ) break;
1488 if ( tscope < LDAP_SCOPE_SUBTREE )
1489 tscope = LDAP_SCOPE_SUBTREE;
1491 case LDAP_SCOPE_SUBTREE:
1492 if ( tscope < LDAP_SCOPE_SUBTREE )
1493 tscope = LDAP_SCOPE_SUBTREE;
1494 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1496 case LDAP_SCOPE_CHILDREN:
1497 if ( tscope < LDAP_SCOPE_SUBTREE )
1498 tscope = LDAP_SCOPE_SUBTREE;
1501 if ( !qbptr->scopes[tscope] ) continue;
1504 qc = find_filter( op, qbptr->scopes[tscope],
1505 query->filter, first );
1507 if ( qc->q_sizelimit ) {
1508 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1511 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1512 if (qm->lru_top != qc) {
1513 remove_query(qm, qc);
1514 add_query_on_top(qm, qc);
1516 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1521 if ( be_issuffix( op->o_bd, &qbase.base ))
1524 dnParent( &qbase.base, &pdn );
1529 Debug( pcache_debug,
1530 "Not answerable: Unlock QC index=%p\n",
1531 (void *) templa, 0, 0 );
1532 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1538 free_query (CachedQuery* qc)
1540 free(qc->q_uuid.bv_val);
1541 filter_free(qc->filter);
1542 ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1543 ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1544 memset(qc, 0, sizeof(*qc));
1549 /* Add query to query cache, the returned Query is locked for writing */
1550 static CachedQuery *
1555 QueryTemplate *templ,
1556 pc_caching_reason_t why,
1559 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1563 time_t ttl = 0, ttr = 0;
1566 new_cached_query->qtemp = templ;
1567 BER_BVZERO( &new_cached_query->q_uuid );
1568 new_cached_query->q_sizelimit = 0;
1570 now = slap_get_time();
1575 ttr = now + templ->ttr;
1579 ttl = templ->negttl;
1583 ttl = templ->limitttl;
1590 new_cached_query->expiry_time = now + ttl;
1591 new_cached_query->refresh_time = ttr;
1592 new_cached_query->bindref_time = 0;
1594 new_cached_query->bind_refcnt = 0;
1595 new_cached_query->answerable_cnt = 0;
1596 new_cached_query->refcnt = 1;
1597 ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1599 new_cached_query->lru_up = NULL;
1600 new_cached_query->lru_down = NULL;
1601 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1602 (long) new_cached_query->expiry_time,
1603 pc_caching_reason_str[ why ], 0 );
1605 new_cached_query->scope = query->scope;
1606 new_cached_query->filter = query->filter;
1607 new_cached_query->first = first = filter_first( query->filter );
1609 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1611 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1613 qb.base = query->base;
1615 /* Adding a query */
1616 Debug( pcache_debug, "Lock AQ index = %p\n",
1617 (void *) templ, 0, 0 );
1618 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1619 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1621 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1622 qbase->base.bv_len = qb.base.bv_len;
1623 qbase->base.bv_val = (char *)(qbase+1);
1624 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1625 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1626 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1628 new_cached_query->next = templ->query;
1629 new_cached_query->prev = NULL;
1630 new_cached_query->qbase = qbase;
1631 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1632 pcache_query_cmp, avl_dup_error );
1635 if (templ->query == NULL)
1636 templ->query_last = new_cached_query;
1638 templ->query->prev = new_cached_query;
1639 templ->query = new_cached_query;
1640 templ->no_of_queries++;
1642 ldap_pvt_thread_mutex_destroy(&new_cached_query->answerable_cnt_mutex);
1644 ldap_pvt_thread_rdwr_wunlock(&new_cached_query->rwlock);
1645 ldap_pvt_thread_rdwr_destroy( &new_cached_query->rwlock );
1646 ch_free( new_cached_query );
1647 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1648 query->filter, first );
1649 filter_free( query->filter );
1650 query->filter = NULL;
1652 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1653 (void *) templ, templ->no_of_queries, 0 );
1655 /* Adding on top of LRU list */
1657 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1658 add_query_on_top(qm, new_cached_query);
1659 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1661 Debug( pcache_debug, "Unlock AQ index = %p \n",
1662 (void *) templ, 0, 0 );
1663 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1665 return rc == 0 ? new_cached_query : NULL;
1669 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1671 if (!qc->prev && !qc->next) {
1672 template->query_last = template->query = NULL;
1673 } else if (qc->prev == NULL) {
1674 qc->next->prev = NULL;
1675 template->query = qc->next;
1676 } else if (qc->next == NULL) {
1677 qc->prev->next = NULL;
1678 template->query_last = qc->prev;
1680 qc->next->prev = qc->prev;
1681 qc->prev->next = qc->next;
1683 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1684 qc->qbase->queries--;
1685 if ( qc->qbase->queries == 0 ) {
1686 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1687 ch_free( qc->qbase );
1691 template->no_of_queries--;
1694 /* remove bottom query of LRU list from the query cache */
1696 * NOTE: slight change in functionality.
1698 * - if result->bv_val is NULL, the query at the bottom of the LRU
1700 * - otherwise, the query whose UUID is *result is removed
1701 * - if not found, result->bv_val is zeroed
1704 cache_replacement(query_manager* qm, struct berval *result)
1706 CachedQuery* bottom;
1707 QueryTemplate *temp;
1709 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1710 if ( BER_BVISNULL( result ) ) {
1711 bottom = qm->lru_bottom;
1714 Debug ( pcache_debug,
1715 "Cache replacement invoked without "
1716 "any query in LRU list\n", 0, 0, 0 );
1717 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1722 for ( bottom = qm->lru_bottom;
1724 bottom = bottom->lru_up )
1726 if ( bvmatch( result, &bottom->q_uuid ) ) {
1732 Debug ( pcache_debug,
1733 "Could not find query with uuid=\"%s\""
1734 "in LRU list\n", result->bv_val, 0, 0 );
1735 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1736 BER_BVZERO( result );
1741 temp = bottom->qtemp;
1742 remove_query(qm, bottom);
1743 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1745 *result = bottom->q_uuid;
1746 BER_BVZERO( &bottom->q_uuid );
1748 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1749 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1750 remove_from_template(bottom, temp);
1751 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1752 (void *) temp, temp->no_of_queries, 0 );
1753 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1754 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1759 struct query_info *next;
1771 struct query_info *qi;
1774 if ( rs->sr_type != REP_SEARCH ) return 0;
1776 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1777 if ( attr == NULL ) return 0;
1779 count = attr->a_numvals;
1780 assert( count > 0 );
1781 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1782 qi->next = op->o_callback->sc_private;
1783 op->o_callback->sc_private = qi;
1784 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1785 qi->del = ( count == 1 );
1793 struct berval *query_uuid )
1795 struct query_info *qi, *qnext;
1796 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
1797 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1798 Filter filter = {LDAP_FILTER_EQUALITY};
1799 SlapReply sreply = {REP_RESULT};
1800 slap_callback cb = { NULL, remove_func, NULL, NULL };
1803 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1804 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1805 filter.f_ava = &ava;
1806 filter.f_av_desc = ad_queryId;
1807 filter.f_av_value = *query_uuid;
1809 op->o_tag = LDAP_REQ_SEARCH;
1810 op->o_protocol = LDAP_VERSION3;
1811 op->o_callback = &cb;
1812 op->o_time = slap_get_time();
1813 op->o_do_not_cache = 1;
1815 op->o_req_dn = op->o_bd->be_suffix[0];
1816 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1817 op->ors_scope = LDAP_SCOPE_SUBTREE;
1818 op->ors_deref = LDAP_DEREF_NEVER;
1819 op->ors_slimit = SLAP_NO_LIMIT;
1820 op->ors_tlimit = SLAP_NO_LIMIT;
1821 op->ors_limit = NULL;
1822 op->ors_filter = &filter;
1823 op->ors_filterstr.bv_val = filter_str;
1824 op->ors_filterstr.bv_len = strlen(filter_str);
1825 op->ors_attrs = NULL;
1826 op->ors_attrsonly = 0;
1828 op->o_bd->be_search( op, &sreply );
1830 for ( qi=cb.sc_private; qi; qi=qnext ) {
1833 op->o_req_dn = qi->xdn;
1834 op->o_req_ndn = qi->xdn;
1835 rs_reinit( &sreply, REP_RESULT );
1838 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1839 query_uuid->bv_val, 0, 0 );
1841 op->o_tag = LDAP_REQ_DELETE;
1843 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1849 struct berval vals[2];
1851 vals[0] = *query_uuid;
1852 vals[1].bv_val = NULL;
1854 mod.sml_op = LDAP_MOD_DELETE;
1856 mod.sml_desc = ad_queryId;
1857 mod.sml_type = ad_queryId->ad_cname;
1858 mod.sml_values = vals;
1859 mod.sml_nvalues = NULL;
1860 mod.sml_numvals = 1;
1861 mod.sml_next = NULL;
1862 Debug( pcache_debug,
1863 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1864 query_uuid->bv_val, 0, 0 );
1866 op->orm_modlist = &mod;
1868 op->o_bd->be_modify( op, &sreply );
1870 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1871 op->o_tmpfree( qi, op->o_tmpmemctx );
1878 AttributeName* attrs,
1887 struct berval *fstr )
1889 AttributeDescription *ad;
1892 switch ( f->f_choice ) {
1893 case LDAP_FILTER_EQUALITY:
1895 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1896 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1897 assert( ret == len );
1898 fstr->bv_len += len;
1901 case LDAP_FILTER_GE:
1903 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1904 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1905 assert( ret == len );
1906 fstr->bv_len += len;
1909 case LDAP_FILTER_LE:
1911 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1912 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1913 assert( ret == len );
1914 fstr->bv_len += len;
1917 case LDAP_FILTER_APPROX:
1919 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1920 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1921 assert( ret == len );
1922 fstr->bv_len += len;
1925 case LDAP_FILTER_SUBSTRINGS:
1927 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1928 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1929 assert( ret == len );
1930 fstr->bv_len += len;
1933 case LDAP_FILTER_PRESENT:
1935 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1936 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1937 assert( ret == len );
1938 fstr->bv_len += len;
1941 case LDAP_FILTER_AND:
1942 case LDAP_FILTER_OR:
1943 case LDAP_FILTER_NOT: {
1945 fstr->bv_val[fstr->bv_len++] = '(';
1946 switch ( f->f_choice ) {
1947 case LDAP_FILTER_AND:
1948 fstr->bv_val[fstr->bv_len] = '&';
1950 case LDAP_FILTER_OR:
1951 fstr->bv_val[fstr->bv_len] = '|';
1953 case LDAP_FILTER_NOT:
1954 fstr->bv_val[fstr->bv_len] = '!';
1959 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1960 rc = filter2template( op, f, fstr );
1963 fstr->bv_val[fstr->bv_len++] = ')';
1964 fstr->bv_val[fstr->bv_len] = '\0';
1970 /* a filter should at least have room for "()",
1971 * an "=" and for a 1-char attr */
1972 strcpy( fstr->bv_val, "(?=)" );
1973 fstr->bv_len += STRLENOF("(?=)");
1980 #define BI_HASHED 0x01
1981 #define BI_DIDCB 0x02
1982 #define BI_LOOKUP 0x04
1986 typedef struct bindinfo {
1987 cache_manager *bi_cm;
1989 QueryTemplate *bi_templ;
1990 struct search_info *bi_si;
1992 slap_callback bi_cb;
1995 struct search_info {
1998 QueryTemplate *qtemp;
1999 AttributeName* save_attrs; /* original attributes, saved for response */
2000 int swap_saved_attrs;
2005 int slimit_exceeded;
2006 pc_caching_reason_t caching_reason;
2012 remove_query_and_data(
2015 struct berval *uuid )
2017 query_manager* qm = cm->qm;
2019 qm->crfunc( qm, uuid );
2020 if ( !BER_BVISNULL( uuid ) ) {
2023 Debug( pcache_debug,
2024 "Removing query UUID %s\n",
2025 uuid->bv_val, 0, 0 );
2026 return_val = remove_query_data( op, uuid );
2027 Debug( pcache_debug,
2028 "QUERY REMOVED, SIZE=%d\n",
2030 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
2031 cm->cur_entries -= return_val;
2032 cm->num_cached_queries--;
2033 Debug( pcache_debug,
2034 "STORED QUERIES = %lu\n",
2035 cm->num_cached_queries, 0, 0 );
2036 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
2037 Debug( pcache_debug,
2038 "QUERY REMOVED, CACHE ="
2040 cm->cur_entries, 0, 0 );
2045 * Callback used to fetch queryId values based on entryUUID;
2046 * used by pcache_remove_entries_from_cache()
2049 fetch_queryId_cb( Operation *op, SlapReply *rs )
2053 /* only care about searchEntry responses */
2054 if ( rs->sr_type != REP_SEARCH ) {
2058 /* allow only one response per entryUUID */
2059 if ( op->o_callback->sc_private != NULL ) {
2065 /* copy all queryId values into callback's private data */
2066 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2068 BerVarray vals = NULL;
2070 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
2071 op->o_callback->sc_private = (void *)vals;
2075 /* clear entry if required */
2076 rs_flush_entry( op, rs, (slap_overinst *) op->o_bd->bd_info );
2082 * Call that allows to remove a set of entries from the cache,
2083 * by forcing the removal of all the related queries.
2086 pcache_remove_entries_from_cache(
2089 BerVarray entryUUIDs )
2091 Connection conn = { 0 };
2092 OperationBuffer opbuf;
2094 slap_callback sc = { 0 };
2096 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
2097 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2098 AttributeName attrs[ 2 ] = {{{ 0 }}};
2102 void *thrctx = ldap_pvt_thread_pool_context();
2104 connection_fake_init( &conn, &opbuf, thrctx );
2112 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2113 op->ors_scope = LDAP_SCOPE_SUBTREE;
2114 op->ors_deref = LDAP_DEREF_NEVER;
2115 f.f_choice = LDAP_FILTER_EQUALITY;
2117 ava.aa_desc = slap_schema.si_ad_entryUUID;
2118 op->ors_filter = &f;
2120 op->ors_tlimit = SLAP_NO_LIMIT;
2121 op->ors_limit = NULL;
2122 attrs[ 0 ].an_desc = ad_queryId;
2123 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2124 op->ors_attrs = attrs;
2125 op->ors_attrsonly = 0;
2127 op->o_req_dn = cm->db.be_suffix[ 0 ];
2128 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2130 op->o_tag = LDAP_REQ_SEARCH;
2131 op->o_protocol = LDAP_VERSION3;
2132 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2134 op->o_dn = op->o_bd->be_rootdn;
2135 op->o_ndn = op->o_bd->be_rootndn;
2136 sc.sc_response = fetch_queryId_cb;
2137 op->o_callback = ≻
2139 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
2140 BerVarray vals = NULL;
2141 SlapReply rs = { REP_RESULT };
2143 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
2144 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
2145 op->ors_filterstr.bv_val = filtbuf;
2146 ava.aa_value = entryUUIDs[ s ];
2148 rc = op->o_bd->be_search( op, &rs );
2149 if ( rc != LDAP_SUCCESS ) {
2153 vals = (BerVarray)op->o_callback->sc_private;
2154 if ( vals != NULL ) {
2157 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2158 struct berval val = vals[ i ];
2160 remove_query_and_data( op, cm, &val );
2162 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2163 ch_free( val.bv_val );
2167 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2168 op->o_callback->sc_private = NULL;
2176 * Call that allows to remove a query from the cache.
2179 pcache_remove_query_from_cache(
2182 struct berval *queryid )
2184 Operation op2 = *op;
2188 /* remove the selected query */
2189 remove_query_and_data( &op2, cm, queryid );
2191 return LDAP_SUCCESS;
2195 * Call that allows to remove a set of queries related to an entry
2196 * from the cache; if queryid is not null, the entry must belong to
2197 * the query indicated by queryid.
2200 pcache_remove_entry_queries_from_cache(
2204 struct berval *queryid )
2206 Connection conn = { 0 };
2207 OperationBuffer opbuf;
2209 slap_callback sc = { 0 };
2210 SlapReply rs = { REP_RESULT };
2212 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
2213 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2214 AttributeName attrs[ 2 ] = {{{ 0 }}};
2217 BerVarray vals = NULL;
2220 void *thrctx = ldap_pvt_thread_pool_context();
2222 connection_fake_init( &conn, &opbuf, thrctx );
2230 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2231 op->ors_scope = LDAP_SCOPE_BASE;
2232 op->ors_deref = LDAP_DEREF_NEVER;
2233 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
2234 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
2235 f.f_choice = LDAP_FILTER_PRESENT;
2236 f.f_desc = slap_schema.si_ad_objectClass;
2239 op->ors_filterstr.bv_len = snprintf( filter_str,
2240 sizeof( filter_str ), "(%s=%s)",
2241 ad_queryId->ad_cname.bv_val, queryid->bv_val );
2242 f.f_choice = LDAP_FILTER_EQUALITY;
2244 f.f_av_desc = ad_queryId;
2245 f.f_av_value = *queryid;
2247 op->ors_filter = &f;
2249 op->ors_tlimit = SLAP_NO_LIMIT;
2250 op->ors_limit = NULL;
2251 attrs[ 0 ].an_desc = ad_queryId;
2252 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2253 op->ors_attrs = attrs;
2254 op->ors_attrsonly = 0;
2256 op->o_req_dn = *ndn;
2257 op->o_req_ndn = *ndn;
2259 op->o_tag = LDAP_REQ_SEARCH;
2260 op->o_protocol = LDAP_VERSION3;
2261 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2263 op->o_dn = op->o_bd->be_rootdn;
2264 op->o_ndn = op->o_bd->be_rootndn;
2265 sc.sc_response = fetch_queryId_cb;
2266 op->o_callback = ≻
2268 rc = op->o_bd->be_search( op, &rs );
2269 if ( rc != LDAP_SUCCESS ) {
2273 vals = (BerVarray)op->o_callback->sc_private;
2274 if ( vals != NULL ) {
2277 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2278 struct berval val = vals[ i ];
2280 remove_query_and_data( op, cm, &val );
2282 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2283 ch_free( val.bv_val );
2287 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2290 return LDAP_SUCCESS;
2296 struct berval *query_uuid )
2298 struct search_info *si = op->o_callback->sc_private;
2299 slap_overinst *on = si->on;
2300 cache_manager *cm = on->on_bi.bi_private;
2303 struct berval crp_uuid;
2304 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2306 Connection conn = {0};
2307 OperationBuffer opbuf;
2308 void *thrctx = ldap_pvt_thread_pool_context();
2310 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2311 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2313 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2314 op_tmp = &opbuf.ob_op;
2315 op_tmp->o_bd = &cm->db;
2316 op_tmp->o_dn = cm->db.be_rootdn;
2317 op_tmp->o_ndn = cm->db.be_rootndn;
2319 Debug( pcache_debug, "UUID for query being added = %s\n",
2322 for ( e=si->head; e; e=si->head ) {
2323 si->head = e->e_private;
2324 e->e_private = NULL;
2325 while ( cm->cur_entries > (cm->max_entries) ) {
2326 BER_BVZERO( &crp_uuid );
2327 remove_query_and_data( op_tmp, cm, &crp_uuid );
2330 return_val = merge_entry(op_tmp, e, 0, query_uuid);
2331 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2332 cm->cur_entries += return_val;
2333 Debug( pcache_debug,
2334 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2335 cm->cur_entries, 0, 0 );
2337 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2344 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2345 slap_callback *cb = op->o_callback;
2346 struct search_info *si = cb->sc_private;
2347 slap_overinst *on = si->on;
2348 cache_manager *cm = on->on_bi.bi_private;
2349 query_manager* qm = cm->qm;
2351 if ( rs->sr_type == REP_RESULT ||
2352 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2354 if ( si->swap_saved_attrs ) {
2355 rs->sr_attrs = si->save_attrs;
2356 op->ors_attrs = si->save_attrs;
2358 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) &&
2359 si->caching_reason == PC_IGNORE )
2361 filter_free( si->query.filter );
2363 /* duplicate query, free it */
2365 for (;si->head; si->head=e) {
2366 e = si->head->e_private;
2367 si->head->e_private = NULL;
2368 entry_free(si->head);
2372 } else if ( si->caching_reason != PC_IGNORE ) {
2373 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2374 si->qtemp, si->caching_reason, 1 );
2377 switch ( si->caching_reason ) {
2379 cache_entries( op, &qc->q_uuid );
2382 si->pbi->bi_cq = qc;
2387 qc->q_sizelimit = rs->sr_nentries;
2397 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2398 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2399 cm->num_cached_queries++;
2400 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2401 cm->num_cached_queries, 0, 0 );
2402 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2404 /* If the consistency checker suspended itself,
2407 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2408 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2409 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2411 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2413 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2416 } else if ( si->count ) {
2417 /* duplicate query, free it */
2419 for (;si->head; si->head=e) {
2420 e = si->head->e_private;
2421 si->head->e_private = NULL;
2422 entry_free(si->head);
2427 filter_free( si->query.filter );
2430 op->o_callback = op->o_callback->sc_next;
2431 op->o_tmpfree( cb, op->o_tmpmemctx );
2434 return SLAP_CB_CONTINUE;
2442 struct search_info *si = op->o_callback->sc_private;
2444 if ( si->swap_saved_attrs ) {
2445 rs->sr_attrs = si->save_attrs;
2446 rs->sr_attr_flags = slap_attr_flags( si->save_attrs );
2447 op->ors_attrs = si->save_attrs;
2450 if ( rs->sr_type == REP_SEARCH ) {
2453 /* don't return more entries than requested by the client */
2454 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2455 si->slimit_exceeded = 1;
2458 /* If we haven't exceeded the limit for this query,
2459 * build a chain of answers to store. If we hit the
2460 * limit, empty the chain and ignore the rest.
2463 slap_overinst *on = si->on;
2464 cache_manager *cm = on->on_bi.bi_private;
2466 /* check if the entry contains undefined
2467 * attributes/objectClasses (ITS#5680) */
2468 if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2469 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2470 op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
2474 /* check for malformed entries: attrs with no values */
2476 Attribute *a = rs->sr_entry->e_attrs;
2477 for (; a; a=a->a_next) {
2478 if ( !a->a_numvals ) {
2479 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2480 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2481 a->a_desc->ad_cname.bv_val );
2487 if ( si->count < si->max ) {
2489 e = entry_dup( rs->sr_entry );
2490 if ( !si->head ) si->head = e;
2491 if ( si->tail ) si->tail->e_private = e;
2498 for (;si->head; si->head=e) {
2499 e = si->head->e_private;
2500 si->head->e_private = NULL;
2501 entry_free(si->head);
2506 if ( si->slimit_exceeded ) {
2509 } else if ( rs->sr_type == REP_RESULT ) {
2512 if ( rs->sr_err == LDAP_SUCCESS ) {
2513 si->caching_reason = PC_POSITIVE;
2515 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2516 && si->qtemp->limitttl )
2520 si->caching_reason = PC_SIZELIMIT;
2521 for (;si->head; si->head=e) {
2522 e = si->head->e_private;
2523 si->head->e_private = NULL;
2524 entry_free(si->head);
2528 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2529 rs->sr_err == LDAP_SUCCESS )
2531 si->caching_reason = PC_NEGATIVE;
2535 if ( si->slimit_exceeded ) {
2536 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2540 return SLAP_CB_CONTINUE;
2543 /* NOTE: this is a quick workaround to let pcache minimally interact
2544 * with pagedResults. A more articulated solutions would be to
2545 * perform the remote query without control and cache all results,
2546 * performing the pagedResults search only within the client
2547 * and the proxy. This requires pcache to understand pagedResults. */
2549 pcache_chk_controls(
2553 const char *non = "";
2554 const char *stripped = "";
2556 switch( op->o_pagedresults ) {
2557 case SLAP_CONTROL_NONCRITICAL:
2559 stripped = "; stripped";
2562 case SLAP_CONTROL_CRITICAL:
2563 Debug( pcache_debug, "%s: "
2564 "%scritical pagedResults control "
2565 "disabled with proxy cache%s.\n",
2566 op->o_log_prefix, non, stripped );
2568 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2572 rs->sr_err = SLAP_CB_CONTINUE;
2580 pc_setpw( Operation *op, struct berval *pwd, cache_manager *cm )
2582 struct berval vals[2];
2585 const char *text = NULL;
2586 BER_BVZERO( &vals[0] );
2587 slap_passwd_hash( pwd, &vals[0], &text );
2588 if ( BER_BVISEMPTY( &vals[0] )) {
2589 Debug( pcache_debug, "pc_setpw: hash failed %s\n",
2595 BER_BVZERO( &vals[1] );
2599 SlapReply sr = { REP_RESULT };
2600 slap_callback cb = { 0, slap_null_cb, 0, 0 };
2603 mod.sml_op = LDAP_MOD_REPLACE;
2605 mod.sml_desc = slap_schema.si_ad_userPassword;
2606 mod.sml_type = mod.sml_desc->ad_cname;
2607 mod.sml_values = vals;
2608 mod.sml_nvalues = NULL;
2609 mod.sml_numvals = 1;
2610 mod.sml_next = NULL;
2612 op->o_tag = LDAP_REQ_MODIFY;
2613 op->orm_modlist = &mod;
2615 op->o_dn = op->o_bd->be_rootdn;
2616 op->o_ndn = op->o_bd->be_rootndn;
2617 op->o_callback = &cb;
2618 Debug( pcache_debug, "pc_setpw: CACHING BIND for %s\n",
2619 op->o_req_dn.bv_val, 0, 0 );
2620 rc = op->o_bd->be_modify( op, &sr );
2621 ch_free( vals[0].bv_val );
2626 typedef struct bindcacheinfo {
2632 pc_bind_save( Operation *op, SlapReply *rs )
2634 if ( rs->sr_err == LDAP_SUCCESS ) {
2635 bindcacheinfo *bci = op->o_callback->sc_private;
2636 slap_overinst *on = bci->on;
2637 cache_manager *cm = on->on_bi.bi_private;
2638 CachedQuery *qc = bci->qc;
2641 ldap_pvt_thread_rdwr_wlock( &qc->rwlock );
2642 if ( qc->bind_refcnt-- ) {
2643 Operation op2 = *op;
2644 if ( pc_setpw( &op2, &op->orb_cred, cm ) == LDAP_SUCCESS )
2645 bci->qc->bindref_time = op->o_time + bci->qc->qtemp->bindttr;
2650 ldap_pvt_thread_rdwr_wunlock( &qc->rwlock );
2651 if ( delete ) free_query(qc);
2653 return SLAP_CB_CONTINUE;
2657 pc_bind_attrs( Operation *op, Entry *e, QueryTemplate *temp,
2658 struct berval *fbv )
2661 struct berval *vals, pres = BER_BVC("*");
2665 vals = op->o_tmpalloc( temp->bindnattrs * sizeof( struct berval ),
2668 for ( i=0; i<temp->bindnattrs; i++ ) {
2669 a = attr_find( e->e_attrs, temp->bindfattrs[i] );
2670 if ( a && a->a_vals ) {
2671 vals[i] = a->a_vals[0];
2672 len += a->a_vals[0].bv_len;
2677 fbv->bv_len = len + temp->bindftemp.bv_len;
2678 fbv->bv_val = op->o_tmpalloc( fbv->bv_len + 1, op->o_tmpmemctx );
2680 p1 = temp->bindftemp.bv_val;
2685 if ( p1[0] == '=' && p1[1] == ')' ) {
2686 AC_MEMCPY( p2, vals[i].bv_val, vals[i].bv_len );
2687 p2 += vals[i].bv_len;
2693 op->o_tmpfree( vals, op->o_tmpmemctx );
2695 /* FIXME: are we sure str2filter_x can't fail?
2696 * caller needs to check */
2698 Filter *f = str2filter_x( op, fbv->bv_val );
2699 assert( f != NULL );
2704 /* Check if the requested entry is from the cache and has a valid
2705 * ttr and password hash
2708 pc_bind_search( Operation *op, SlapReply *rs )
2710 if ( rs->sr_type == REP_SEARCH ) {
2711 bindinfo *pbi = op->o_callback->sc_private;
2713 /* We only care if this is an already cached result and we're
2714 * below the refresh time, or we're offline.
2717 if (( pbi->bi_cm->cc_paused & PCACHE_CC_OFFLINE ) ||
2718 op->o_time < pbi->bi_cq->bindref_time ) {
2721 /* See if a recognized password is hashed here */
2722 a = attr_find( rs->sr_entry->e_attrs,
2723 slap_schema.si_ad_userPassword );
2724 if ( a && a->a_vals[0].bv_val[0] == '{' &&
2725 lutil_passwd_scheme( a->a_vals[0].bv_val ))
2726 pbi->bi_flags |= BI_HASHED;
2728 Debug( pcache_debug, "pc_bind_search: cache is stale, "
2729 "reftime: %ld, current time: %ld\n",
2730 pbi->bi_cq->bindref_time, op->o_time, 0 );
2732 } else if ( pbi->bi_si ) {
2733 /* This search result is going into the cache */
2737 filter_free( pbi->bi_si->query.filter );
2738 f = pc_bind_attrs( op, rs->sr_entry, pbi->bi_templ, &fbv );
2739 op->o_tmpfree( fbv.bv_val, op->o_tmpmemctx );
2740 pbi->bi_si->query.filter = filter_dup( f, NULL );
2741 filter_free_x( op, f, 1 );
2747 /* We always want pc_bind_search to run after the search handlers */
2749 pc_bind_resp( Operation *op, SlapReply *rs )
2751 bindinfo *pbi = op->o_callback->sc_private;
2752 if ( !( pbi->bi_flags & BI_DIDCB )) {
2753 slap_callback *sc = op->o_callback;
2754 while ( sc && sc->sc_response != pcache_response )
2757 sc = op->o_callback;
2758 pbi->bi_cb.sc_next = sc->sc_next;
2759 sc->sc_next = &pbi->bi_cb;
2760 pbi->bi_flags |= BI_DIDCB;
2762 return SLAP_CB_CONTINUE;
2765 #ifdef PCACHE_CONTROL_PRIVDB
2771 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2772 cache_manager *cm = on->on_bi.bi_private;
2773 slap_callback *save_cb;
2776 /* skip if control is unset */
2777 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2778 return SLAP_CB_CONTINUE;
2781 /* The cache DB isn't open yet */
2782 if ( cm->defer_db_open ) {
2783 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2784 "pcachePrivDB: cacheDB not available" );
2788 /* FIXME: might be a little bit exaggerated... */
2789 if ( !be_isroot( op ) ) {
2790 save_cb = op->o_callback;
2791 op->o_callback = NULL;
2792 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2793 "pcachePrivDB: operation not allowed" );
2794 op->o_callback = save_cb;
2799 /* map tag to operation */
2800 type = slap_req2op( op->o_tag );
2801 if ( type != SLAP_OP_LAST ) {
2802 BackendInfo *bi = cm->db.bd_info;
2805 /* execute, if possible */
2806 if ( (&bi->bi_op_bind)[ type ] ) {
2807 Operation op2 = *op;
2811 rc = (&bi->bi_op_bind)[ type ]( &op2, rs );
2812 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2813 op->o_conn->c_authz_cookie = cm->db.be_private;
2820 /* otherwise fall back to error */
2821 save_cb = op->o_callback;
2822 op->o_callback = NULL;
2823 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2824 "operation not supported with pcachePrivDB control" );
2825 op->o_callback = save_cb;
2829 #endif /* PCACHE_CONTROL_PRIVDB */
2836 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2837 cache_manager *cm = on->on_bi.bi_private;
2838 QueryTemplate *temp;
2840 slap_callback cb = { 0 }, *sc;
2841 bindinfo bi = { 0 };
2846 #ifdef PCACHE_CONTROL_PRIVDB
2847 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL )
2848 return pcache_op_privdb( op, rs );
2849 #endif /* PCACHE_CONTROL_PRIVDB */
2851 /* Skip if we're not configured for Binds, or cache DB isn't open yet */
2852 if ( !cm->cache_binds || cm->defer_db_open )
2853 return SLAP_CB_CONTINUE;
2855 /* First find a matching template with Bind info */
2856 for ( temp=cm->qm->templates; temp; temp=temp->qmnext ) {
2857 if ( temp->bindttr && dnIsSuffix( &op->o_req_ndn, &temp->bindbase ))
2860 /* Didn't find a suitable template, just passthru */
2862 return SLAP_CB_CONTINUE;
2864 /* See if the entry is already locally cached. If so, we can
2865 * populate the query filter to retrieve the cached query. We
2866 * need to check the bindrefresh time in the query.
2869 op2.o_dn = op->o_bd->be_rootdn;
2870 op2.o_ndn = op->o_bd->be_rootndn;
2874 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL, NULL, 0, &e );
2875 if ( rc == LDAP_SUCCESS && e ) {
2876 bi.bi_flags |= BI_LOOKUP;
2877 op2.ors_filter = pc_bind_attrs( op, e, temp, &op2.ors_filterstr );
2878 be_entry_release_r( &op2, e );
2880 op2.ors_filter = temp->bindfilter;
2881 op2.ors_filterstr = temp->bindfilterstr;
2884 op2.o_bd = op->o_bd;
2885 op2.o_tag = LDAP_REQ_SEARCH;
2886 op2.ors_scope = LDAP_SCOPE_BASE;
2887 op2.ors_deref = LDAP_DEREF_NEVER;
2889 op2.ors_tlimit = SLAP_NO_LIMIT;
2890 op2.ors_limit = NULL;
2891 op2.ors_attrs = cm->qm->attr_sets[temp->attr_set_index].attrs;
2892 op2.ors_attrsonly = 0;
2894 /* We want to invoke search at the same level of the stack
2895 * as we're already at...
2900 bi.bi_cb.sc_response = pc_bind_search;
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 sc->sc_writewait = NULL;
2937 bci = sc->sc_private;
2938 sc->sc_next = op->o_callback;
2939 op->o_callback = sc;
2943 return SLAP_CB_CONTINUE;
2946 static slap_response refresh_merge;
2953 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2954 cache_manager *cm = on->on_bi.bi_private;
2955 query_manager* qm = cm->qm;
2960 QueryTemplate *qtemp = NULL;
2961 bindinfo *pbi = NULL;
2964 CachedQuery *answerable = NULL;
2967 struct berval tempstr;
2969 #ifdef PCACHE_CONTROL_PRIVDB
2970 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2971 return pcache_op_privdb( op, rs );
2973 #endif /* PCACHE_CONTROL_PRIVDB */
2975 /* The cache DB isn't open yet */
2976 if ( cm->defer_db_open ) {
2977 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2978 "pcachePrivDB: cacheDB not available" );
2982 /* pickup runtime ACL changes */
2983 cm->db.be_acl = op->o_bd->be_acl;
2986 /* See if we're processing a Bind request
2987 * or a cache refresh */
2988 slap_callback *cb = op->o_callback;
2990 for ( ; cb; cb=cb->sc_next ) {
2991 if ( cb->sc_response == pc_bind_resp ) {
2992 pbi = cb->sc_private;
2995 if ( cb->sc_response == refresh_merge ) {
2996 /* This is a refresh, do not search the cache */
2997 return SLAP_CB_CONTINUE;
3002 /* FIXME: cannot cache/answer requests with pagedResults control */
3004 query.filter = op->ors_filter;
3007 query.base = pbi->bi_templ->bindbase;
3008 query.scope = pbi->bi_templ->bindscope;
3009 attr_set = pbi->bi_templ->attr_set_index;
3011 qtemp = pbi->bi_templ;
3012 if ( pbi->bi_flags & BI_LOOKUP )
3013 answerable = qm->qcfunc(op, qm, &query, qtemp);
3016 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1,
3019 if ( filter2template( op, op->ors_filter, &tempstr ))
3021 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3022 return SLAP_CB_CONTINUE;
3025 Debug( pcache_debug, "query template of incoming query = %s\n",
3026 tempstr.bv_val, 0, 0 );
3029 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
3031 query.base = op->o_req_ndn;
3032 query.scope = op->ors_scope;
3034 /* check for query containment */
3035 if (attr_set > -1) {
3036 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
3037 for (; qt; qt = qt->qtnext ) {
3038 /* find if template i can potentially answer tempstr */
3039 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
3043 Debug( pcache_debug, "Entering QC, querystr = %s\n",
3044 op->ors_filterstr.bv_val, 0, 0 );
3045 answerable = qm->qcfunc(op, qm, &query, qt);
3047 /* if != NULL, rlocks qtemp->t_rwlock */
3052 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3056 BackendDB *save_bd = op->o_bd;
3058 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
3059 answerable->answerable_cnt++;
3060 /* we only care about refcnts if we're refreshing */
3061 if ( answerable->refresh_time )
3062 answerable->refcnt++;
3063 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
3064 answerable->answerable_cnt, 0, 0 );
3065 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
3067 ldap_pvt_thread_rdwr_wlock(&answerable->rwlock);
3068 if ( BER_BVISNULL( &answerable->q_uuid )) {
3069 /* No entries cached, just an empty result set */
3071 send_ldap_result( op, rs );
3073 /* Let Bind know we used a cached query */
3075 answerable->bind_refcnt++;
3076 pbi->bi_cq = answerable;
3080 if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
3082 /* The cached entry was already processed by any
3083 * other overlays, so don't let it get processed again.
3085 * This loop removes over_back_response from the stack.
3087 if ( overlay_callback_after_backover( op, &cb, 0) == 0 ) {
3088 slap_callback **scp;
3089 for ( scp = &op->o_callback; *scp != NULL;
3090 scp = &(*scp)->sc_next ) {
3091 if ( (*scp)->sc_next == &cb ) {
3098 i = cm->db.bd_info->bi_op_search( op, rs );
3100 ldap_pvt_thread_rdwr_wunlock(&answerable->rwlock);
3101 /* locked by qtemp->qcfunc (query_containment) */
3102 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
3107 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
3109 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3110 if (cm->num_cached_queries >= cm->max_queries) {
3113 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3115 if (op->ors_attrsonly)
3120 struct search_info *si;
3122 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
3123 query.filter = filter_dup(op->ors_filter, NULL);
3125 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
3126 cb->sc_response = pcache_response;
3127 cb->sc_cleanup = pcache_op_cleanup;
3128 cb->sc_private = (cb+1);
3129 cb->sc_writewait = 0;
3130 si = cb->sc_private;
3134 si->max = cm->num_entries_limit ;
3138 si->slimit_exceeded = 0;
3139 si->caching_reason = PC_IGNORE;
3140 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
3141 si->slimit = op->ors_slimit;
3142 op->ors_slimit = cm->num_entries_limit;
3146 si->swap_saved_attrs = 1;
3147 si->save_attrs = op->ors_attrs;
3152 op->ors_attrs = qtemp->t_attrs.attrs;
3154 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3155 cb->sc_next = op->o_callback;
3156 op->o_callback = cb;
3159 slap_callback **pcb;
3161 /* need to move the callback at the end, in case other
3162 * overlays are present, so that the final entry is
3163 * actually cached */
3165 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
3170 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
3174 return SLAP_CB_CONTINUE;
3179 AttributeName* attrs,
3187 for ( ; attrs[i].an_name.bv_val; i++ ) {
3188 /* only count valid attribute names
3189 * (searches ignore others, this overlay does the same) */
3190 if ( attrs[i].an_desc ) {
3196 /* recognize default or explicit single "*" */
3198 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_all_user_attrs ) ) )
3201 attrs = slap_anlist_all_user_attributes;
3203 /* recognize implicit (no valid attributes) or explicit single "1.1" */
3204 } else if ( count == 0 ||
3205 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) )
3211 for ( i = 0; i < num; i++ ) {
3215 if ( count > qm->attr_sets[i].count ) {
3216 if ( qm->attr_sets[i].count &&
3217 bvmatch( &qm->attr_sets[i].attrs[0].an_name, slap_bv_all_user_attrs )) {
3224 if ( !qm->attr_sets[i].count ) {
3230 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
3231 if ( !a2->an_desc && !bvmatch( &a2->an_name, slap_bv_all_user_attrs ) ) continue;
3233 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
3251 /* Refresh a cached query:
3252 * 1: Replay the query on the remote DB and merge each entry into
3253 * the local DB. Remember the DNs of each remote entry.
3254 * 2: Search the local DB for all entries matching this queryID.
3255 * Delete any entry whose DN is not in the list from (1).
3257 typedef struct dnlist {
3258 struct dnlist *next;
3263 typedef struct refresh_info {
3271 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
3273 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
3275 dn->dn.bv_len = bvdn->bv_len;
3276 dn->dn.bv_val = (char *)(dn+1);
3277 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
3278 dn->dn.bv_val[dn->dn.bv_len] = '\0';
3283 refresh_merge( Operation *op, SlapReply *rs )
3285 if ( rs->sr_type == REP_SEARCH ) {
3286 refresh_info *ri = op->o_callback->sc_private;
3292 ocb = op->o_callback;
3293 /* Find local entry, merge */
3294 op->o_bd = ri->ri_be;
3295 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
3296 if ( rc != LDAP_SUCCESS || e == NULL ) {
3297 /* No local entry, just add it. FIXME: we are not checking
3298 * the cache entry limit here
3300 merge_entry( op, rs->sr_entry, 1, &ri->ri_q->q_uuid );
3302 /* Entry exists, update it */
3305 Modifications *modlist, *mods = NULL;
3306 const char* text = NULL;
3307 char textbuf[SLAP_TEXT_BUFLEN];
3308 size_t textlen = sizeof(textbuf);
3309 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
3313 /* Get a copy of only the attrs we requested */
3314 for ( a=e->e_attrs; a; a=a->a_next ) {
3315 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
3316 *b = attr_alloc( a->a_desc );
3318 /* The actual values still belong to e */
3319 (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
3320 SLAP_ATTR_DONT_FREE_DATA;
3321 b = &((*b)->a_next);
3325 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
3326 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
3327 &mods, &modlist, 0 );
3328 be_entry_release_r( op, e );
3329 attrs_free( ne.e_attrs );
3330 slap_mods_free( modlist, 1 );
3331 /* mods is NULL if there are no changes */
3333 SlapReply rs2 = { REP_RESULT };
3334 struct berval dn = op->o_req_dn;
3335 struct berval ndn = op->o_req_ndn;
3336 op->o_tag = LDAP_REQ_MODIFY;
3337 op->orm_modlist = mods;
3338 op->o_req_dn = rs->sr_entry->e_name;
3339 op->o_req_ndn = rs->sr_entry->e_nname;
3340 op->o_callback = &cb;
3341 op->o_bd->be_modify( op, &rs2 );
3342 rs->sr_err = rs2.sr_err;
3343 rs_assert_done( &rs2 );
3344 slap_mods_free( mods, 1 );
3346 op->o_req_ndn = ndn;
3350 /* Add DN to list */
3351 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3353 if ( ri->ri_tail ) {
3354 ri->ri_tail->next = dnl;
3359 op->o_callback = ocb;
3365 refresh_purge( Operation *op, SlapReply *rs )
3367 if ( rs->sr_type == REP_SEARCH ) {
3368 refresh_info *ri = op->o_callback->sc_private;
3372 /* Did the entry exist on the remote? */
3373 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
3374 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
3375 dnlist *dnext = (*dn)->next;
3376 op->o_tmpfree( *dn, op->o_tmpmemctx );
3382 /* No, so put it on the list to delete */
3385 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3386 dnl->next = ri->ri_dels;
3388 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
3389 /* If ours is the only queryId, delete entry */
3390 dnl->delete = ( a->a_numvals == 1 );
3397 refresh_query( Operation *op, CachedQuery *query, slap_overinst *on )
3399 SlapReply rs = {REP_RESULT};
3400 slap_callback cb = { 0 };
3401 refresh_info ri = { 0 };
3402 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
3403 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3404 Filter filter = {LDAP_FILTER_EQUALITY};
3405 AttributeName attrs[ 2 ] = {{{ 0 }}};
3409 ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
3411 ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
3413 cb.sc_response = refresh_merge;
3414 cb.sc_private = &ri;
3417 ri.ri_be = op->o_bd;
3420 op->o_tag = LDAP_REQ_SEARCH;
3421 op->o_protocol = LDAP_VERSION3;
3422 op->o_callback = &cb;
3423 op->o_do_not_cache = 1;
3425 op->o_req_dn = query->qbase->base;
3426 op->o_req_ndn = query->qbase->base;
3427 op->ors_scope = query->scope;
3428 op->ors_deref = LDAP_DEREF_NEVER;
3429 op->ors_slimit = SLAP_NO_LIMIT;
3430 op->ors_tlimit = SLAP_NO_LIMIT;
3431 op->ors_limit = NULL;
3432 op->ors_filter = query->filter;
3433 filter2bv_x( op, query->filter, &op->ors_filterstr );
3434 op->ors_attrs = query->qtemp->t_attrs.attrs;
3435 op->ors_attrsonly = 0;
3437 op->o_bd = on->on_info->oi_origdb;
3438 rc = op->o_bd->be_search( op, &rs );
3440 op->o_bd = ri.ri_be;
3444 /* Get the DNs of all entries matching this query */
3445 cb.sc_response = refresh_purge;
3447 op->o_bd = ri.ri_be;
3448 op->o_req_dn = op->o_bd->be_suffix[0];
3449 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3450 op->ors_scope = LDAP_SCOPE_SUBTREE;
3451 op->ors_deref = LDAP_DEREF_NEVER;
3452 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
3453 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
3454 filter.f_ava = &ava;
3455 filter.f_av_desc = ad_queryId;
3456 filter.f_av_value = query->q_uuid;
3457 attrs[ 0 ].an_desc = ad_queryId;
3458 attrs[ 0 ].an_name = ad_queryId->ad_cname;
3459 op->ors_attrs = attrs;
3460 op->ors_attrsonly = 0;
3461 rs_reinit( &rs, REP_RESULT );
3462 rc = op->o_bd->be_search( op, &rs );
3463 if ( rc ) goto leave;
3465 while (( dn = ri.ri_dels )) {
3466 op->o_req_dn = dn->dn;
3467 op->o_req_ndn = dn->dn;
3468 rs_reinit( &rs, REP_RESULT );
3470 op->o_tag = LDAP_REQ_DELETE;
3471 op->o_bd->be_delete( op, &rs );
3474 struct berval vals[2];
3476 vals[0] = query->q_uuid;
3477 BER_BVZERO( &vals[1] );
3478 mod.sml_op = LDAP_MOD_DELETE;
3480 mod.sml_desc = ad_queryId;
3481 mod.sml_type = ad_queryId->ad_cname;
3482 mod.sml_values = vals;
3483 mod.sml_nvalues = NULL;
3484 mod.sml_numvals = 1;
3485 mod.sml_next = NULL;
3487 op->o_tag = LDAP_REQ_MODIFY;
3488 op->orm_modlist = &mod;
3489 op->o_bd->be_modify( op, &rs );
3491 ri.ri_dels = dn->next;
3492 op->o_tmpfree( dn, op->o_tmpmemctx );
3496 /* reset our local heap, we're done with it */
3497 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
3506 struct re_s *rtask = arg;
3507 slap_overinst *on = rtask->arg;
3508 cache_manager *cm = on->on_bi.bi_private;
3509 query_manager *qm = cm->qm;
3510 Connection conn = {0};
3511 OperationBuffer opbuf;
3514 CachedQuery *query, *qprev;
3515 int return_val, pause = PCACHE_CC_PAUSED;
3516 QueryTemplate *templ;
3518 /* Don't expire anything when we're offline */
3519 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
3520 pause = PCACHE_CC_OFFLINE;
3524 connection_fake_init( &conn, &opbuf, ctx );
3528 op->o_dn = cm->db.be_rootdn;
3529 op->o_ndn = cm->db.be_rootndn;
3533 for (templ = qm->templates; templ; templ=templ->qmnext) {
3535 if ( !templ->query_last ) continue;
3537 op->o_time = slap_get_time();
3538 if ( !templ->ttr ) {
3540 if ( templ->negttl && templ->negttl < ttl )
3541 ttl = templ->negttl;
3542 if ( templ->limitttl && templ->limitttl < ttl )
3543 ttl = templ->limitttl;
3544 /* The oldest timestamp that needs expiration checking */
3548 for ( query=templ->query_last; query; query=qprev ) {
3549 qprev = query->prev;
3550 if ( query->refresh_time && query->refresh_time < op->o_time ) {
3551 /* A refresh will extend the expiry if the query has been
3552 * referenced, but not if it's unreferenced. If the
3553 * expiration has been hit, then skip the refresh since
3554 * we're just going to discard the result anyway.
3556 if ( query->refcnt )
3557 query->expiry_time = op->o_time + templ->ttl;
3558 if ( query->expiry_time > op->o_time ) {
3559 refresh_query( op, query, on );
3564 if (query->expiry_time < op->o_time) {
3566 Debug( pcache_debug, "Lock CR index = %p\n",
3567 (void *) templ, 0, 0 );
3568 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
3569 if ( query == templ->query_last ) {
3571 remove_from_template(query, templ);
3572 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
3573 (void *) templ, templ->no_of_queries, 0 );
3574 Debug( pcache_debug, "Unlock CR index = %p\n",
3575 (void *) templ, 0, 0 );
3578 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3581 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
3582 remove_query(qm, query);
3583 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
3584 if ( BER_BVISNULL( &query->q_uuid ))
3587 return_val = remove_query_data(op, &query->q_uuid);
3588 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3590 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3591 cm->cur_entries -= return_val;
3592 cm->num_cached_queries--;
3593 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3594 cm->num_cached_queries, 0, 0 );
3595 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3596 Debug( pcache_debug,
3597 "STALE QUERY REMOVED, CACHE ="
3599 cm->cur_entries, 0, 0 );
3600 ldap_pvt_thread_rdwr_wlock( &query->rwlock );
3601 if ( query->bind_refcnt-- ) {
3606 ldap_pvt_thread_rdwr_wunlock( &query->rwlock );
3607 if ( rem ) free_query(query);
3608 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3609 } else if ( !templ->ttr && query->expiry_time > ttl ) {
3610 /* We don't need to check for refreshes, and this
3611 * query's expiry is too new, and all subsequent queries
3612 * will be newer yet. So stop looking.
3614 * If we have refreshes, then we always have to walk the
3615 * entire query list.
3623 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3624 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3625 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3627 /* If there were no queries, defer processing for a while */
3628 if ( cm->cc_paused != pause )
3629 cm->cc_paused = pause;
3630 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3632 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3637 #define MAX_ATTR_SETS 500
3650 static ConfigDriver pc_cf_gen;
3651 static ConfigLDAPadd pc_ldadd;
3652 static ConfigCfAdd pc_cfadd;
3654 static ConfigTable pccfg[] = {
3655 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3657 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3658 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3659 "DESC 'Proxy Cache basic parameters' "
3660 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3661 { "pcacheAttrset", "index> <attributes...",
3662 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3663 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3664 "DESC 'A set of attributes to cache' "
3665 "EQUALITY caseIgnoreMatch "
3666 "SYNTAX OMsDirectoryString )", NULL, NULL },
3667 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3669 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3670 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3671 "DESC 'Filter template, attrset, cache TTL, "
3672 "optional negative TTL, optional sizelimit TTL, "
3674 "EQUALITY caseIgnoreMatch "
3675 "SYNTAX OMsDirectoryString )", NULL, NULL },
3676 { "pcachePosition", "head|tail(default)",
3677 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3678 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3679 "DESC 'Response callback position in overlay stack' "
3680 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3681 { "pcacheMaxQueries", "queries",
3682 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3683 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3684 "DESC 'Maximum number of queries to cache' "
3685 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
3686 { "pcachePersist", "TRUE|FALSE",
3687 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3688 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3689 "DESC 'Save cached queries for hot restart' "
3690 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3691 { "pcacheValidate", "TRUE|FALSE",
3692 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3693 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3694 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3695 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3696 { "pcacheOffline", "TRUE|FALSE",
3697 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3698 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3699 "DESC 'Set cache to offline mode and disable expiration' "
3700 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3701 { "pcacheBind", "filter> <attrset-index> <TTR> <scope> <base",
3702 6, 6, 0, ARG_MAGIC|PC_BIND, pc_cf_gen,
3703 "( OLcfgOvAt:2.9 NAME 'olcPcacheBind' "
3704 "DESC 'Parameters for caching Binds' "
3705 "EQUALITY caseIgnoreMatch "
3706 "SYNTAX OMsDirectoryString )", NULL, NULL },
3707 { "pcache-", "private database args",
3708 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3711 /* Legacy keywords */
3712 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3714 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3716 { "proxyattrset", "index> <attributes...",
3717 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3719 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3720 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3722 { "response-callback", "head|tail(default)",
3723 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3725 { "proxyCacheQueries", "queries",
3726 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3728 { "proxySaveQueries", "TRUE|FALSE",
3729 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3731 { "proxyCheckCacheability", "TRUE|FALSE",
3732 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3735 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3738 static ConfigOCs pcocs[] = {
3739 { "( OLcfgOvOc:2.1 "
3740 "NAME 'olcPcacheConfig' "
3741 "DESC 'ProxyCache configuration' "
3742 "SUP olcOverlayConfig "
3743 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3744 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3745 "olcPcacheValidate $ olcPcacheOffline $ olcPcacheBind ) )",
3746 Cft_Overlay, pccfg, NULL, pc_cfadd },
3747 { "( OLcfgOvOc:2.2 "
3748 "NAME 'olcPcacheDatabase' "
3749 "DESC 'Cache database configuration' "
3750 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3754 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3757 pc_ldadd_cleanup( ConfigArgs *c )
3759 slap_overinst *on = c->ca_private;
3760 return pcache_db_open2( on, &c->reply );
3764 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3769 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3770 p->ce_bi->bi_cf_ocs != pcocs )
3771 return LDAP_CONSTRAINT_VIOLATION;
3773 on = (slap_overinst *)p->ce_bi;
3774 cm = on->on_bi.bi_private;
3776 /* Defer open if this is an LDAPadd */
3777 if ( CONFIG_ONLINE_ADD( ca ))
3778 ca->cleanup = pc_ldadd_cleanup;
3780 cm->defer_db_open = 0;
3781 ca->ca_private = on;
3782 return LDAP_SUCCESS;
3786 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3788 CfEntryInfo *pe = p->e_private;
3789 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3790 cache_manager *cm = on->on_bi.bi_private;
3793 /* FIXME: should not hardcode "olcDatabase" here */
3794 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3795 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3796 0, cm->db.bd_info->bi_type );
3797 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3800 bv.bv_val = ca->cr_msg;
3802 cm->defer_db_open = 0;
3804 /* We can only create this entry if the database is table-driven
3806 if ( cm->db.bd_info->bi_cf_ocs )
3807 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3814 pc_cf_gen( ConfigArgs *c )
3816 slap_overinst *on = (slap_overinst *)c->bi;
3817 cache_manager* cm = on->on_bi.bi_private;
3818 query_manager* qm = cm->qm;
3819 QueryTemplate* temp;
3820 AttributeName* attr_name;
3821 AttributeName* attrarray;
3822 const char* text=NULL;
3827 if ( c->op == SLAP_CONFIG_EMIT ) {
3831 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3832 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3833 cm->num_entries_limit, cm->cc_period );
3834 bv.bv_val = c->cr_msg;
3835 value_add_one( &c->rvalue_vals, &bv );
3838 for (i=0; i<cm->numattrsets; i++) {
3839 if ( !qm->attr_sets[i].count ) continue;
3841 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3843 /* count the attr length */
3844 for ( attr_name = qm->attr_sets[i].attrs;
3845 attr_name->an_name.bv_val; attr_name++ )
3847 bv.bv_len += attr_name->an_name.bv_len + 1;
3848 if ( attr_name->an_desc &&
3849 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3850 bv.bv_len += STRLENOF("undef:");
3854 bv.bv_val = ch_malloc( bv.bv_len+1 );
3855 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3856 for ( attr_name = qm->attr_sets[i].attrs;
3857 attr_name->an_name.bv_val; attr_name++ ) {
3859 if ( attr_name->an_desc &&
3860 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3861 ptr = lutil_strcopy( ptr, "undef:" );
3863 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3865 ber_bvarray_add( &c->rvalue_vals, &bv );
3867 if ( !c->rvalue_vals )
3871 for (temp=qm->templates; temp; temp=temp->qmnext) {
3872 /* HEADS-UP: always print all;
3873 * if optional == 0, ignore */
3874 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3875 " %d %ld %ld %ld %ld",
3876 temp->attr_set_index,
3881 bv.bv_len += temp->querystr.bv_len + 2;
3882 bv.bv_val = ch_malloc( bv.bv_len+1 );
3885 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3887 strcpy( ptr, c->cr_msg );
3888 ber_bvarray_add( &c->rvalue_vals, &bv );
3890 if ( !c->rvalue_vals )
3894 for (temp=qm->templates; temp; temp=temp->qmnext) {
3895 if ( !temp->bindttr ) continue;
3896 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3898 temp->attr_set_index,
3900 ldap_pvt_scope2str( temp->bindscope ));
3901 bv.bv_len += temp->bindbase.bv_len + temp->bindftemp.bv_len + 4;
3902 bv.bv_val = ch_malloc( bv.bv_len + 1 );
3905 ptr = lutil_strcopy( ptr, temp->bindftemp.bv_val );
3907 ptr = lutil_strcopy( ptr, c->cr_msg );
3909 ptr = lutil_strcopy( ptr, temp->bindbase.bv_val );
3912 ber_bvarray_add( &c->rvalue_vals, &bv );
3914 if ( !c->rvalue_vals )
3918 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3919 BER_BVSTR( &bv, "head" );
3921 BER_BVSTR( &bv, "tail" );
3923 value_add_one( &c->rvalue_vals, &bv );
3926 c->value_int = cm->max_queries;
3929 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3933 } else if ( c->op == LDAP_MOD_DELETE ) {
3936 case PC_ATTR: /* FIXME */
3941 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3942 /* If there were cached queries when we went offline,
3943 * restart the checker now.
3945 if ( cm->num_cached_queries ) {
3946 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3948 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3949 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3959 if ( cm->numattrsets > 0 ) {
3960 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive already provided" );
3961 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3965 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3966 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3968 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3971 if ( cm->numattrsets <= 0 ) {
3972 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3973 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3976 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3977 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3978 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3982 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3983 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3984 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3988 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3989 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3991 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3994 if ( cm->max_entries <= 0 ) {
3995 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3996 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
4000 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
4001 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
4003 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4006 if ( cm->num_entries_limit <= 0 ) {
4007 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
4008 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4011 if ( cm->num_entries_limit > cm->max_entries ) {
4012 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
4013 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4017 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4018 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
4020 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4024 cm->cc_period = (time_t)t;
4025 Debug( pcache_debug,
4026 "Total # of attribute sets to be cached = %d.\n",
4027 cm->numattrsets, 0, 0 );
4028 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
4029 sizeof( struct attr_set ) );
4032 if ( cm->numattrsets == 0 ) {
4033 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4034 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4037 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
4038 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
4040 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4044 if ( num < 0 || num >= cm->numattrsets ) {
4045 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
4046 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4047 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4050 qm->attr_sets[num].flags |= PC_CONFIGURED;
4051 if ( c->argc == 2 ) {
4053 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4054 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
4055 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4058 } else if ( c->argc == 3 ) {
4059 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4060 qm->attr_sets[num].count = 1;
4061 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4062 sizeof( AttributeName ) );
4063 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4066 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4067 qm->attr_sets[num].count = 1;
4068 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4069 sizeof( AttributeName ) );
4070 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4073 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
4076 /* else: fallthru */
4078 } else if ( c->argc == 4 ) {
4079 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
4080 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
4082 qm->attr_sets[num].count = 2;
4083 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
4084 sizeof( AttributeName ) );
4085 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4086 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4089 /* else: fallthru */
4092 if ( c->argc > 2 ) {
4093 int all_user = 0, all_op = 0;
4095 qm->attr_sets[num].count = c->argc - 2;
4096 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
4097 sizeof( AttributeName ) );
4098 attr_name = qm->attr_sets[num].attrs;
4099 for ( i = 2; i < c->argc; i++ ) {
4100 attr_name->an_desc = NULL;
4101 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
4102 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4103 "invalid attr #%d \"%s\" in attrlist",
4104 i - 2, c->argv[i] );
4105 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4106 ch_free( qm->attr_sets[num].attrs );
4107 qm->attr_sets[num].attrs = NULL;
4108 qm->attr_sets[num].count = 0;
4111 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4113 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
4114 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4116 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4118 if ( strncasecmp( c->argv[i], "undef:", STRLENOF("undef:") ) == 0 ) {
4120 ber_str2bv( c->argv[i] + STRLENOF("undef:"), 0, 0, &bv );
4121 attr_name->an_desc = slap_bv2tmp_ad( &bv, NULL );
4123 } else if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
4124 strcpy( c->cr_msg, text );
4125 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4126 ch_free( qm->attr_sets[num].attrs );
4127 qm->attr_sets[num].attrs = NULL;
4128 qm->attr_sets[num].count = 0;
4131 attr_name->an_name = attr_name->an_desc->ad_cname;
4133 attr_name->an_oc = NULL;
4134 attr_name->an_flags = 0;
4135 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
4136 qm->attr_sets[num].flags |= PC_GOT_OC;
4138 BER_BVZERO( &attr_name->an_name );
4141 /* warn if list contains both "*" and "+" */
4142 if ( i > 4 && all_user && all_op ) {
4143 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4144 "warning: attribute list contains \"*\" and \"+\"" );
4145 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4150 if ( cm->numattrsets == 0 ) {
4151 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4152 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4155 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4156 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
4158 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4162 if ( i < 0 || i >= cm->numattrsets ||
4163 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4164 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
4165 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4166 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4170 AttributeName *attrs;
4172 cnt = template_attrs( c->argv[1], &qm->attr_sets[i], &attrs, &text );
4174 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4176 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4179 temp = ch_calloc( 1, sizeof( QueryTemplate ));
4180 temp->qmnext = qm->templates;
4181 qm->templates = temp;
4182 temp->t_attrs.attrs = attrs;
4183 temp->t_attrs.count = cnt;
4185 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
4186 temp->query = temp->query_last = NULL;
4187 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4188 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4189 "unable to parse template ttl=\"%s\"",
4191 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4193 ch_free( temp->t_attrs.attrs );
4197 temp->ttl = (time_t)t;
4198 temp->negttl = (time_t)0;
4199 temp->limitttl = (time_t)0;
4200 temp->ttr = (time_t)0;
4201 switch ( c->argc ) {
4203 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
4204 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4205 "unable to parse template ttr=\"%s\"",
4207 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4210 temp->ttr = (time_t)t;
4214 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4215 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4216 "unable to parse template sizelimit ttl=\"%s\"",
4218 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4221 temp->limitttl = (time_t)t;
4225 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
4226 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4227 "unable to parse template negative ttl=\"%s\"",
4229 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4232 temp->negttl = (time_t)t;
4236 temp->no_of_queries = 0;
4238 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
4239 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
4240 Debug( pcache_debug, " query template: %s\n",
4241 temp->querystr.bv_val, 0, 0 );
4242 temp->attr_set_index = i;
4243 qm->attr_sets[i].flags |= PC_REFERENCED;
4244 temp->qtnext = qm->attr_sets[i].templates;
4245 qm->attr_sets[i].templates = temp;
4246 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
4247 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
4248 for ( i=0; attrarray[i].an_name.bv_val; i++ )
4249 Debug( pcache_debug, "\t%s\n",
4250 attrarray[i].an_name.bv_val, 0, 0 );
4254 if ( !qm->templates ) {
4255 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcacheTemplate\" directive not provided yet" );
4256 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4259 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4260 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse Bind index #=\"%s\"",
4262 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4266 if ( i < 0 || i >= cm->numattrsets ||
4267 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4268 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind index %d invalid (%s%d)",
4269 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4270 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4273 { struct berval bv, tempbv;
4274 AttributeDescription **descs;
4276 ber_str2bv( c->argv[1], 0, 0, &bv );
4277 ndescs = ftemp_attrs( &bv, &tempbv, &descs, &text );
4279 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4281 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4284 for ( temp = qm->templates; temp; temp=temp->qmnext ) {
4285 if ( temp->attr_set_index == i && bvmatch( &tempbv,
4289 ch_free( tempbv.bv_val );
4292 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind template %s %d invalid",
4294 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4297 ber_dupbv( &temp->bindftemp, &bv );
4298 temp->bindfattrs = descs;
4299 temp->bindnattrs = ndescs;
4301 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4302 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4303 "unable to parse bind ttr=\"%s\"",
4305 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4307 ch_free( temp->bindfattrs );
4308 temp->bindfattrs = NULL;
4309 ch_free( temp->bindftemp.bv_val );
4310 BER_BVZERO( &temp->bindftemp );
4313 num = ldap_pvt_str2scope( c->argv[4] );
4315 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4316 "unable to parse bind scope=\"%s\"",
4318 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4322 struct berval dn, ndn;
4323 ber_str2bv( c->argv[5], 0, 0, &dn );
4324 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
4326 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4327 "invalid bind baseDN=\"%s\"",
4329 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4332 if ( temp->bindbase.bv_val )
4333 ch_free( temp->bindbase.bv_val );
4334 temp->bindbase = ndn;
4337 /* convert the template into dummy filter */
4339 char *eq = temp->bindftemp.bv_val, *e2;
4342 while ((eq = strchr(eq, '=' ))) {
4347 bv.bv_len = temp->bindftemp.bv_len + i;
4348 bv.bv_val = ch_malloc( bv.bv_len + 1 );
4349 for ( e2 = bv.bv_val, eq = temp->bindftemp.bv_val;
4360 f = str2filter( bv.bv_val );
4362 ch_free( bv.bv_val );
4363 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4364 "unable to parse bindfilter=\"%s\"", bv.bv_val );
4365 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4366 ch_free( temp->bindbase.bv_val );
4367 BER_BVZERO( &temp->bindbase );
4370 if ( temp->bindfilter )
4371 filter_free( temp->bindfilter );
4372 if ( temp->bindfilterstr.bv_val )
4373 ch_free( temp->bindfilterstr.bv_val );
4374 temp->bindfilterstr = bv;
4375 temp->bindfilter = f;
4377 temp->bindttr = (time_t)t;
4378 temp->bindscope = num;
4379 cm->cache_binds = 1;
4383 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
4384 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
4386 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
4387 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4390 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
4391 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4396 if ( c->value_int <= 0 ) {
4397 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
4398 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4401 cm->max_queries = c->value_int;
4405 cm->cc_paused |= PCACHE_CC_OFFLINE;
4407 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
4410 if ( cm->db.be_private == NULL ) {
4411 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4412 "private database must be defined before setting database specific options" );
4413 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4417 if ( cm->db.bd_info->bi_cf_ocs ) {
4420 char *argv0 = c->argv[ 0 ];
4422 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4424 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
4426 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4427 "private database does not recognize specific option '%s'",
4429 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4433 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
4435 c->bi = c->be->bd_info;
4437 rc = config_add_vals( ct, c );
4441 c->table = c2.table;
4444 c->argv[ 0 ] = argv0;
4446 } else if ( cm->db.be_config != NULL ) {
4447 char *argv0 = c->argv[ 0 ];
4449 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4450 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
4451 c->argv[ 0 ] = argv0;
4454 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4455 "no means to set private database specific options" );
4456 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
4461 rc = SLAP_CONF_UNKNOWN;
4477 slap_overinst *on = (slap_overinst *)be->bd_info;
4478 cache_manager* cm = on->on_bi.bi_private;
4480 /* Something for the cache database? */
4481 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
4482 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
4484 return SLAP_CONF_UNKNOWN;
4492 slap_overinst *on = (slap_overinst *)be->bd_info;
4496 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
4497 on->on_bi.bi_private = cm;
4499 qm = (query_manager*)ch_malloc(sizeof(query_manager));
4502 cm->db.bd_info = NULL;
4503 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
4504 cm->db.be_private = NULL;
4505 cm->db.bd_self = &cm->db;
4507 cm->numattrsets = 0;
4508 cm->num_entries_limit = 5;
4509 cm->num_cached_queries = 0;
4510 cm->max_entries = 0;
4511 cm->cur_entries = 0;
4512 cm->max_queries = 10000;
4513 cm->save_queries = 0;
4514 cm->check_cacheability = 0;
4515 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4516 cm->defer_db_open = 1;
4517 cm->cache_binds = 0;
4518 cm->cc_period = 1000;
4521 #ifdef PCACHE_MONITOR
4522 cm->monitor_cb = NULL;
4523 #endif /* PCACHE_MONITOR */
4525 qm->attr_sets = NULL;
4526 qm->templates = NULL;
4528 qm->lru_bottom = NULL;
4530 qm->qcfunc = query_containment;
4531 qm->crfunc = cache_replacement;
4532 qm->addfunc = add_query;
4533 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
4535 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
4537 #ifndef PCACHE_MONITOR
4539 #else /* PCACHE_MONITOR */
4540 return pcache_monitor_db_init( be );
4541 #endif /* PCACHE_MONITOR */
4545 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
4547 assert( op->o_tag == LDAP_REQ_SEARCH );
4549 if ( rs->sr_type == REP_SEARCH ) {
4552 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
4556 assert( a->a_nvals != NULL );
4558 valsp = op->o_callback->sc_private;
4559 assert( *valsp == NULL );
4561 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
4569 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
4571 assert( op->o_tag == LDAP_REQ_SEARCH );
4573 if ( rs->sr_type == REP_SEARCH ) {
4574 int *countp = (int *)op->o_callback->sc_private;
4587 cache_manager *cm = on->on_bi.bi_private;
4588 query_manager* qm = cm->qm;
4591 rc = backend_startup_one( &cm->db, cr );
4593 cm->defer_db_open = 0;
4596 /* There is no runqueue in TOOL mode */
4597 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
4598 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4599 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
4600 consistency_check, on,
4601 "pcache_consistency", cm->db.be_suffix[0].bv_val );
4602 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4604 /* Cached database must have the rootdn */
4605 if ( BER_BVISNULL( &cm->db.be_rootndn )
4606 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
4608 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
4609 "underlying database of type \"%s\"\n"
4610 " serving naming context \"%s\"\n"
4611 " has no \"rootdn\", required by \"pcache\".\n",
4612 on->on_info->oi_orig->bi_type,
4613 cm->db.be_suffix[0].bv_val, 0 );
4617 if ( cm->save_queries ) {
4618 void *thrctx = ldap_pvt_thread_pool_context();
4619 Connection conn = { 0 };
4620 OperationBuffer opbuf;
4622 slap_callback cb = { 0 };
4623 SlapReply rs = { REP_RESULT };
4624 BerVarray vals = NULL;
4625 Filter f = { 0 }, f2 = { 0 };
4626 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
4627 AttributeName attrs[ 2 ] = {{{ 0 }}};
4629 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4634 op->o_tag = LDAP_REQ_SEARCH;
4635 op->o_protocol = LDAP_VERSION3;
4636 cb.sc_response = pcache_cachedquery_open_cb;
4637 cb.sc_private = &vals;
4638 op->o_callback = &cb;
4639 op->o_time = slap_get_time();
4640 op->o_do_not_cache = 1;
4641 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4643 op->o_dn = cm->db.be_rootdn;
4644 op->o_ndn = cm->db.be_rootndn;
4645 op->o_req_dn = cm->db.be_suffix[ 0 ];
4646 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
4648 op->ors_scope = LDAP_SCOPE_BASE;
4649 op->ors_deref = LDAP_DEREF_NEVER;
4651 op->ors_tlimit = SLAP_NO_LIMIT;
4652 op->ors_limit = NULL;
4653 ber_str2bv( "(pcacheQueryURL=*)", 0, 0, &op->ors_filterstr );
4654 f.f_choice = LDAP_FILTER_PRESENT;
4655 f.f_desc = ad_cachedQueryURL;
4656 op->ors_filter = &f;
4657 attrs[ 0 ].an_desc = ad_cachedQueryURL;
4658 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
4659 op->ors_attrs = attrs;
4660 op->ors_attrsonly = 0;
4662 rc = op->o_bd->be_search( op, &rs );
4663 if ( rc == LDAP_SUCCESS && vals != NULL ) {
4666 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
4667 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
4668 cm->num_cached_queries++;
4672 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4675 /* count cached entries */
4676 f.f_choice = LDAP_FILTER_NOT;
4678 f2.f_choice = LDAP_FILTER_EQUALITY;
4680 f2.f_av_desc = slap_schema.si_ad_objectClass;
4681 BER_BVSTR( &f2.f_av_value, "glue" );
4682 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
4684 op->ors_slimit = SLAP_NO_LIMIT;
4685 op->ors_scope = LDAP_SCOPE_SUBTREE;
4686 op->ors_attrs = slap_anlist_no_attrs;
4688 rs_reinit( &rs, REP_RESULT );
4689 op->o_callback->sc_response = pcache_cachedquery_count_cb;
4690 op->o_callback->sc_private = &rs.sr_nentries;
4692 rc = op->o_bd->be_search( op, &rs );
4694 cm->cur_entries = rs.sr_nentries;
4708 slap_overinst *on = (slap_overinst *)be->bd_info;
4709 cache_manager *cm = on->on_bi.bi_private;
4710 query_manager* qm = cm->qm;
4711 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
4713 /* check attr sets */
4714 for ( i = 0; i < cm->numattrsets; i++) {
4715 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
4716 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
4717 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
4721 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
4725 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
4726 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
4731 if ( ncf || rf || nrf ) {
4732 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
4733 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
4734 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
4741 /* need to inherit something from the original database... */
4742 cm->db.be_def_limit = be->be_def_limit;
4743 cm->db.be_limits = be->be_limits;
4744 cm->db.be_acl = be->be_acl;
4745 cm->db.be_dfltaccess = be->be_dfltaccess;
4747 if ( SLAP_DBMONITORING( be ) ) {
4748 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
4751 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
4754 if ( !cm->defer_db_open ) {
4755 rc = pcache_db_open2( on, cr );
4758 #ifdef PCACHE_MONITOR
4759 if ( rc == LDAP_SUCCESS ) {
4760 rc = pcache_monitor_db_open( be );
4762 #endif /* PCACHE_MONITOR */
4768 pcache_free_qbase( void *v )
4774 tavl_free( qb->scopes[i], NULL );
4784 slap_overinst *on = (slap_overinst *)be->bd_info;
4785 cache_manager *cm = on->on_bi.bi_private;
4786 query_manager *qm = cm->qm;
4790 /* stop the thread ... */
4792 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4793 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4794 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4796 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4797 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4801 if ( cm->save_queries ) {
4803 BerVarray vals = NULL;
4806 Connection conn = { 0 };
4807 OperationBuffer opbuf;
4809 slap_callback cb = { 0 };
4811 SlapReply rs = { REP_RESULT };
4812 Modifications mod = {{ 0 }};
4814 thrctx = ldap_pvt_thread_pool_context();
4816 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4819 mod.sml_numvals = 0;
4820 if ( qm->templates != NULL ) {
4821 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4822 for ( qc = tm->query; qc; qc = qc->next ) {
4825 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4826 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4834 op->o_dn = cm->db.be_rootdn;
4835 op->o_ndn = cm->db.be_rootndn;
4837 op->o_tag = LDAP_REQ_MODIFY;
4838 op->o_protocol = LDAP_VERSION3;
4839 cb.sc_response = slap_null_cb;
4840 op->o_callback = &cb;
4841 op->o_time = slap_get_time();
4842 op->o_do_not_cache = 1;
4843 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4845 op->o_req_dn = op->o_bd->be_suffix[0];
4846 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4848 mod.sml_op = LDAP_MOD_REPLACE;
4850 mod.sml_desc = ad_cachedQueryURL;
4851 mod.sml_type = ad_cachedQueryURL->ad_cname;
4852 mod.sml_values = vals;
4853 mod.sml_nvalues = NULL;
4854 mod.sml_next = NULL;
4855 Debug( pcache_debug,
4856 "%sSETTING CACHED QUERY URLS\n",
4857 vals == NULL ? "RE" : "", 0, 0 );
4859 op->orm_modlist = &mod;
4861 op->o_bd->be_modify( op, &rs );
4863 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4866 /* cleanup stuff inherited from the original database... */
4867 cm->db.be_limits = NULL;
4868 cm->db.be_acl = NULL;
4870 if ( cm->db.bd_info->bi_db_close ) {
4871 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4874 #ifdef PCACHE_MONITOR
4875 if ( rc == LDAP_SUCCESS ) {
4876 rc = pcache_monitor_db_close( be );
4878 #endif /* PCACHE_MONITOR */
4889 slap_overinst *on = (slap_overinst *)be->bd_info;
4890 cache_manager *cm = on->on_bi.bi_private;
4891 query_manager *qm = cm->qm;
4895 if ( cm->db.be_private != NULL ) {
4896 backend_stopdown_one( &cm->db );
4899 while ( (tm = qm->templates) != NULL ) {
4900 CachedQuery *qc, *qn;
4901 qm->templates = tm->qmnext;
4902 for ( qc = tm->query; qc; qc = qn ) {
4906 avl_free( tm->qbase, pcache_free_qbase );
4907 free( tm->querystr.bv_val );
4908 free( tm->bindfattrs );
4909 free( tm->bindftemp.bv_val );
4910 free( tm->bindfilterstr.bv_val );
4911 free( tm->bindbase.bv_val );
4912 filter_free( tm->bindfilter );
4913 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4914 free( tm->t_attrs.attrs );
4918 for ( i = 0; i < cm->numattrsets; i++ ) {
4921 /* Account of LDAP_NO_ATTRS */
4922 if ( !qm->attr_sets[i].count ) continue;
4924 for ( j = 0; !BER_BVISNULL( &qm->attr_sets[i].attrs[j].an_name ); j++ ) {
4925 if ( qm->attr_sets[i].attrs[j].an_desc &&
4926 ( qm->attr_sets[i].attrs[j].an_desc->ad_flags &
4927 SLAP_DESC_TEMPORARY ) ) {
4928 slap_sl_mfuncs.bmf_free( qm->attr_sets[i].attrs[j].an_desc, NULL );
4931 free( qm->attr_sets[i].attrs );
4933 free( qm->attr_sets );
4934 qm->attr_sets = NULL;
4936 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4937 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4941 #ifdef PCACHE_MONITOR
4942 pcache_monitor_db_destroy( be );
4943 #endif /* PCACHE_MONITOR */
4948 #ifdef PCACHE_CONTROL_PRIVDB
4950 Control ::= SEQUENCE {
4951 controlType LDAPOID,
4952 criticality BOOLEAN DEFAULT FALSE,
4953 controlValue OCTET STRING OPTIONAL }
4955 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4957 * criticality must be TRUE; controlValue must be absent.
4965 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4966 rs->sr_text = "privateDB control specified multiple times";
4967 return LDAP_PROTOCOL_ERROR;
4970 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4971 rs->sr_text = "privateDB control value not absent";
4972 return LDAP_PROTOCOL_ERROR;
4975 if ( !ctrl->ldctl_iscritical ) {
4976 rs->sr_text = "privateDB control criticality required";
4977 return LDAP_PROTOCOL_ERROR;
4980 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4982 return LDAP_SUCCESS;
4985 static char *extops[] = {
4986 LDAP_EXOP_MODIFY_PASSWD,
4989 #endif /* PCACHE_CONTROL_PRIVDB */
4991 static struct berval pcache_exop_MODIFY_PASSWD = BER_BVC( LDAP_EXOP_MODIFY_PASSWD );
4992 #ifdef PCACHE_EXOP_QUERY_DELETE
4993 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4995 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4996 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4997 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
5000 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
5001 requestName [0] LDAPOID,
5002 requestValue [1] OCTET STRING OPTIONAL }
5004 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
5006 requestValue ::= SEQUENCE { CHOICE {
5008 entryDN [1] LDAPDN },
5009 queryID [2] OCTET STRING (SIZE(16))
5010 -- constrained to UUID }
5012 * Either baseDN or entryDN must be present, to allow database selection.
5014 * 1. if baseDN and queryID are present, then the query corresponding
5015 * to queryID is deleted;
5016 * 2. if baseDN is present and queryID is absent, then all queries
5018 * 3. if entryDN is present and queryID is absent, then all queries
5019 * corresponding to the queryID values present in entryDN are deleted;
5020 * 4. if entryDN and queryID are present, then all queries
5021 * corresponding to the queryID values present in entryDN are deleted,
5022 * but only if the value of queryID is contained in the entry;
5024 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
5025 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
5026 * or by removing the database files.
5028 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
5029 COMPONENTS OF LDAPResult,
5030 responseName [10] LDAPOID OPTIONAL,
5031 responseValue [11] OCTET STRING OPTIONAL }
5033 * responseName and responseValue must be absent.
5037 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
5038 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
5039 * - if ndn != NULL, it is set to the normalized DN in the request
5040 * corresponding to either the baseDN or the entryDN, according
5041 * to *tagp; memory is malloc'ed on the Operation's slab, and must
5042 * be freed by the caller.
5043 * - if uuid != NULL, it is set to point to the normalized UUID;
5044 * memory is malloc'ed on the Operation's slab, and must
5045 * be freed by the caller.
5048 pcache_parse_query_delete(
5052 struct berval *uuid,
5056 int rc = LDAP_SUCCESS;
5059 BerElementBuffer berbuf;
5060 BerElement *ber = (BerElement *)&berbuf;
5061 struct berval reqdata = BER_BVNULL;
5073 if ( in == NULL || in->bv_len == 0 ) {
5074 *text = "empty request data field in queryDelete exop";
5075 return LDAP_PROTOCOL_ERROR;
5078 ber_dupbv_x( &reqdata, in, ctx );
5080 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
5081 ber_init2( ber, &reqdata, 0 );
5083 tag = ber_scanf( ber, "{" /*}*/ );
5085 if ( tag == LBER_ERROR ) {
5086 Debug( LDAP_DEBUG_TRACE,
5087 "pcache_parse_query_delete: decoding error.\n",
5089 goto decoding_error;
5092 tag = ber_peek_tag( ber, &len );
5093 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
5094 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
5098 if ( ndn != NULL ) {
5101 tag = ber_scanf( ber, "m", &dn );
5102 if ( tag == LBER_ERROR ) {
5103 Debug( LDAP_DEBUG_TRACE,
5104 "pcache_parse_query_delete: DN parse failed.\n",
5106 goto decoding_error;
5109 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
5110 if ( rc != LDAP_SUCCESS ) {
5111 *text = "invalid DN in queryDelete exop request data";
5116 tag = ber_scanf( ber, "x" /* "m" */ );
5117 if ( tag == LBER_DEFAULT ) {
5118 goto decoding_error;
5122 tag = ber_peek_tag( ber, &len );
5125 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
5126 if ( uuid != NULL ) {
5128 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
5130 tag = ber_scanf( ber, "m", &bv );
5131 if ( tag == LBER_ERROR ) {
5132 Debug( LDAP_DEBUG_TRACE,
5133 "pcache_parse_query_delete: UUID parse failed.\n",
5135 goto decoding_error;
5138 if ( bv.bv_len != 16 ) {
5139 Debug( LDAP_DEBUG_TRACE,
5140 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5141 (unsigned long)bv.bv_len, 0, 0 );
5142 goto decoding_error;
5145 rc = lutil_uuidstr_from_normalized(
5146 bv.bv_val, bv.bv_len,
5147 uuidbuf, sizeof( uuidbuf ) );
5149 goto decoding_error;
5151 ber_str2bv( uuidbuf, rc, 1, uuid );
5155 tag = ber_skip_tag( ber, &len );
5156 if ( tag == LBER_DEFAULT ) {
5157 goto decoding_error;
5161 Debug( LDAP_DEBUG_TRACE,
5162 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5163 (unsigned long)len, 0, 0 );
5164 goto decoding_error;
5168 tag = ber_peek_tag( ber, &len );
5171 if ( tag != LBER_DEFAULT || len != 0 ) {
5173 Debug( LDAP_DEBUG_TRACE,
5174 "pcache_parse_query_delete: decoding error\n",
5176 rc = LDAP_PROTOCOL_ERROR;
5177 *text = "queryDelete data decoding error";
5180 if ( ndn && !BER_BVISNULL( ndn ) ) {
5181 slap_sl_free( ndn->bv_val, ctx );
5185 if ( uuid && !BER_BVISNULL( uuid ) ) {
5186 slap_sl_free( uuid->bv_val, ctx );
5191 if ( !BER_BVISNULL( &reqdata ) ) {
5192 ber_memfree_x( reqdata.bv_val, ctx );
5199 pcache_exop_query_delete(
5203 BackendDB *bd = op->o_bd;
5205 struct berval uuid = BER_BVNULL,
5207 char buf[ SLAP_TEXT_BUFLEN ];
5209 ber_tag_t tag = LBER_DEFAULT;
5211 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5215 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5216 &tag, &op->o_req_ndn, uuidp,
5217 &rs->sr_text, op->o_tmpmemctx );
5218 if ( rs->sr_err != LDAP_SUCCESS ) {
5222 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5223 assert( !BER_BVISNULL( &op->o_req_ndn ) );
5224 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
5226 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
5227 snprintf( &buf[ len ], sizeof( buf ) - len, " pcacheQueryId=\"%s\"", uuid.bv_val );
5230 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
5231 op->o_log_prefix, buf, 0 );
5233 op->o_req_dn = op->o_req_ndn;
5235 op->o_bd = select_backend( &op->o_req_ndn, 0 );
5236 if ( op->o_bd == NULL ) {
5237 send_ldap_error( op, rs, LDAP_NO_SUCH_OBJECT,
5238 "no global superior knowledge" );
5240 rs->sr_err = backend_check_restrictions( op, rs,
5241 (struct berval *)&pcache_exop_QUERY_DELETE );
5242 if ( rs->sr_err != LDAP_SUCCESS ) {
5246 if ( op->o_bd->be_extended == NULL ) {
5247 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
5248 "backend does not support extended operations" );
5252 op->o_bd->be_extended( op, rs );
5255 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
5256 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
5257 BER_BVZERO( &op->o_req_ndn );
5258 BER_BVZERO( &op->o_req_dn );
5261 if ( !BER_BVISNULL( &uuid ) ) {
5262 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5269 #endif /* PCACHE_EXOP_QUERY_DELETE */
5272 pcache_op_extended( Operation *op, SlapReply *rs )
5274 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5275 cache_manager *cm = on->on_bi.bi_private;
5277 #ifdef PCACHE_CONTROL_PRIVDB
5278 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
5279 return pcache_op_privdb( op, rs );
5281 #endif /* PCACHE_CONTROL_PRIVDB */
5283 #ifdef PCACHE_EXOP_QUERY_DELETE
5284 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
5285 struct berval uuid = BER_BVNULL;
5286 ber_tag_t tag = LBER_DEFAULT;
5288 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5289 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
5290 assert( rs->sr_err == LDAP_SUCCESS );
5292 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
5293 /* remove all queries related to the selected entry */
5294 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
5295 cm, &op->o_req_ndn, &uuid );
5297 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
5298 if ( !BER_BVISNULL( &uuid ) ) {
5299 /* remove the selected query */
5300 rs->sr_err = pcache_remove_query_from_cache( op,
5304 /* TODO: remove all queries */
5305 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
5306 rs->sr_text = "deletion of all queries not implemented";
5310 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5313 #endif /* PCACHE_EXOP_QUERY_DELETE */
5315 /* We only care if we're configured for Bind caching */
5316 if ( bvmatch( &op->ore_reqoid, &pcache_exop_MODIFY_PASSWD ) &&
5318 /* See if the local entry exists and has a password.
5319 * It's too much work to find the matching query, so
5320 * we just see if there's a hashed password to update.
5322 Operation op2 = *op;
5328 op2.o_dn = op->o_bd->be_rootdn;
5329 op2.o_ndn = op->o_bd->be_rootndn;
5330 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL,
5331 slap_schema.si_ad_userPassword, 0, &e );
5332 if ( rc == LDAP_SUCCESS && e ) {
5333 /* See if a recognized password is hashed here */
5334 Attribute *a = attr_find( e->e_attrs,
5335 slap_schema.si_ad_userPassword );
5336 if ( a && a->a_vals[0].bv_val[0] == '{' &&
5337 lutil_passwd_scheme( a->a_vals[0].bv_val )) {
5340 be_entry_release_r( &op2, e );
5344 rc = overlay_op_walk( op, rs, op_extended, on->on_info,
5346 if ( rc == LDAP_SUCCESS ) {
5347 req_pwdexop_s *qpw = &op->oq_pwdexop;
5349 /* We don't care if it succeeds or not */
5350 pc_setpw( &op2, &qpw->rs_new, cm );
5355 return SLAP_CB_CONTINUE;
5359 pcache_entry_release( Operation *op, Entry *e, int rw )
5361 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5362 cache_manager *cm = on->on_bi.bi_private;
5363 BackendDB *db = op->o_bd;
5367 rc = be_entry_release_rw( op, e, rw );
5372 #ifdef PCACHE_MONITOR
5375 pcache_monitor_update(
5381 cache_manager *cm = (cache_manager *) priv;
5382 query_manager *qm = cm->qm;
5385 BerVarray vals = NULL;
5387 attr_delete( &e->e_attrs, ad_cachedQueryURL );
5388 if ( ( SLAP_OPATTRS( rs->sr_attr_flags ) || ad_inlist( ad_cachedQueryURL, rs->sr_attrs ) )
5389 && qm->templates != NULL )
5393 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
5394 for ( qc = tm->query; qc; qc = qc->next ) {
5397 if ( query2url( op, qc, &bv, 1 ) == 0 ) {
5398 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
5404 if ( vals != NULL ) {
5405 attr_merge_normalize( e, ad_cachedQueryURL, vals, NULL );
5406 ber_bvarray_free_x( vals, op->o_tmpmemctx );
5412 char buf[ SLAP_TEXT_BUFLEN ];
5415 /* number of cached queries */
5416 a = attr_find( e->e_attrs, ad_numQueries );
5417 assert( a != NULL );
5420 bv.bv_len = snprintf( buf, sizeof( buf ), "%lu", cm->num_cached_queries );
5422 if ( a->a_nvals != a->a_vals ) {
5423 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5425 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5427 /* number of cached entries */
5428 a = attr_find( e->e_attrs, ad_numEntries );
5429 assert( a != NULL );
5432 bv.bv_len = snprintf( buf, sizeof( buf ), "%d", cm->cur_entries );
5434 if ( a->a_nvals != a->a_vals ) {
5435 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5437 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5440 return SLAP_CB_CONTINUE;
5444 pcache_monitor_free(
5448 struct berval values[ 2 ];
5449 Modification mod = { 0 };
5452 char textbuf[ SLAP_TEXT_BUFLEN ];
5456 /* NOTE: if slap_shutdown != 0, priv might have already been freed */
5459 /* Remove objectClass */
5460 mod.sm_op = LDAP_MOD_DELETE;
5461 mod.sm_desc = slap_schema.si_ad_objectClass;
5462 mod.sm_values = values;
5464 values[ 0 ] = oc_olmPCache->soc_cname;
5465 BER_BVZERO( &values[ 1 ] );
5467 rc = modify_delete_values( e, &mod, 1, &text,
5468 textbuf, sizeof( textbuf ) );
5469 /* don't care too much about return code... */
5472 mod.sm_values = NULL;
5473 mod.sm_desc = ad_cachedQueryURL;
5475 rc = modify_delete_values( e, &mod, 1, &text,
5476 textbuf, sizeof( textbuf ) );
5477 /* don't care too much about return code... */
5480 mod.sm_values = NULL;
5481 mod.sm_desc = ad_numQueries;
5483 rc = modify_delete_values( e, &mod, 1, &text,
5484 textbuf, sizeof( textbuf ) );
5485 /* don't care too much about return code... */
5488 mod.sm_values = NULL;
5489 mod.sm_desc = ad_numEntries;
5491 rc = modify_delete_values( e, &mod, 1, &text,
5492 textbuf, sizeof( textbuf ) );
5493 /* don't care too much about return code... */
5495 return SLAP_CB_CONTINUE;
5499 * call from within pcache_initialize()
5502 pcache_monitor_initialize( void )
5504 static int pcache_monitor_initialized = 0;
5506 if ( backend_info( "monitor" ) == NULL ) {
5510 if ( pcache_monitor_initialized++ ) {
5518 pcache_monitor_db_init( BackendDB *be )
5520 if ( pcache_monitor_initialize() == LDAP_SUCCESS ) {
5521 SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_MONITORING;
5528 pcache_monitor_db_open( BackendDB *be )
5530 slap_overinst *on = (slap_overinst *)be->bd_info;
5531 cache_manager *cm = on->on_bi.bi_private;
5532 Attribute *a, *next;
5533 monitor_callback_t *cb = NULL;
5536 monitor_extra_t *mbe;
5538 if ( !SLAP_DBMONITORING( be ) ) {
5542 mi = backend_info( "monitor" );
5543 if ( !mi || !mi->bi_extra ) {
5544 SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
5549 /* don't bother if monitor is not configured */
5550 if ( !mbe->is_configured() ) {
5551 static int warning = 0;
5553 if ( warning++ == 0 ) {
5554 Debug( LDAP_DEBUG_ANY, "pcache_monitor_db_open: "
5555 "monitoring disabled; "
5556 "configure monitor database to enable\n",
5563 /* alloc as many as required (plus 1 for objectClass) */
5564 a = attrs_alloc( 1 + 2 );
5570 a->a_desc = slap_schema.si_ad_objectClass;
5571 attr_valadd( a, &oc_olmPCache->soc_cname, NULL, 1 );
5575 struct berval bv = BER_BVC( "0" );
5577 next->a_desc = ad_numQueries;
5578 attr_valadd( next, &bv, NULL, 1 );
5579 next = next->a_next;
5581 next->a_desc = ad_numEntries;
5582 attr_valadd( next, &bv, NULL, 1 );
5583 next = next->a_next;
5586 cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
5587 cb->mc_update = pcache_monitor_update;
5588 cb->mc_free = pcache_monitor_free;
5589 cb->mc_private = (void *)cm;
5591 /* make sure the database is registered; then add monitor attributes */
5592 BER_BVZERO( &cm->monitor_ndn );
5593 rc = mbe->register_overlay( be, on, &cm->monitor_ndn );
5595 rc = mbe->register_entry_attrs( &cm->monitor_ndn, a, cb,
5612 /* store for cleanup */
5613 cm->monitor_cb = (void *)cb;
5615 /* we don't need to keep track of the attributes, because
5616 * bdb_monitor_free() takes care of everything */
5625 pcache_monitor_db_close( BackendDB *be )
5627 slap_overinst *on = (slap_overinst *)be->bd_info;
5628 cache_manager *cm = on->on_bi.bi_private;
5630 if ( cm->monitor_cb != NULL ) {
5631 BackendInfo *mi = backend_info( "monitor" );
5632 monitor_extra_t *mbe;
5634 if ( mi && &mi->bi_extra ) {
5636 mbe->unregister_entry_callback( &cm->monitor_ndn,
5637 (monitor_callback_t *)cm->monitor_cb,
5646 pcache_monitor_db_destroy( BackendDB *be )
5651 #endif /* PCACHE_MONITOR */
5653 static slap_overinst pcache;
5655 static char *obsolete_names[] = {
5660 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5662 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
5667 struct berval debugbv = BER_BVC("pcache");
5671 code = slap_loglevel_get( &debugbv, &pcache_debug );
5676 #ifdef PCACHE_CONTROL_PRIVDB
5677 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
5678 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
5679 parse_privdb_ctrl, &privDB_cid );
5680 if ( code != LDAP_SUCCESS ) {
5681 Debug( LDAP_DEBUG_ANY,
5682 "pcache_initialize: failed to register control %s (%d)\n",
5683 PCACHE_CONTROL_PRIVDB, code, 0 );
5686 #endif /* PCACHE_CONTROL_PRIVDB */
5688 #ifdef PCACHE_EXOP_QUERY_DELETE
5689 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
5690 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
5692 if ( code != LDAP_SUCCESS ) {
5693 Debug( LDAP_DEBUG_ANY,
5694 "pcache_initialize: unable to register queryDelete exop: %d.\n",
5698 #endif /* PCACHE_EXOP_QUERY_DELETE */
5700 argv[ 0 ] = "back-bdb/back-hdb monitor";
5705 for ( i = 0; s_oid[ i ].name; i++ ) {
5707 argv[ 1 ] = s_oid[ i ].name;
5708 argv[ 2 ] = s_oid[ i ].oid;
5710 if ( parse_oidm( &c, 0, NULL ) != 0 ) {
5711 Debug( LDAP_DEBUG_ANY, "pcache_initialize: "
5712 "unable to add objectIdentifier \"%s=%s\"\n",
5713 s_oid[ i ].name, s_oid[ i ].oid, 0 );
5718 for ( i = 0; s_ad[i].desc != NULL; i++ ) {
5719 code = register_at( s_ad[i].desc, s_ad[i].adp, 0 );
5721 Debug( LDAP_DEBUG_ANY,
5722 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
5725 (*s_ad[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
5728 for ( i = 0; s_oc[i].desc != NULL; i++ ) {
5729 code = register_oc( s_oc[i].desc, s_oc[i].ocp, 0 );
5731 Debug( LDAP_DEBUG_ANY,
5732 "pcache_initialize: register_oc #%d failed\n", i, 0, 0 );
5735 (*s_oc[i].ocp)->soc_flags |= SLAP_OC_HIDE;
5738 pcache.on_bi.bi_type = "pcache";
5739 pcache.on_bi.bi_obsolete_names = obsolete_names;
5740 pcache.on_bi.bi_db_init = pcache_db_init;
5741 pcache.on_bi.bi_db_config = pcache_db_config;
5742 pcache.on_bi.bi_db_open = pcache_db_open;
5743 pcache.on_bi.bi_db_close = pcache_db_close;
5744 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
5746 pcache.on_bi.bi_op_search = pcache_op_search;
5747 pcache.on_bi.bi_op_bind = pcache_op_bind;
5748 #ifdef PCACHE_CONTROL_PRIVDB
5749 pcache.on_bi.bi_op_compare = pcache_op_privdb;
5750 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
5751 pcache.on_bi.bi_op_modify = pcache_op_privdb;
5752 pcache.on_bi.bi_op_add = pcache_op_privdb;
5753 pcache.on_bi.bi_op_delete = pcache_op_privdb;
5754 #endif /* PCACHE_CONTROL_PRIVDB */
5755 pcache.on_bi.bi_extended = pcache_op_extended;
5757 pcache.on_bi.bi_entry_release_rw = pcache_entry_release;
5758 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
5760 pcache.on_bi.bi_cf_ocs = pcocs;
5762 code = config_register_schema( pccfg, pcocs );
5763 if ( code ) return code;
5765 return overlay_register( &pcache );
5768 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5769 int init_module(int argc, char *argv[]) {
5770 return pcache_initialize();
5774 #endif /* defined(SLAPD_OVER_PROXYCACHE) */