2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2009 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003 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>
40 * Control that allows to access the private DB
41 * instead of the public one
43 #define PCACHE_CONTROL_PRIVDB "1.3.6.1.4.1.4203.666.11.9.5.1"
46 * Extended Operation that allows to remove a query from the cache
48 #define PCACHE_EXOP_QUERY_DELETE "1.3.6.1.4.1.4203.666.11.9.6.1"
51 /* query cache structs */
54 typedef struct Query_s {
55 Filter* filter; /* Search Filter */
56 struct berval base; /* Search Base */
57 int scope; /* Search scope */
60 struct query_template_s;
62 typedef struct Qbase_s {
63 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
68 /* struct representing a cached query */
69 typedef struct cached_query_s {
74 struct berval q_uuid; /* query identifier */
76 struct query_template_s *qtemp; /* template of the query */
77 time_t expiry_time; /* time till the query is considered invalid */
78 time_t refresh_time; /* time till the query is refreshed */
79 unsigned long answerable_cnt; /* how many times it was answerable */
80 int refcnt; /* references since last refresh */
81 ldap_pvt_thread_mutex_t answerable_cnt_mutex;
82 struct cached_query_s *next; /* next query in the template */
83 struct cached_query_s *prev; /* previous query in the template */
84 struct cached_query_s *lru_up; /* previous query in the LRU list */
85 struct cached_query_s *lru_down; /* next query in the LRU list */
86 ldap_pvt_thread_rdwr_t rwlock;
92 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>,x-refresh=<refresh>
94 * <base> ::= CachedQuery.qbase->base
95 * <scope> ::= CachedQuery.scope
96 * <filter> ::= filter2bv(CachedQuery.filter)
97 * <uuid> ::= CachedQuery.q_uuid
98 * <attrset> ::= CachedQuery.qtemp->attr_set_index
99 * <expiry> ::= CachedQuery.expiry_time
100 * <refresh> ::= CachedQuery.refresh_time
102 * quick hack: parse URI, call add_query() and then fix
103 * CachedQuery.expiry_time and CachedQuery.q_uuid
107 * Represents a set of projected attributes.
111 struct query_template_s *templates;
112 AttributeName* attrs; /* specifies the set */
114 #define PC_CONFIGURED (0x1)
115 #define PC_REFERENCED (0x2)
116 #define PC_GOT_OC (0x4)
117 int count; /* number of attributes */
120 /* struct representing a query template
121 * e.g. template string = &(cn=)(mail=)
123 typedef struct query_template_s {
124 struct query_template_s *qtnext;
125 struct query_template_s *qmnext;
128 CachedQuery* query; /* most recent query cached for the template */
129 CachedQuery* query_last; /* oldest query cached for the template */
130 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
131 struct berval querystr; /* Filter string corresponding to the QT */
133 int attr_set_index; /* determines the projected attributes */
134 int no_of_queries; /* Total number of queries in the template */
135 time_t ttl; /* TTL for the queries of this template */
136 time_t negttl; /* TTL for negative results */
137 time_t limitttl; /* TTL for sizelimit exceeding results */
138 time_t ttr; /* time to refresh */
139 struct attr_set t_attrs; /* filter attrs + attr_set */
147 } pc_caching_reason_t;
149 static const char *pc_caching_reason_str[] = {
158 struct query_manager_s;
160 /* prototypes for functions for 1) query containment
161 * 2) query addition, 3) cache replacement
163 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
164 Query*, QueryTemplate*);
165 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
166 Query*, QueryTemplate*, pc_caching_reason_t, int wlock);
167 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
169 /* LDAP query cache */
170 typedef struct query_manager_s {
171 struct attr_set* attr_sets; /* possible sets of projected attributes */
172 QueryTemplate* templates; /* cacheable templates */
174 CachedQuery* lru_top; /* top and bottom of LRU list */
175 CachedQuery* lru_bottom;
177 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
179 /* Query cache methods */
180 QCfunc *qcfunc; /* Query containment*/
181 CRfunc *crfunc; /* cache replacement */
182 AddQueryfunc *addfunc; /* add query */
185 /* LDAP query cache manager */
186 typedef struct cache_manager_s {
187 BackendDB db; /* underlying database */
188 unsigned long num_cached_queries; /* total number of cached queries */
189 unsigned long max_queries; /* upper bound on # of cached queries */
190 int save_queries; /* save cached queries across restarts */
191 int check_cacheability; /* check whether a query is cacheable */
192 int numattrsets; /* number of attribute sets */
193 int cur_entries; /* current number of entries cached */
194 int max_entries; /* max number of entries cached */
195 int num_entries_limit; /* max # of entries in a cacheable query */
197 char response_cb; /* install the response callback
198 * at the tail of the callback list */
199 #define PCACHE_RESPONSE_CB_HEAD 0
200 #define PCACHE_RESPONSE_CB_TAIL 1
201 char defer_db_open; /* defer open for online add */
203 time_t cc_period; /* interval between successive consistency checks (sec) */
204 #define PCACHE_CC_PAUSED 1
205 #define PCACHE_CC_OFFLINE 2
209 ldap_pvt_thread_mutex_t cache_mutex;
211 query_manager* qm; /* query cache managed by the cache manager */
214 static int pcache_debug;
216 #ifdef PCACHE_CONTROL_PRIVDB
217 static int privDB_cid;
218 #endif /* PCACHE_CONTROL_PRIVDB */
220 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
223 AttributeDescription **adp;
225 { "( 1.3.6.1.4.1.4203.666.11.9.1.1 "
227 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
228 "EQUALITY octetStringMatch "
229 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
230 "NO-USER-MODIFICATION "
231 "USAGE directoryOperation )",
233 { "( 1.3.6.1.4.1.4203.666.11.9.1.2 "
234 "NAME 'cachedQueryURL' "
235 "DESC 'URI describing a cached query' "
236 "EQUALITY caseExactMatch "
237 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
238 "NO-USER-MODIFICATION "
239 "USAGE directoryOperation )",
240 &ad_cachedQueryURL },
249 AttributeName** filter_attrs,
251 int* filter_got_oc );
258 QueryTemplate *templ,
259 pc_caching_reason_t why,
266 struct berval *query_uuid );
269 * Turn a cached query into its URL representation
272 query2url( Operation *op, CachedQuery *q, struct berval *urlbv, int dolock )
274 struct berval bv_scope,
276 char attrset_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
277 expiry_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
278 refresh_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
279 answerable_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
281 ber_len_t attrset_len,
287 ldap_pvt_thread_rdwr_rlock( &q->rwlock );
290 ldap_pvt_scope2bv( q->scope, &bv_scope );
291 filter2bv_x( op, q->filter, &bv_filter );
292 attrset_len = sprintf( attrset_buf,
293 "%lu", (unsigned long)q->qtemp->attr_set_index );
294 expiry_len = sprintf( expiry_buf,
295 "%lu", (unsigned long)q->expiry_time );
296 answerable_len = snprintf( answerable_buf, sizeof( answerable_buf ),
297 "%lu", q->answerable_cnt );
298 if ( q->refresh_time )
299 refresh_len = sprintf( refresh_buf,
300 "%lu", (unsigned long)q->refresh_time );
304 urlbv->bv_len = STRLENOF( "ldap:///" )
305 + q->qbase->base.bv_len
310 + STRLENOF( "?x-uuid=" )
312 + STRLENOF( ",x-attrset=" )
314 + STRLENOF( ",x-expiry=" )
316 + STRLENOF( ",x-answerable=" )
319 urlbv->bv_len += STRLENOF( ",x-refresh=" )
322 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
323 ptr = lutil_strcopy( ptr, "ldap:///" );
324 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
325 ptr = lutil_strcopy( ptr, "??" );
326 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
327 ptr = lutil_strcopy( ptr, "?" );
328 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
329 ptr = lutil_strcopy( ptr, "?x-uuid=" );
330 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
331 ptr = lutil_strcopy( ptr, ",x-attrset=" );
332 ptr = lutil_strcopy( ptr, attrset_buf );
333 ptr = lutil_strcopy( ptr, ",x-expiry=" );
334 ptr = lutil_strcopy( ptr, expiry_buf );
335 ptr = lutil_strcopy( ptr, ",x-answerable=" );
336 ptr = lutil_strcopy( ptr, answerable_buf );
338 ptr = lutil_strcopy( ptr, ",x-refresh=" );
339 ptr = lutil_strcopy( ptr, refresh_buf );
342 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
345 ldap_pvt_thread_rdwr_runlock( &q->rwlock );
352 * Turn an URL representing a formerly cached query into a cached query,
353 * and try to cache it
364 LDAPURLDesc *lud = NULL;
366 tempstr = BER_BVNULL,
371 unsigned long answerable_cnt;
374 #define GOT_UUID 0x1U
375 #define GOT_ATTRSET 0x2U
376 #define GOT_EXPIRY 0x4U
377 #define GOT_ANSWERABLE 0x8U
378 #define GOT_REFRESH 0x10U
379 #define GOT_ALL (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
382 rc = ldap_url_parse( url, &lud );
383 if ( rc != LDAP_URL_SUCCESS ) {
387 /* non-allowed fields */
388 if ( lud->lud_host != NULL ) {
393 if ( lud->lud_attrs != NULL ) {
399 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
404 /* required fields */
405 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
410 switch ( lud->lud_scope ) {
411 case LDAP_SCOPE_BASE:
412 case LDAP_SCOPE_ONELEVEL:
413 case LDAP_SCOPE_SUBTREE:
414 case LDAP_SCOPE_SUBORDINATE:
422 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
427 if ( lud->lud_exts == NULL ) {
432 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
433 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
434 struct berval tmpUUID;
435 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
437 if ( got & GOT_UUID ) {
442 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
443 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
444 if ( rc != LDAP_SUCCESS ) {
449 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
450 if ( got & GOT_ATTRSET ) {
455 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
461 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
464 if ( got & GOT_EXPIRY ) {
469 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
473 expiry_time = (time_t)l;
476 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
477 if ( got & GOT_ANSWERABLE ) {
482 rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
486 got |= GOT_ANSWERABLE;
488 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
491 if ( got & GOT_REFRESH ) {
496 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
500 refresh_time = (time_t)l;
509 if ( got != GOT_ALL ) {
514 if ( !(got & GOT_REFRESH ))
517 /* ignore expired queries */
518 if ( expiry_time <= slap_get_time()) {
520 SlapReply rs2 = { 0 };
522 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
524 (void)remove_query_data( &op2, &rs2, &uuid );
529 ber_str2bv( lud->lud_dn, 0, 0, &base );
530 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
531 if ( rc != LDAP_SUCCESS ) {
534 query.scope = lud->lud_scope;
535 query.filter = str2filter( lud->lud_filter );
537 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
539 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
540 ch_free( tempstr.bv_val );
545 /* check for query containment */
546 qt = qm->attr_sets[attrset].templates;
547 for ( ; qt; qt = qt->qtnext ) {
548 /* find if template i can potentially answer tempstr */
549 if ( bvmatch( &qt->querystr, &tempstr ) ) {
559 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
561 cq->expiry_time = expiry_time;
562 cq->refresh_time = refresh_time;
564 cq->answerable_cnt = answerable_cnt;
567 /* it's now into cq->filter */
577 if ( query.filter != NULL ) filter_free( query.filter );
578 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
579 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
580 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
581 if ( lud != NULL ) ldap_free_urldesc( lud );
586 /* Return 1 for an added entry, else 0 */
591 struct berval* query_uuid )
594 Modifications* modlist = NULL;
595 const char* text = NULL;
597 char textbuf[SLAP_TEXT_BUFLEN];
598 size_t textlen = sizeof(textbuf);
600 SlapReply sreply = {REP_RESULT};
602 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
607 /* add queryId attribute */
608 attr_merge_one( e, ad_queryId, query_uuid, NULL );
610 /* append the attribute list from the fetched entry */
611 e->e_attrs->a_next = attr;
613 op->o_tag = LDAP_REQ_ADD;
614 op->o_protocol = LDAP_VERSION3;
615 op->o_callback = &cb;
616 op->o_time = slap_get_time();
617 op->o_do_not_cache = 1;
620 op->o_req_dn = e->e_name;
621 op->o_req_ndn = e->e_nname;
622 rc = op->o_bd->be_add( op, &sreply );
624 if ( rc != LDAP_SUCCESS ) {
625 if ( rc == LDAP_ALREADY_EXISTS ) {
626 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
627 modlist->sml_op = LDAP_MOD_ADD;
628 op->o_tag = LDAP_REQ_MODIFY;
629 op->orm_modlist = modlist;
630 op->o_bd->be_modify( op, &sreply );
631 slap_mods_free( modlist, 1 );
632 } else if ( rc == LDAP_REFERRAL ||
633 rc == LDAP_NO_SUCH_OBJECT ) {
634 syncrepl_add_glue( op, e );
643 if ( op->ora_e == e )
644 be_entry_release_w( op, e );
651 /* Length-ordered sort on normalized DNs */
652 static int pcache_dn_cmp( const void *v1, const void *v2 )
654 const Qbase *q1 = v1, *q2 = v2;
656 int rc = q1->base.bv_len - q2->base.bv_len;
658 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
662 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
665 dif = bv1->bv_len - bv2->bv_len;
667 if ( dif > 0 ) len -= dif;
668 len = memcmp( bv1->bv_val, bv2->bv_val, len );
674 /* compare the current value in each filter */
675 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
677 int rc, weight1, weight2;
679 switch( f1->f_choice ) {
680 case LDAP_FILTER_PRESENT:
683 case LDAP_FILTER_EQUALITY:
691 switch( f2->f_choice ) {
692 case LDAP_FILTER_PRESENT:
695 case LDAP_FILTER_EQUALITY:
703 rc = weight1 - weight2;
709 rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
712 if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
714 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
715 if ( !BER_BVISNULL( &f2->f_sub_initial )) {
716 rc = lex_bvcmp( &f1->f_sub_initial,
717 &f2->f_sub_initial );
721 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
725 if ( f1->f_sub_any ) {
726 if ( f2->f_sub_any ) {
727 rc = lex_bvcmp( f1->f_sub_any,
732 } else if ( f2->f_sub_any ) {
736 if ( !BER_BVISNULL( &f1->f_sub_final )) {
737 if ( !BER_BVISNULL( &f2->f_sub_final )) {
738 rc = lex_bvcmp( &f1->f_sub_final,
743 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
747 rc = lex_bvcmp( &f1->f_mr_value,
761 while ( f1->f_choice == LDAP_FILTER_AND || f1->f_choice == LDAP_FILTER_OR )
763 while ( f2->f_choice == LDAP_FILTER_AND || f2->f_choice == LDAP_FILTER_OR )
765 rc = pcache_filter_cmp( f1, f2 );
773 /* compare filters in each query */
774 static int pcache_query_cmp( const void *v1, const void *v2 )
776 const CachedQuery *q1 = v1, *q2 =v2;
777 return pcache_filter_cmp( q1->first, q2->first );
780 /* add query on top of LRU list */
782 add_query_on_top (query_manager* qm, CachedQuery* qc)
784 CachedQuery* top = qm->lru_top;
795 Debug( pcache_debug, "Base of added query = %s\n",
796 qc->qbase->base.bv_val, 0, 0 );
799 /* remove_query from LRU list */
802 remove_query (query_manager* qm, CachedQuery* qc)
825 qc->lru_up = qc->lru_down = NULL;
828 /* find and remove string2 from string1
829 * from start if position = 1,
830 * from end if position = 3,
831 * from anywhere if position = 2
832 * string1 is overwritten if position = 2.
836 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
847 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
848 ber2->bv_val, ber2->bv_len )) {
850 ber1->bv_val += ber2->bv_len;
851 ber1->bv_len -= ber2->bv_len;
856 ber1->bv_val[ber1->bv_len] = '\0';
857 temp = strstr( ber1->bv_val, ber2->bv_val );
859 strcpy( temp, temp+ber2->bv_len );
860 ber1->bv_len -= ber2->bv_len;
866 if ( ber1->bv_len >= ber2->bv_len &&
867 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
870 ber1->bv_len -= ber2->bv_len;
878 static struct berval*
879 merge_init_final(Operation *op, struct berval* init, struct berval* any,
880 struct berval* final)
882 struct berval* merged, *temp;
883 int i, any_count, count;
885 for (any_count=0; any && any[any_count].bv_val; any_count++)
895 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
900 ber_dupbv_x( temp, init, op->o_tmpmemctx );
904 for (i=0; i<any_count; i++) {
905 ber_dupbv_x( temp, any, op->o_tmpmemctx );
910 ber_dupbv_x( temp, final, op->o_tmpmemctx );
917 /* Each element in stored must be found in incoming. Incoming is overwritten.
920 strings_containment(struct berval* stored, struct berval* incoming)
922 struct berval* element;
926 for ( element=stored; element->bv_val != NULL; element++ ) {
927 for (j = k; incoming[j].bv_val != NULL; j++) {
928 if (find_and_remove(&(incoming[j]), element, 2)) {
945 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
949 struct berval init_incoming;
950 struct berval final_incoming;
951 struct berval *remaining_incoming = NULL;
953 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
954 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
957 init_incoming = incoming->f_sub_initial;
958 final_incoming = incoming->f_sub_final;
960 if (find_and_remove(&init_incoming,
961 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
962 &(stored->f_sub_final), 3))
964 if (stored->f_sub_any == NULL) {
968 remaining_incoming = merge_init_final(op, &init_incoming,
969 incoming->f_sub_any, &final_incoming);
970 rc = strings_containment(stored->f_sub_any, remaining_incoming);
971 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
978 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
980 struct berval incoming_val[2];
983 incoming_val[1] = incoming->f_av_value;
985 if (find_and_remove(incoming_val+1,
986 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
987 &(stored->f_sub_final), 3)) {
988 if (stored->f_sub_any == NULL){
992 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
993 BER_BVZERO( incoming_val+1 );
994 rc = strings_containment(stored->f_sub_any, incoming_val);
995 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1002 filter_first( Filter *f )
1004 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1010 static CachedQuery *
1011 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
1015 MatchingRule* mrule = NULL;
1016 int res=0, eqpass= 0;
1019 CachedQuery cq, *qc;
1024 /* substring matches sort to the end, and we just have to
1025 * walk the entire list.
1027 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1028 ptr = tavl_end( root, 1 );
1029 dir = TAVL_DIR_LEFT;
1031 ptr = tavl_find3( root, &cq, pcache_query_cmp, &ret );
1032 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1041 /* an incoming substr query can only be satisfied by a cached
1044 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1045 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1048 /* an incoming eq query can be satisfied by a cached eq or substr
1051 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1052 if ( eqpass == 0 ) {
1053 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1054 nextpass: eqpass = 1;
1055 ptr = tavl_end( root, 1 );
1056 dir = TAVL_DIR_LEFT;
1060 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1066 switch (fs->f_choice) {
1067 case LDAP_FILTER_EQUALITY:
1068 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1069 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1073 case LDAP_FILTER_GE:
1074 case LDAP_FILTER_LE:
1075 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1082 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1083 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1084 &(fi->f_ava->aa_value),
1085 &(fs->f_ava->aa_value), &text);
1086 if (rc != LDAP_SUCCESS) {
1089 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1092 switch (fs->f_choice) {
1093 case LDAP_FILTER_OR:
1094 case LDAP_FILTER_AND:
1099 case LDAP_FILTER_SUBSTRINGS:
1100 /* check if the equality query can be
1101 * answered with cached substring query */
1102 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1103 && substr_containment_equality( op,
1106 /* check if the substring query can be
1107 * answered with cached substring query */
1108 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1109 ) && substr_containment_substr( op,
1115 case LDAP_FILTER_PRESENT:
1120 case LDAP_FILTER_EQUALITY:
1126 case LDAP_FILTER_GE:
1127 if (mrule && ret >= 0)
1132 case LDAP_FILTER_LE:
1133 if (mrule && ret <= 0)
1138 case LDAP_FILTER_NOT:
1144 } while((res) && (fi != NULL) && (fs != NULL));
1148 ptr = tavl_next( ptr, dir );
1153 /* check whether query is contained in any of
1154 * the cached queries in template
1156 static CachedQuery *
1157 query_containment(Operation *op, query_manager *qm,
1159 QueryTemplate *templa)
1162 int depth = 0, tscope;
1163 Qbase qbase, *qbptr = NULL;
1166 if (query->filter != NULL) {
1169 Debug( pcache_debug, "Lock QC index = %p\n",
1170 (void *) templa, 0, 0 );
1171 qbase.base = query->base;
1173 first = filter_first( query->filter );
1175 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1178 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1180 tscope = query->scope;
1181 /* Find a matching scope:
1182 * match at depth 0 OK
1185 * subord at depth > 0 OK
1186 * subtree at any depth OK
1188 * subtree or subord at any depth OK
1190 * subtree or subord at any depth OK
1192 * subord at depth > 0 OK
1193 * subtree at any depth OK
1195 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1196 switch ( query->scope ) {
1197 case LDAP_SCOPE_BASE:
1198 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1199 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1200 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1202 case LDAP_SCOPE_ONE:
1203 if ( tscope == LDAP_SCOPE_BASE )
1204 tscope = LDAP_SCOPE_ONE;
1205 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1206 if ( !depth ) break;
1207 if ( tscope < LDAP_SCOPE_SUBTREE )
1208 tscope = LDAP_SCOPE_SUBTREE;
1210 case LDAP_SCOPE_SUBTREE:
1211 if ( tscope < LDAP_SCOPE_SUBTREE )
1212 tscope = LDAP_SCOPE_SUBTREE;
1213 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1215 case LDAP_SCOPE_CHILDREN:
1216 if ( tscope < LDAP_SCOPE_SUBTREE )
1217 tscope = LDAP_SCOPE_SUBTREE;
1220 if ( !qbptr->scopes[tscope] ) continue;
1223 qc = find_filter( op, qbptr->scopes[tscope],
1224 query->filter, first );
1226 if ( qc->q_sizelimit ) {
1227 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1230 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1231 if (qm->lru_top != qc) {
1232 remove_query(qm, qc);
1233 add_query_on_top(qm, qc);
1235 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1240 if ( be_issuffix( op->o_bd, &qbase.base ))
1243 dnParent( &qbase.base, &pdn );
1248 Debug( pcache_debug,
1249 "Not answerable: Unlock QC index=%p\n",
1250 (void *) templa, 0, 0 );
1251 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1257 free_query (CachedQuery* qc)
1259 free(qc->q_uuid.bv_val);
1260 filter_free(qc->filter);
1261 ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1262 ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1263 memset(qc, 0, sizeof(*qc));
1268 /* Add query to query cache, the returned Query is locked for writing */
1269 static CachedQuery *
1274 QueryTemplate *templ,
1275 pc_caching_reason_t why,
1278 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1282 time_t ttl = 0, ttr = 0;
1285 new_cached_query->qtemp = templ;
1286 BER_BVZERO( &new_cached_query->q_uuid );
1287 new_cached_query->q_sizelimit = 0;
1289 now = slap_get_time();
1294 ttr = now + templ->ttr;
1298 ttl = templ->negttl;
1302 ttl = templ->limitttl;
1309 new_cached_query->expiry_time = now + ttl;
1310 new_cached_query->refresh_time = ttr;
1312 new_cached_query->answerable_cnt = 0;
1313 new_cached_query->refcnt = 1;
1314 ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1316 new_cached_query->lru_up = NULL;
1317 new_cached_query->lru_down = NULL;
1318 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1319 (long) new_cached_query->expiry_time,
1320 pc_caching_reason_str[ why ], 0 );
1322 new_cached_query->scope = query->scope;
1323 new_cached_query->filter = query->filter;
1324 new_cached_query->first = first = filter_first( query->filter );
1326 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1328 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1330 qb.base = query->base;
1332 /* Adding a query */
1333 Debug( pcache_debug, "Lock AQ index = %p\n",
1334 (void *) templ, 0, 0 );
1335 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1336 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1338 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1339 qbase->base.bv_len = qb.base.bv_len;
1340 qbase->base.bv_val = (char *)(qbase+1);
1341 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1342 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1343 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1345 new_cached_query->next = templ->query;
1346 new_cached_query->prev = NULL;
1347 new_cached_query->qbase = qbase;
1348 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1349 pcache_query_cmp, avl_dup_error );
1352 if (templ->query == NULL)
1353 templ->query_last = new_cached_query;
1355 templ->query->prev = new_cached_query;
1356 templ->query = new_cached_query;
1357 templ->no_of_queries++;
1359 ch_free( new_cached_query );
1360 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1361 query->filter, first );
1362 filter_free( query->filter );
1363 query->filter = NULL;
1365 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1366 (void *) templ, templ->no_of_queries, 0 );
1368 Debug( pcache_debug, "Unlock AQ index = %p \n",
1369 (void *) templ, 0, 0 );
1370 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1372 /* Adding on top of LRU list */
1374 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1375 add_query_on_top(qm, new_cached_query);
1376 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1378 return rc == 0 ? new_cached_query : NULL;
1382 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1384 if (!qc->prev && !qc->next) {
1385 template->query_last = template->query = NULL;
1386 } else if (qc->prev == NULL) {
1387 qc->next->prev = NULL;
1388 template->query = qc->next;
1389 } else if (qc->next == NULL) {
1390 qc->prev->next = NULL;
1391 template->query_last = qc->prev;
1393 qc->next->prev = qc->prev;
1394 qc->prev->next = qc->next;
1396 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1397 qc->qbase->queries--;
1398 if ( qc->qbase->queries == 0 ) {
1399 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1400 ch_free( qc->qbase );
1404 template->no_of_queries--;
1407 /* remove bottom query of LRU list from the query cache */
1409 * NOTE: slight change in functionality.
1411 * - if result->bv_val is NULL, the query at the bottom of the LRU
1413 * - otherwise, the query whose UUID is *result is removed
1414 * - if not found, result->bv_val is zeroed
1417 cache_replacement(query_manager* qm, struct berval *result)
1419 CachedQuery* bottom;
1420 QueryTemplate *temp;
1422 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1423 if ( BER_BVISNULL( result ) ) {
1424 bottom = qm->lru_bottom;
1427 Debug ( pcache_debug,
1428 "Cache replacement invoked without "
1429 "any query in LRU list\n", 0, 0, 0 );
1430 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1435 for ( bottom = qm->lru_bottom;
1437 bottom = bottom->lru_up )
1439 if ( bvmatch( result, &bottom->q_uuid ) ) {
1445 Debug ( pcache_debug,
1446 "Could not find query with uuid=\"%s\""
1447 "in LRU list\n", result->bv_val, 0, 0 );
1448 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1449 BER_BVZERO( result );
1454 temp = bottom->qtemp;
1455 remove_query(qm, bottom);
1456 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1458 *result = bottom->q_uuid;
1459 BER_BVZERO( &bottom->q_uuid );
1461 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1462 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1463 remove_from_template(bottom, temp);
1464 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1465 (void *) temp, temp->no_of_queries, 0 );
1466 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1467 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1472 struct query_info *next;
1484 struct query_info *qi;
1487 if ( rs->sr_type != REP_SEARCH ) return 0;
1489 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1490 if ( attr == NULL ) return 0;
1492 count = attr->a_numvals;
1493 assert( count > 0 );
1494 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1495 qi->next = op->o_callback->sc_private;
1496 op->o_callback->sc_private = qi;
1497 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1498 qi->del = ( count == 1 );
1507 struct berval *query_uuid )
1509 struct query_info *qi, *qnext;
1510 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1511 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1512 Filter filter = {LDAP_FILTER_EQUALITY};
1513 SlapReply sreply = {REP_RESULT};
1514 slap_callback cb = { NULL, remove_func, NULL, NULL };
1517 sreply.sr_entry = NULL;
1518 sreply.sr_nentries = 0;
1519 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1520 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1521 filter.f_ava = &ava;
1522 filter.f_av_desc = ad_queryId;
1523 filter.f_av_value = *query_uuid;
1525 op->o_tag = LDAP_REQ_SEARCH;
1526 op->o_protocol = LDAP_VERSION3;
1527 op->o_callback = &cb;
1528 op->o_time = slap_get_time();
1529 op->o_do_not_cache = 1;
1531 op->o_req_dn = op->o_bd->be_suffix[0];
1532 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1533 op->ors_scope = LDAP_SCOPE_SUBTREE;
1534 op->ors_deref = LDAP_DEREF_NEVER;
1535 op->ors_slimit = SLAP_NO_LIMIT;
1536 op->ors_tlimit = SLAP_NO_LIMIT;
1537 op->ors_filter = &filter;
1538 op->ors_filterstr.bv_val = filter_str;
1539 op->ors_filterstr.bv_len = strlen(filter_str);
1540 op->ors_attrs = NULL;
1541 op->ors_attrsonly = 0;
1543 op->o_bd->be_search( op, &sreply );
1545 for ( qi=cb.sc_private; qi; qi=qnext ) {
1548 op->o_req_dn = qi->xdn;
1549 op->o_req_ndn = qi->xdn;
1552 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1553 query_uuid->bv_val, 0, 0 );
1555 op->o_tag = LDAP_REQ_DELETE;
1557 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1563 struct berval vals[2];
1565 vals[0] = *query_uuid;
1566 vals[1].bv_val = NULL;
1568 mod.sml_op = LDAP_MOD_DELETE;
1570 mod.sml_desc = ad_queryId;
1571 mod.sml_type = ad_queryId->ad_cname;
1572 mod.sml_values = vals;
1573 mod.sml_nvalues = NULL;
1574 mod.sml_numvals = 1;
1575 mod.sml_next = NULL;
1576 Debug( pcache_debug,
1577 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1578 query_uuid->bv_val, 0, 0 );
1580 op->orm_modlist = &mod;
1582 op->o_bd->be_modify( op, &sreply );
1584 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1585 op->o_tmpfree( qi, op->o_tmpmemctx );
1592 AttributeName* attrs,
1601 struct berval *fstr,
1602 AttributeName** filter_attrs,
1604 int* filter_got_oc )
1606 AttributeDescription *ad;
1609 switch ( f->f_choice ) {
1610 case LDAP_FILTER_EQUALITY:
1612 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1613 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1614 assert( ret == len );
1615 fstr->bv_len += len;
1618 case LDAP_FILTER_GE:
1620 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1621 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1622 assert( ret == len );
1623 fstr->bv_len += len;
1626 case LDAP_FILTER_LE:
1628 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1629 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1630 assert( ret == len );
1631 fstr->bv_len += len;
1634 case LDAP_FILTER_APPROX:
1636 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1637 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1638 assert( ret == len );
1639 fstr->bv_len += len;
1642 case LDAP_FILTER_SUBSTRINGS:
1644 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1645 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1646 assert( ret == len );
1647 fstr->bv_len += len;
1650 case LDAP_FILTER_PRESENT:
1652 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1653 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1654 assert( ret == len );
1655 fstr->bv_len += len;
1658 case LDAP_FILTER_AND:
1659 case LDAP_FILTER_OR:
1660 case LDAP_FILTER_NOT: {
1662 fstr->bv_val[fstr->bv_len++] = '(';
1663 switch ( f->f_choice ) {
1664 case LDAP_FILTER_AND:
1665 fstr->bv_val[fstr->bv_len] = '&';
1667 case LDAP_FILTER_OR:
1668 fstr->bv_val[fstr->bv_len] = '|';
1670 case LDAP_FILTER_NOT:
1671 fstr->bv_val[fstr->bv_len] = '!';
1676 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1677 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1681 fstr->bv_val[fstr->bv_len++] = ')';
1682 fstr->bv_val[fstr->bv_len] = '\0';
1688 /* a filter should at least have room for "()",
1689 * an "=" and for a 1-char attr */
1690 strcpy( fstr->bv_val, "(?=)" );
1691 fstr->bv_len += STRLENOF("(?=)");
1695 if ( filter_attrs != NULL ) {
1696 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1697 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1699 (*filter_attrs)[*filter_cnt].an_desc = ad;
1700 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1701 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1702 (*filter_attrs)[*filter_cnt].an_flags = 0;
1703 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1705 if ( ad == slap_schema.si_ad_objectClass )
1712 struct search_info {
1715 QueryTemplate *qtemp;
1716 AttributeName* save_attrs; /* original attributes, saved for response */
1717 int swap_saved_attrs;
1722 int slimit_exceeded;
1723 pc_caching_reason_t caching_reason;
1728 remove_query_and_data(
1732 struct berval *uuid )
1734 query_manager* qm = cm->qm;
1736 qm->crfunc( qm, uuid );
1737 if ( !BER_BVISNULL( uuid ) ) {
1740 Debug( pcache_debug,
1741 "Removing query UUID %s\n",
1742 uuid->bv_val, 0, 0 );
1743 return_val = remove_query_data( op, rs, uuid );
1744 Debug( pcache_debug,
1745 "QUERY REMOVED, SIZE=%d\n",
1747 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1748 cm->cur_entries -= return_val;
1749 cm->num_cached_queries--;
1750 Debug( pcache_debug,
1751 "STORED QUERIES = %lu\n",
1752 cm->num_cached_queries, 0, 0 );
1753 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1754 Debug( pcache_debug,
1755 "QUERY REMOVED, CACHE ="
1757 cm->cur_entries, 0, 0 );
1762 * Callback used to fetch queryId values based on entryUUID;
1763 * used by pcache_remove_entries_from_cache()
1766 fetch_queryId_cb( Operation *op, SlapReply *rs )
1770 /* only care about searchEntry responses */
1771 if ( rs->sr_type != REP_SEARCH ) {
1775 /* allow only one response per entryUUID */
1776 if ( op->o_callback->sc_private != NULL ) {
1782 /* copy all queryId values into callback's private data */
1783 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1785 BerVarray vals = NULL;
1787 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1788 op->o_callback->sc_private = (void *)vals;
1792 /* clear entry if required */
1793 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1794 entry_free( rs->sr_entry );
1795 rs->sr_entry = NULL;
1796 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1803 * Call that allows to remove a set of entries from the cache,
1804 * by forcing the removal of all the related queries.
1807 pcache_remove_entries_from_cache(
1810 BerVarray entryUUIDs )
1812 Connection conn = { 0 };
1813 OperationBuffer opbuf;
1815 slap_callback sc = { 0 };
1816 SlapReply rs = { REP_RESULT };
1818 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1819 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1820 AttributeName attrs[ 2 ] = {{{ 0 }}};
1824 void *thrctx = ldap_pvt_thread_pool_context();
1826 connection_fake_init( &conn, &opbuf, thrctx );
1834 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1835 op->ors_scope = LDAP_SCOPE_SUBTREE;
1836 op->ors_deref = LDAP_DEREF_NEVER;
1837 f.f_choice = LDAP_FILTER_EQUALITY;
1839 ava.aa_desc = slap_schema.si_ad_entryUUID;
1840 op->ors_filter = &f;
1842 op->ors_tlimit = SLAP_NO_LIMIT;
1843 attrs[ 0 ].an_desc = ad_queryId;
1844 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1845 op->ors_attrs = attrs;
1846 op->ors_attrsonly = 0;
1848 op->o_req_dn = cm->db.be_suffix[ 0 ];
1849 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1851 op->o_tag = LDAP_REQ_SEARCH;
1852 op->o_protocol = LDAP_VERSION3;
1853 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1855 op->o_dn = op->o_bd->be_rootdn;
1856 op->o_ndn = op->o_bd->be_rootndn;
1857 sc.sc_response = fetch_queryId_cb;
1858 op->o_callback = ≻
1860 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1861 BerVarray vals = NULL;
1863 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1864 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1865 op->ors_filterstr.bv_val = filtbuf;
1866 ava.aa_value = entryUUIDs[ s ];
1868 rc = op->o_bd->be_search( op, &rs );
1869 if ( rc != LDAP_SUCCESS ) {
1873 vals = (BerVarray)op->o_callback->sc_private;
1874 if ( vals != NULL ) {
1877 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1878 struct berval val = vals[ i ];
1880 remove_query_and_data( op, &rs, cm, &val );
1882 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1883 ch_free( val.bv_val );
1887 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1888 op->o_callback->sc_private = NULL;
1896 * Call that allows to remove a query from the cache.
1899 pcache_remove_query_from_cache(
1902 struct berval *queryid )
1904 Operation op2 = *op;
1905 SlapReply rs2 = { 0 };
1909 /* remove the selected query */
1910 remove_query_and_data( &op2, &rs2, cm, queryid );
1912 return LDAP_SUCCESS;
1916 * Call that allows to remove a set of queries related to an entry
1917 * from the cache; if queryid is not null, the entry must belong to
1918 * the query indicated by queryid.
1921 pcache_remove_entry_queries_from_cache(
1925 struct berval *queryid )
1927 Connection conn = { 0 };
1928 OperationBuffer opbuf;
1930 slap_callback sc = { 0 };
1931 SlapReply rs = { REP_RESULT };
1933 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1934 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1935 AttributeName attrs[ 2 ] = {{{ 0 }}};
1938 BerVarray vals = NULL;
1941 void *thrctx = ldap_pvt_thread_pool_context();
1943 connection_fake_init( &conn, &opbuf, thrctx );
1951 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1952 op->ors_scope = LDAP_SCOPE_BASE;
1953 op->ors_deref = LDAP_DEREF_NEVER;
1954 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1955 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1956 f.f_choice = LDAP_FILTER_PRESENT;
1957 f.f_desc = slap_schema.si_ad_objectClass;
1960 op->ors_filterstr.bv_len = snprintf( filter_str,
1961 sizeof( filter_str ), "(%s=%s)",
1962 ad_queryId->ad_cname.bv_val, queryid->bv_val );
1963 f.f_choice = LDAP_FILTER_EQUALITY;
1965 f.f_av_desc = ad_queryId;
1966 f.f_av_value = *queryid;
1968 op->ors_filter = &f;
1970 op->ors_tlimit = SLAP_NO_LIMIT;
1971 attrs[ 0 ].an_desc = ad_queryId;
1972 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1973 op->ors_attrs = attrs;
1974 op->ors_attrsonly = 0;
1976 op->o_req_dn = *ndn;
1977 op->o_req_ndn = *ndn;
1979 op->o_tag = LDAP_REQ_SEARCH;
1980 op->o_protocol = LDAP_VERSION3;
1981 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1983 op->o_dn = op->o_bd->be_rootdn;
1984 op->o_ndn = op->o_bd->be_rootndn;
1985 sc.sc_response = fetch_queryId_cb;
1986 op->o_callback = ≻
1988 rc = op->o_bd->be_search( op, &rs );
1989 if ( rc != LDAP_SUCCESS ) {
1993 vals = (BerVarray)op->o_callback->sc_private;
1994 if ( vals != NULL ) {
1997 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1998 struct berval val = vals[ i ];
2000 remove_query_and_data( op, &rs, cm, &val );
2002 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2003 ch_free( val.bv_val );
2007 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2010 return LDAP_SUCCESS;
2017 struct berval *query_uuid )
2019 struct search_info *si = op->o_callback->sc_private;
2020 slap_overinst *on = si->on;
2021 cache_manager *cm = on->on_bi.bi_private;
2024 struct berval crp_uuid;
2025 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2027 Connection conn = {0};
2028 OperationBuffer opbuf;
2029 void *thrctx = ldap_pvt_thread_pool_context();
2031 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2032 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2034 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2035 op_tmp = &opbuf.ob_op;
2036 op_tmp->o_bd = &cm->db;
2037 op_tmp->o_dn = cm->db.be_rootdn;
2038 op_tmp->o_ndn = cm->db.be_rootndn;
2040 Debug( pcache_debug, "UUID for query being added = %s\n",
2043 for ( e=si->head; e; e=si->head ) {
2044 si->head = e->e_private;
2045 e->e_private = NULL;
2046 while ( cm->cur_entries > (cm->max_entries) ) {
2047 BER_BVZERO( &crp_uuid );
2048 remove_query_and_data( op_tmp, rs, cm, &crp_uuid );
2051 return_val = merge_entry(op_tmp, e, query_uuid);
2052 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2053 cm->cur_entries += return_val;
2054 Debug( pcache_debug,
2055 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2056 cm->cur_entries, 0, 0 );
2058 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2065 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2066 slap_callback *cb = op->o_callback;
2067 struct search_info *si = cb->sc_private;
2068 slap_overinst *on = si->on;
2069 cache_manager *cm = on->on_bi.bi_private;
2070 query_manager* qm = cm->qm;
2072 if ( rs->sr_type == REP_SEARCH ) {
2075 /* don't return more entries than requested by the client */
2076 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2077 si->slimit_exceeded = 1;
2080 /* If we haven't exceeded the limit for this query,
2081 * build a chain of answers to store. If we hit the
2082 * limit, empty the chain and ignore the rest.
2085 /* check if the entry contains undefined
2086 * attributes/objectClasses (ITS#5680) */
2087 if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2088 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2089 op->o_log_prefix, rs->sr_entry->e_name.bv_val, 0 );
2093 /* check for malformed entries: attrs with no values */
2095 Attribute *a = rs->sr_entry->e_attrs;
2096 for (; a; a=a->a_next) {
2097 if ( !a->a_numvals ) {
2098 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2099 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2100 a->a_desc->ad_cname.bv_val );
2106 if ( si->count < si->max ) {
2108 e = entry_dup( rs->sr_entry );
2109 if ( !si->head ) si->head = e;
2110 if ( si->tail ) si->tail->e_private = e;
2117 for (;si->head; si->head=e) {
2118 e = si->head->e_private;
2119 si->head->e_private = NULL;
2120 entry_free(si->head);
2128 if ( rs->sr_type == REP_RESULT ||
2129 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2131 if ( si->swap_saved_attrs ) {
2132 rs->sr_attrs = si->save_attrs;
2133 op->ors_attrs = si->save_attrs;
2135 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) &&
2136 si->caching_reason == PC_IGNORE )
2138 filter_free( si->query.filter );
2140 /* duplicate query, free it */
2142 for (;si->head; si->head=e) {
2143 e = si->head->e_private;
2144 si->head->e_private = NULL;
2145 entry_free(si->head);
2148 op->o_callback = op->o_callback->sc_next;
2149 op->o_tmpfree( cb, op->o_tmpmemctx );
2150 } else if ( si->caching_reason != PC_IGNORE ) {
2151 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2152 si->qtemp, si->caching_reason, 1 );
2155 switch ( si->caching_reason ) {
2157 cache_entries( op, rs, &qc->q_uuid );
2161 qc->q_sizelimit = rs->sr_nentries;
2171 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2172 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2173 cm->num_cached_queries++;
2174 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2175 cm->num_cached_queries, 0, 0 );
2176 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2178 /* If the consistency checker suspended itself,
2181 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2182 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2183 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2185 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2187 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2190 } else if ( si->count ) {
2191 /* duplicate query, free it */
2193 for (;si->head; si->head=e) {
2194 e = si->head->e_private;
2195 si->head->e_private = NULL;
2196 entry_free(si->head);
2201 filter_free( si->query.filter );
2205 return SLAP_CB_CONTINUE;
2213 struct search_info *si = op->o_callback->sc_private;
2215 if ( si->swap_saved_attrs ) {
2216 rs->sr_attrs = si->save_attrs;
2217 op->ors_attrs = si->save_attrs;
2220 if ( rs->sr_type == REP_SEARCH ) {
2221 /* don't return more entries than requested by the client */
2222 if ( si->slimit_exceeded ) {
2226 } else if ( rs->sr_type == REP_RESULT ) {
2229 if ( rs->sr_err == LDAP_SUCCESS ) {
2230 si->caching_reason = PC_POSITIVE;
2232 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2233 && si->qtemp->limitttl )
2235 si->caching_reason = PC_SIZELIMIT;
2238 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2239 rs->sr_err == LDAP_SUCCESS )
2241 si->caching_reason = PC_NEGATIVE;
2245 if ( si->slimit_exceeded ) {
2246 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2250 return SLAP_CB_CONTINUE;
2256 AttributeName** new_attrs,
2257 struct attr_set *attrs,
2258 AttributeName* filter_attrs,
2268 /* duplicate attrs */
2269 count = attrs->count + fattr_cnt;
2270 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2275 *new_attrs = (AttributeName*)ch_calloc( count + 1,
2276 sizeof(AttributeName) );
2277 for (i=0; i<attrs->count; i++) {
2278 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2279 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2281 BER_BVZERO( &(*new_attrs)[i].an_name );
2282 alluser = an_find( *new_attrs, slap_bv_all_user_attrs );
2283 allop = an_find( *new_attrs, slap_bv_all_operational_attrs );
2286 for ( i=0; i<fattr_cnt; i++ ) {
2287 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2290 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2294 } else if ( alluser ) {
2297 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2298 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2299 (*new_attrs)[j].an_oc = NULL;
2300 (*new_attrs)[j].an_flags = 0;
2304 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2305 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2306 (*new_attrs)[j].an_oc = NULL;
2307 (*new_attrs)[j].an_flags = 0;
2310 BER_BVZERO( &(*new_attrs)[j].an_name );
2315 /* NOTE: this is a quick workaround to let pcache minimally interact
2316 * with pagedResults. A more articulated solutions would be to
2317 * perform the remote query without control and cache all results,
2318 * performing the pagedResults search only within the client
2319 * and the proxy. This requires pcache to understand pagedResults. */
2321 pcache_chk_controls(
2325 const char *non = "";
2326 const char *stripped = "";
2328 switch( op->o_pagedresults ) {
2329 case SLAP_CONTROL_NONCRITICAL:
2331 stripped = "; stripped";
2334 case SLAP_CONTROL_CRITICAL:
2335 Debug( pcache_debug, "%s: "
2336 "%scritical pagedResults control "
2337 "disabled with proxy cache%s.\n",
2338 op->o_log_prefix, non, stripped );
2340 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2344 rs->sr_err = SLAP_CB_CONTINUE;
2351 #ifdef PCACHE_CONTROL_PRIVDB
2357 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2358 cache_manager *cm = on->on_bi.bi_private;
2359 slap_callback *save_cb;
2362 /* skip if control is unset */
2363 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2364 return SLAP_CB_CONTINUE;
2367 /* The cache DB isn't open yet */
2368 if ( cm->defer_db_open ) {
2369 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2370 "pcachePrivDB: cacheDB not available" );
2374 /* FIXME: might be a little bit exaggerated... */
2375 if ( !be_isroot( op ) ) {
2376 save_cb = op->o_callback;
2377 op->o_callback = NULL;
2378 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2379 "pcachePrivDB: operation not allowed" );
2380 op->o_callback = save_cb;
2385 /* map tag to operation */
2386 type = slap_req2op( op->o_tag );
2387 if ( type != SLAP_OP_LAST ) {
2391 /* execute, if possible */
2392 func = &cm->db.be_bind;
2393 if ( func[ type ] != NULL ) {
2394 Operation op2 = *op;
2398 rc = func[ type ]( &op2, rs );
2399 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2400 op->o_conn->c_authz_cookie = cm->db.be_private;
2405 /* otherwise fall back to error */
2406 save_cb = op->o_callback;
2407 op->o_callback = NULL;
2408 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2409 "operation not supported with pcachePrivDB control" );
2410 op->o_callback = save_cb;
2414 #endif /* PCACHE_CONTROL_PRIVDB */
2421 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2422 cache_manager *cm = on->on_bi.bi_private;
2423 query_manager* qm = cm->qm;
2427 AttributeName *filter_attrs = NULL;
2430 QueryTemplate *qtemp = NULL;
2433 CachedQuery *answerable = NULL;
2436 int fattr_got_oc = 0;
2438 struct berval tempstr;
2440 #ifdef PCACHE_CONTROL_PRIVDB
2441 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2442 return pcache_op_privdb( op, rs );
2444 #endif /* PCACHE_CONTROL_PRIVDB */
2446 /* The cache DB isn't open yet */
2447 if ( cm->defer_db_open ) {
2448 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2449 "pcachePrivDB: cacheDB not available" );
2453 /* pickup runtime ACL changes */
2454 cm->db.be_acl = op->o_bd->be_acl;
2456 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2458 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2459 &fattr_cnt, &fattr_got_oc ))
2461 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2462 return SLAP_CB_CONTINUE;
2465 Debug( pcache_debug, "query template of incoming query = %s\n",
2466 tempstr.bv_val, 0, 0 );
2468 /* FIXME: cannot cache/answer requests with pagedResults control */
2471 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2473 query.filter = op->ors_filter;
2474 query.base = op->o_req_ndn;
2475 query.scope = op->ors_scope;
2477 /* check for query containment */
2478 if (attr_set > -1) {
2479 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2480 for (; qt; qt = qt->qtnext ) {
2481 /* find if template i can potentially answer tempstr */
2482 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
2486 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2487 op->ors_filterstr.bv_val, 0, 0 );
2488 answerable = qm->qcfunc(op, qm, &query, qt);
2490 /* if != NULL, rlocks qtemp->t_rwlock */
2495 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2498 BackendDB *save_bd = op->o_bd;
2499 slap_callback *save_cb = op->o_callback;
2501 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
2502 answerable->answerable_cnt++;
2503 /* we only care about refcnts if we're refreshing */
2504 if ( answerable->refresh_time )
2505 answerable->refcnt++;
2506 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
2507 answerable->answerable_cnt, 0, 0 );
2508 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
2510 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2511 ldap_pvt_thread_rdwr_rlock(&answerable->rwlock);
2512 if ( BER_BVISNULL( &answerable->q_uuid )) {
2513 /* No entries cached, just an empty result set */
2515 send_ldap_result( op, rs );
2518 if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
2519 /* The cached entry was already processed by any
2520 * other overlays, so don't let it get processed again.
2522 op->o_callback = NULL;
2524 i = cm->db.bd_info->bi_op_search( op, rs );
2526 ldap_pvt_thread_rdwr_runlock(&answerable->rwlock);
2527 /* locked by qtemp->qcfunc (query_containment) */
2528 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2530 op->o_callback = save_cb;
2534 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2536 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2537 if (cm->num_cached_queries >= cm->max_queries) {
2540 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2542 if (op->ors_attrsonly)
2547 struct search_info *si;
2549 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2550 query.filter = filter_dup(op->ors_filter, NULL);
2551 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2552 if ( !qtemp->t_attrs.count ) {
2553 qtemp->t_attrs.count = add_filter_attrs(op,
2554 &qtemp->t_attrs.attrs,
2555 &qm->attr_sets[attr_set],
2556 filter_attrs, fattr_cnt, fattr_got_oc);
2558 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2560 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2561 cb->sc_response = pcache_response;
2562 cb->sc_cleanup = pcache_op_cleanup;
2563 cb->sc_private = (cb+1);
2564 si = cb->sc_private;
2568 si->max = cm->num_entries_limit ;
2572 si->slimit_exceeded = 0;
2573 si->caching_reason = PC_IGNORE;
2574 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
2575 si->slimit = op->ors_slimit;
2576 op->ors_slimit = cm->num_entries_limit;
2580 si->swap_saved_attrs = 1;
2581 si->save_attrs = op->ors_attrs;
2583 op->ors_attrs = qtemp->t_attrs.attrs;
2585 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2586 cb->sc_next = op->o_callback;
2587 op->o_callback = cb;
2590 slap_callback **pcb;
2592 /* need to move the callback at the end, in case other
2593 * overlays are present, so that the final entry is
2594 * actually cached */
2596 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2601 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2605 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2607 return SLAP_CB_CONTINUE;
2612 AttributeName* attrs,
2620 for ( ; attrs[count].an_name.bv_val; count++ );
2623 /* recognize a single "*" or a "1.1" */
2626 attrs = slap_anlist_all_user_attributes;
2628 } else if ( count == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) {
2633 for ( i = 0; i < num; i++ ) {
2637 if ( count > qm->attr_sets[i].count ) {
2642 if ( !qm->attr_sets[i].count ) {
2648 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2649 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2667 /* Refresh a cached query:
2668 * 1: Replay the query on the remote DB and merge each entry into
2669 * the local DB. Remember the DNs of each remote entry.
2670 * 2: Search the local DB for all entries matching this queryID.
2671 * Delete any entry whose DN is not in the list from (1).
2673 typedef struct dnlist {
2674 struct dnlist *next;
2679 typedef struct refresh_info {
2687 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
2689 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
2691 dn->dn.bv_len = bvdn->bv_len;
2692 dn->dn.bv_val = (char *)(dn+1);
2693 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
2694 dn->dn.bv_val[dn->dn.bv_len] = '\0';
2699 refresh_merge( Operation *op, SlapReply *rs )
2701 if ( rs->sr_type == REP_SEARCH ) {
2702 refresh_info *ri = op->o_callback->sc_private;
2703 BackendDB *be = op->o_bd;
2709 ocb = op->o_callback;
2710 /* Find local entry, merge */
2711 op->o_bd = ri->ri_be;
2712 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
2713 if ( rc != LDAP_SUCCESS || e == NULL ) {
2714 /* No local entry, just add it. FIXME: we are not checking
2715 * the cache entry limit here
2717 merge_entry( op, rs->sr_entry, &ri->ri_q->q_uuid );
2719 /* Entry exists, update it */
2722 Modifications *modlist, *mods = NULL;
2723 const char* text = NULL;
2724 char textbuf[SLAP_TEXT_BUFLEN];
2725 size_t textlen = sizeof(textbuf);
2726 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
2730 /* Get a copy of only the attrs we requested */
2731 for ( a=e->e_attrs; a; a=a->a_next ) {
2732 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
2733 *b = attr_alloc( a->a_desc );
2735 /* The actual values still belong to e */
2736 (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
2737 SLAP_ATTR_DONT_FREE_DATA;
2738 b = &((*b)->a_next);
2742 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
2743 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
2744 &mods, &modlist, 0 );
2745 be_entry_release_r( op, e );
2746 attrs_free( ne.e_attrs );
2747 slap_mods_free( modlist, 1 );
2748 /* mods is NULL if there are no changes */
2750 struct berval dn = op->o_req_dn;
2751 struct berval ndn = op->o_req_ndn;
2752 op->o_tag = LDAP_REQ_MODIFY;
2753 op->orm_modlist = mods;
2754 op->o_req_dn = rs->sr_entry->e_name;
2755 op->o_req_ndn = rs->sr_entry->e_nname;
2756 op->o_callback = &cb;
2757 op->o_bd->be_modify( op, rs );
2758 slap_mods_free( mods, 1 );
2760 op->o_req_ndn = ndn;
2764 /* Add DN to list */
2765 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
2767 if ( ri->ri_tail ) {
2768 ri->ri_tail->next = dnl;
2773 op->o_callback = ocb;
2779 refresh_purge( Operation *op, SlapReply *rs )
2781 if ( rs->sr_type == REP_SEARCH ) {
2782 refresh_info *ri = op->o_callback->sc_private;
2786 /* Did the entry exist on the remote? */
2787 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
2788 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
2789 dnlist *dnext = (*dn)->next;
2790 op->o_tmpfree( *dn, op->o_tmpmemctx );
2796 /* No, so put it on the list to delete */
2799 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
2800 dnl->next = ri->ri_dels;
2802 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2803 /* If ours is the only queryId, delete entry */
2804 dnl->delete = ( a->a_numvals == 1 );
2811 refresh_query( Operation *op, SlapReply *rs, CachedQuery *query,
2814 slap_callback cb = { 0 };
2815 refresh_info ri = { 0 };
2816 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
2817 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2818 Filter filter = {LDAP_FILTER_EQUALITY};
2819 AttributeName attrs[ 2 ] = {{{ 0 }}};
2823 ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
2825 ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
2827 cb.sc_response = refresh_merge;
2828 cb.sc_private = &ri;
2831 ri.ri_be = op->o_bd;
2834 op->o_tag = LDAP_REQ_SEARCH;
2835 op->o_protocol = LDAP_VERSION3;
2836 op->o_callback = &cb;
2837 op->o_do_not_cache = 1;
2839 op->o_req_dn = query->qbase->base;
2840 op->o_req_ndn = query->qbase->base;
2841 op->ors_scope = query->scope;
2842 op->ors_slimit = SLAP_NO_LIMIT;
2843 op->ors_tlimit = SLAP_NO_LIMIT;
2844 op->ors_filter = query->filter;
2845 filter2bv_x( op, query->filter, &op->ors_filterstr );
2846 op->ors_attrs = query->qtemp->t_attrs.attrs;
2847 op->ors_attrsonly = 0;
2849 op->o_bd = on->on_info->oi_origdb;
2850 rc = op->o_bd->be_search( op, rs );
2852 op->o_bd = ri.ri_be;
2856 /* Get the DNs of all entries matching this query */
2857 cb.sc_response = refresh_purge;
2859 op->o_bd = ri.ri_be;
2860 op->o_req_dn = op->o_bd->be_suffix[0];
2861 op->o_req_ndn = op->o_bd->be_nsuffix[0];
2862 op->ors_scope = LDAP_SCOPE_SUBTREE;
2863 op->ors_deref = LDAP_DEREF_NEVER;
2864 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
2865 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
2866 filter.f_ava = &ava;
2867 filter.f_av_desc = ad_queryId;
2868 filter.f_av_value = query->q_uuid;
2869 attrs[ 0 ].an_desc = ad_queryId;
2870 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2871 op->ors_attrs = attrs;
2872 op->ors_attrsonly = 0;
2873 rs->sr_entry = NULL;
2874 rs->sr_nentries = 0;
2875 rc = op->o_bd->be_search( op, rs );
2876 if ( rc ) goto leave;
2878 while (( dn = ri.ri_dels )) {
2879 op->o_req_dn = dn->dn;
2880 op->o_req_ndn = dn->dn;
2882 op->o_tag = LDAP_REQ_DELETE;
2883 op->o_bd->be_delete( op, rs );
2886 struct berval vals[2];
2888 vals[0] = query->q_uuid;
2889 BER_BVZERO( &vals[1] );
2890 mod.sml_op = LDAP_MOD_DELETE;
2892 mod.sml_desc = ad_queryId;
2893 mod.sml_type = ad_queryId->ad_cname;
2894 mod.sml_values = vals;
2895 mod.sml_nvalues = NULL;
2896 mod.sml_numvals = 1;
2897 mod.sml_next = NULL;
2899 op->o_tag = LDAP_REQ_MODIFY;
2900 op->orm_modlist = &mod;
2901 op->o_bd->be_modify( op, rs );
2903 ri.ri_dels = dn->next;
2904 op->o_tmpfree( dn, op->o_tmpmemctx );
2908 /* reset our local heap, we're done with it */
2909 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
2918 struct re_s *rtask = arg;
2919 slap_overinst *on = rtask->arg;
2920 cache_manager *cm = on->on_bi.bi_private;
2921 query_manager *qm = cm->qm;
2922 Connection conn = {0};
2923 OperationBuffer opbuf;
2926 SlapReply rs = {REP_RESULT};
2927 CachedQuery *query, *qprev;
2928 int return_val, pause = PCACHE_CC_PAUSED;
2929 QueryTemplate *templ;
2931 /* Don't expire anything when we're offline */
2932 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
2933 pause = PCACHE_CC_OFFLINE;
2937 connection_fake_init( &conn, &opbuf, ctx );
2941 op->o_dn = cm->db.be_rootdn;
2942 op->o_ndn = cm->db.be_rootndn;
2946 for (templ = qm->templates; templ; templ=templ->qmnext) {
2948 if ( !templ->query_last ) continue;
2950 op->o_time = slap_get_time();
2951 if ( !templ->ttr ) {
2953 if ( templ->negttl && templ->negttl < ttl )
2954 ttl = templ->negttl;
2955 if ( templ->limitttl && templ->limitttl < ttl )
2956 ttl = templ->limitttl;
2957 /* The oldest timestamp that needs expiration checking */
2961 for ( query=templ->query_last; query; query=qprev ) {
2962 qprev = query->prev;
2963 if ( query->refresh_time && query->refresh_time < op->o_time ) {
2964 /* A refresh will extend the expiry if the query has been
2965 * referenced, but not if it's unreferenced. If the
2966 * expiration has been hit, then skip the refresh since
2967 * we're just going to discard the result anyway.
2969 if ( query->refcnt )
2970 query->expiry_time = op->o_time + templ->ttl;
2971 if ( query->expiry_time > op->o_time ) {
2972 refresh_query( op, &rs, query, on );
2977 if (query->expiry_time < op->o_time) {
2979 Debug( pcache_debug, "Lock CR index = %p\n",
2980 (void *) templ, 0, 0 );
2981 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2982 if ( query == templ->query_last ) {
2984 remove_from_template(query, templ);
2985 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2986 (void *) templ, templ->no_of_queries, 0 );
2987 Debug( pcache_debug, "Unlock CR index = %p\n",
2988 (void *) templ, 0, 0 );
2990 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2994 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2995 remove_query(qm, query);
2996 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2997 if ( BER_BVISNULL( &query->q_uuid ))
3000 return_val = remove_query_data(op, &rs, &query->q_uuid);
3001 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3003 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3004 cm->cur_entries -= return_val;
3005 cm->num_cached_queries--;
3006 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3007 cm->num_cached_queries, 0, 0 );
3008 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3009 Debug( pcache_debug,
3010 "STALE QUERY REMOVED, CACHE ="
3012 cm->cur_entries, 0, 0 );
3014 } else if ( !templ->ttr && query->expiry_time > ttl ) {
3015 /* We don't need to check for refreshes, and this
3016 * query's expiry is too new, and all subsequent queries
3017 * will be newer yet. So stop looking.
3019 * If we have refreshes, then we always have to walk the
3020 * entire query list.
3028 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3029 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3030 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3032 /* If there were no queries, defer processing for a while */
3033 if ( cm->cc_paused != pause )
3034 cm->cc_paused = pause;
3035 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3037 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3042 #define MAX_ATTR_SETS 500
3054 static ConfigDriver pc_cf_gen;
3055 static ConfigLDAPadd pc_ldadd;
3056 static ConfigCfAdd pc_cfadd;
3058 static ConfigTable pccfg[] = {
3059 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3061 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3062 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3063 "DESC 'Proxy Cache basic parameters' "
3064 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3065 { "pcacheAttrset", "index> <attributes...",
3066 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3067 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3068 "DESC 'A set of attributes to cache' "
3069 "SYNTAX OMsDirectoryString )", NULL, NULL },
3070 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3072 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3073 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3074 "DESC 'Filter template, attrset, cache TTL, "
3075 "optional negative TTL, optional sizelimit TTL, "
3077 "SYNTAX OMsDirectoryString )", NULL, NULL },
3078 { "pcachePosition", "head|tail(default)",
3079 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3080 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3081 "DESC 'Response callback position in overlay stack' "
3082 "SYNTAX OMsDirectoryString )", NULL, NULL },
3083 { "pcacheMaxQueries", "queries",
3084 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3085 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3086 "DESC 'Maximum number of queries to cache' "
3087 "SYNTAX OMsInteger )", NULL, NULL },
3088 { "pcachePersist", "TRUE|FALSE",
3089 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3090 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3091 "DESC 'Save cached queries for hot restart' "
3092 "SYNTAX OMsBoolean )", NULL, NULL },
3093 { "pcacheValidate", "TRUE|FALSE",
3094 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3095 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3096 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3097 "SYNTAX OMsBoolean )", NULL, NULL },
3098 { "pcacheOffline", "TRUE|FALSE",
3099 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3100 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3101 "DESC 'Set cache to offline mode and disable expiration' "
3102 "SYNTAX OMsBoolean )", NULL, NULL },
3103 { "pcache-", "private database args",
3104 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3107 /* Legacy keywords */
3108 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3110 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3112 { "proxyattrset", "index> <attributes...",
3113 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3115 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3116 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3118 { "response-callback", "head|tail(default)",
3119 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3121 { "proxyCacheQueries", "queries",
3122 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3124 { "proxySaveQueries", "TRUE|FALSE",
3125 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3127 { "proxyCheckCacheability", "TRUE|FALSE",
3128 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3131 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3134 static ConfigOCs pcocs[] = {
3135 { "( OLcfgOvOc:2.1 "
3136 "NAME 'olcPcacheConfig' "
3137 "DESC 'ProxyCache configuration' "
3138 "SUP olcOverlayConfig "
3139 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3140 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3141 "olcPcacheValidate $ olcPcacheOffline ) )",
3142 Cft_Overlay, pccfg, NULL, pc_cfadd },
3143 { "( OLcfgOvOc:2.2 "
3144 "NAME 'olcPcacheDatabase' "
3145 "DESC 'Cache database configuration' "
3146 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3150 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3153 pc_ldadd_cleanup( ConfigArgs *c )
3155 slap_overinst *on = c->ca_private;
3156 return pcache_db_open2( on, &c->reply );
3160 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3165 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3166 p->ce_bi->bi_cf_ocs != pcocs )
3167 return LDAP_CONSTRAINT_VIOLATION;
3169 on = (slap_overinst *)p->ce_bi;
3170 cm = on->on_bi.bi_private;
3172 /* Defer open if this is an LDAPadd */
3173 if ( CONFIG_ONLINE_ADD( ca ))
3174 ca->cleanup = pc_ldadd_cleanup;
3176 cm->defer_db_open = 0;
3177 ca->ca_private = on;
3178 return LDAP_SUCCESS;
3182 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3184 CfEntryInfo *pe = p->e_private;
3185 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3186 cache_manager *cm = on->on_bi.bi_private;
3189 /* FIXME: should not hardcode "olcDatabase" here */
3190 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3191 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3192 0, cm->db.bd_info->bi_type );
3193 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3196 bv.bv_val = ca->cr_msg;
3198 cm->defer_db_open = 0;
3200 /* We can only create this entry if the database is table-driven
3202 if ( cm->db.bd_info->bi_cf_ocs )
3203 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3210 pc_cf_gen( ConfigArgs *c )
3212 slap_overinst *on = (slap_overinst *)c->bi;
3213 cache_manager* cm = on->on_bi.bi_private;
3214 query_manager* qm = cm->qm;
3215 QueryTemplate* temp;
3216 AttributeName* attr_name;
3217 AttributeName* attrarray;
3218 const char* text=NULL;
3223 if ( c->op == SLAP_CONFIG_EMIT ) {
3227 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3228 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3229 cm->num_entries_limit, cm->cc_period );
3230 bv.bv_val = c->cr_msg;
3231 value_add_one( &c->rvalue_vals, &bv );
3234 for (i=0; i<cm->numattrsets; i++) {
3235 if ( !qm->attr_sets[i].count ) continue;
3237 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3239 /* count the attr length */
3240 for ( attr_name = qm->attr_sets[i].attrs;
3241 attr_name->an_name.bv_val; attr_name++ )
3242 bv.bv_len += attr_name->an_name.bv_len + 1;
3244 bv.bv_val = ch_malloc( bv.bv_len+1 );
3245 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3246 for ( attr_name = qm->attr_sets[i].attrs;
3247 attr_name->an_name.bv_val; attr_name++ ) {
3249 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3251 ber_bvarray_add( &c->rvalue_vals, &bv );
3253 if ( !c->rvalue_vals )
3257 for (temp=qm->templates; temp; temp=temp->qmnext) {
3258 /* HEADS-UP: always print all;
3259 * if optional == 0, ignore */
3260 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3261 " %d %ld %ld %ld %ld",
3262 temp->attr_set_index,
3267 bv.bv_len += temp->querystr.bv_len + 2;
3268 bv.bv_val = ch_malloc( bv.bv_len+1 );
3271 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3273 strcpy( ptr, c->cr_msg );
3274 ber_bvarray_add( &c->rvalue_vals, &bv );
3276 if ( !c->rvalue_vals )
3280 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3281 BER_BVSTR( &bv, "head" );
3283 BER_BVSTR( &bv, "tail" );
3285 value_add_one( &c->rvalue_vals, &bv );
3288 c->value_int = cm->max_queries;
3291 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3295 } else if ( c->op == LDAP_MOD_DELETE ) {
3298 case PC_ATTR: /* FIXME */
3302 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3303 /* If there were cached queries when we went offline,
3304 * restart the checker now.
3306 if ( cm->num_cached_queries ) {
3307 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3309 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3310 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3320 if ( cm->numattrsets > 0 ) {
3321 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
3322 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3326 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3327 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3329 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3332 if ( cm->numattrsets <= 0 ) {
3333 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3334 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3337 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3338 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3339 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3343 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3344 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3345 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3349 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3350 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3352 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3355 if ( cm->max_entries <= 0 ) {
3356 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3357 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
3361 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
3362 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
3364 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3367 if ( cm->num_entries_limit <= 0 ) {
3368 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
3369 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3372 if ( cm->num_entries_limit > cm->max_entries ) {
3373 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
3374 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3378 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3379 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
3381 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3385 cm->cc_period = (time_t)t;
3386 Debug( pcache_debug,
3387 "Total # of attribute sets to be cached = %d.\n",
3388 cm->numattrsets, 0, 0 );
3389 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
3390 sizeof( struct attr_set ) );
3393 if ( cm->numattrsets == 0 ) {
3394 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3395 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3398 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
3399 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
3401 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3405 if ( num < 0 || num >= cm->numattrsets ) {
3406 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
3407 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3408 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3411 qm->attr_sets[num].flags |= PC_CONFIGURED;
3412 if ( c->argc == 2 ) {
3414 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3415 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
3416 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3419 } else if ( c->argc == 3 ) {
3420 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3421 qm->attr_sets[num].count = 1;
3422 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3423 sizeof( AttributeName ) );
3424 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
3427 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3428 qm->attr_sets[num].count = 1;
3429 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3430 sizeof( AttributeName ) );
3431 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3434 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
3437 /* else: fallthru */
3439 } else if ( c->argc == 4 ) {
3440 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
3441 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
3443 qm->attr_sets[num].count = 2;
3444 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
3445 sizeof( AttributeName ) );
3446 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
3447 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3450 /* else: fallthru */
3453 if ( c->argc > 2 ) {
3454 int all_user = 0, all_op = 0;
3456 qm->attr_sets[num].count = c->argc - 2;
3457 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
3458 sizeof( AttributeName ) );
3459 attr_name = qm->attr_sets[num].attrs;
3460 for ( i = 2; i < c->argc; i++ ) {
3461 attr_name->an_desc = NULL;
3462 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
3463 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3464 "invalid attr #%d \"%s\" in attrlist",
3465 i - 2, c->argv[i] );
3466 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3467 ch_free( qm->attr_sets[num].attrs );
3468 qm->attr_sets[num].attrs = NULL;
3469 qm->attr_sets[num].count = 0;
3472 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3474 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
3475 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3477 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3479 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
3480 strcpy( c->cr_msg, text );
3481 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3482 ch_free( qm->attr_sets[num].attrs );
3483 qm->attr_sets[num].attrs = NULL;
3484 qm->attr_sets[num].count = 0;
3487 attr_name->an_name = attr_name->an_desc->ad_cname;
3489 attr_name->an_oc = NULL;
3490 attr_name->an_flags = 0;
3491 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
3492 qm->attr_sets[num].flags |= PC_GOT_OC;
3494 BER_BVZERO( &attr_name->an_name );
3497 /* warn if list contains both "*" and "+" */
3498 if ( i > 4 && all_user && all_op ) {
3499 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3500 "warning: attribute list contains \"*\" and \"+\"" );
3501 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3506 if ( cm->numattrsets == 0 ) {
3507 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3508 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3511 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
3512 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
3514 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3518 if ( i < 0 || i >= cm->numattrsets ||
3519 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
3520 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
3521 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3522 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3525 temp = ch_calloc( 1, sizeof( QueryTemplate ));
3526 temp->qmnext = qm->templates;
3527 qm->templates = temp;
3528 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
3529 temp->query = temp->query_last = NULL;
3530 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
3531 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3532 "unable to parse template ttl=\"%s\"",
3534 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3537 temp->ttl = (time_t)t;
3538 temp->negttl = (time_t)0;
3539 temp->limitttl = (time_t)0;
3540 temp->ttr = (time_t)0;
3541 switch ( c->argc ) {
3543 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
3544 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3545 "unable to parse template ttr=\"%s\"",
3547 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3550 temp->ttr = (time_t)t;
3554 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3555 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3556 "unable to parse template sizelimit ttl=\"%s\"",
3558 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3561 temp->limitttl = (time_t)t;
3565 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
3566 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3567 "unable to parse template negative ttl=\"%s\"",
3569 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3572 temp->negttl = (time_t)t;
3576 temp->no_of_queries = 0;
3578 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3579 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3580 Debug( pcache_debug, " query template: %s\n",
3581 temp->querystr.bv_val, 0, 0 );
3582 temp->attr_set_index = i;
3583 qm->attr_sets[i].flags |= PC_REFERENCED;
3584 temp->qtnext = qm->attr_sets[i].templates;
3585 qm->attr_sets[i].templates = temp;
3586 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
3587 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3588 for ( i=0; attrarray[i].an_name.bv_val; i++ )
3589 Debug( pcache_debug, "\t%s\n",
3590 attrarray[i].an_name.bv_val, 0, 0 );
3594 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3595 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3597 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3598 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3601 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3602 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3607 if ( c->value_int <= 0 ) {
3608 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3609 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3612 cm->max_queries = c->value_int;
3616 cm->cc_paused |= PCACHE_CC_OFFLINE;
3618 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3621 if ( cm->db.be_private == NULL ) {
3622 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3623 "private database must be defined before setting database specific options" );
3624 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3628 if ( cm->db.bd_info->bi_cf_ocs ) {
3631 char *argv0 = c->argv[ 0 ];
3633 c->argv[ 0 ] = &argv0[ STRLENOF( "proxycache-" ) ];
3635 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
3637 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3638 "private database does not recognize specific option '%s'",
3640 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3644 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
3646 c->bi = c->be->bd_info;
3648 rc = config_add_vals( ct, c );
3652 c->table = c2.table;
3655 c->argv[ 0 ] = argv0;
3657 } else if ( cm->db.be_config != NULL ) {
3658 char *argv0 = c->argv[ 0 ];
3660 c->argv[ 0 ] = &argv0[ STRLENOF( "proxycache-" ) ];
3661 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
3662 c->argv[ 0 ] = argv0;
3665 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3666 "no means to set private database specific options" );
3667 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3672 rc = SLAP_CONF_UNKNOWN;
3688 slap_overinst *on = (slap_overinst *)be->bd_info;
3689 cache_manager* cm = on->on_bi.bi_private;
3691 /* Something for the cache database? */
3692 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3693 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3695 return SLAP_CONF_UNKNOWN;
3703 slap_overinst *on = (slap_overinst *)be->bd_info;
3707 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3708 on->on_bi.bi_private = cm;
3710 qm = (query_manager*)ch_malloc(sizeof(query_manager));
3713 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3714 cm->db.be_private = NULL;
3715 cm->db.bd_self = &cm->db;
3717 cm->numattrsets = 0;
3718 cm->num_entries_limit = 5;
3719 cm->num_cached_queries = 0;
3720 cm->max_entries = 0;
3721 cm->cur_entries = 0;
3722 cm->max_queries = 10000;
3723 cm->save_queries = 0;
3724 cm->check_cacheability = 0;
3725 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3726 cm->defer_db_open = 1;
3727 cm->cc_period = 1000;
3731 qm->attr_sets = NULL;
3732 qm->templates = NULL;
3734 qm->lru_bottom = NULL;
3736 qm->qcfunc = query_containment;
3737 qm->crfunc = cache_replacement;
3738 qm->addfunc = add_query;
3739 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3741 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3746 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3748 assert( op->o_tag == LDAP_REQ_SEARCH );
3750 if ( rs->sr_type == REP_SEARCH ) {
3753 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3757 assert( a->a_nvals != NULL );
3759 valsp = op->o_callback->sc_private;
3760 assert( *valsp == NULL );
3762 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3770 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3772 assert( op->o_tag == LDAP_REQ_SEARCH );
3774 if ( rs->sr_type == REP_SEARCH ) {
3775 int *countp = (int *)op->o_callback->sc_private;
3788 cache_manager *cm = on->on_bi.bi_private;
3789 query_manager* qm = cm->qm;
3792 rc = backend_startup_one( &cm->db, cr );
3794 cm->defer_db_open = 0;
3797 /* There is no runqueue in TOOL mode */
3798 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
3799 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3800 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3801 consistency_check, on,
3802 "pcache_consistency", cm->db.be_suffix[0].bv_val );
3803 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3805 /* Cached database must have the rootdn */
3806 if ( BER_BVISNULL( &cm->db.be_rootndn )
3807 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3809 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3810 "underlying database of type \"%s\"\n"
3811 " serving naming context \"%s\"\n"
3812 " has no \"rootdn\", required by \"proxycache\".\n",
3813 on->on_info->oi_orig->bi_type,
3814 cm->db.be_suffix[0].bv_val, 0 );
3818 if ( cm->save_queries ) {
3819 void *thrctx = ldap_pvt_thread_pool_context();
3820 Connection conn = { 0 };
3821 OperationBuffer opbuf;
3823 slap_callback cb = { 0 };
3824 SlapReply rs = { 0 };
3825 BerVarray vals = NULL;
3826 Filter f = { 0 }, f2 = { 0 };
3827 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3828 AttributeName attrs[ 2 ] = {{{ 0 }}};
3830 connection_fake_init( &conn, &opbuf, thrctx );
3835 op->o_tag = LDAP_REQ_SEARCH;
3836 op->o_protocol = LDAP_VERSION3;
3837 cb.sc_response = pcache_cachedquery_open_cb;
3838 cb.sc_private = &vals;
3839 op->o_callback = &cb;
3840 op->o_time = slap_get_time();
3841 op->o_do_not_cache = 1;
3842 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3844 op->o_dn = cm->db.be_rootdn;
3845 op->o_ndn = cm->db.be_rootndn;
3846 op->o_req_dn = cm->db.be_suffix[ 0 ];
3847 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3849 op->ors_scope = LDAP_SCOPE_BASE;
3850 op->ors_deref = LDAP_DEREF_NEVER;
3852 op->ors_tlimit = SLAP_NO_LIMIT;
3853 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3854 f.f_choice = LDAP_FILTER_PRESENT;
3855 f.f_desc = ad_cachedQueryURL;
3856 op->ors_filter = &f;
3857 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3858 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3859 op->ors_attrs = attrs;
3860 op->ors_attrsonly = 0;
3862 rc = op->o_bd->be_search( op, &rs );
3863 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3866 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3867 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3868 cm->num_cached_queries++;
3872 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3875 /* count cached entries */
3876 f.f_choice = LDAP_FILTER_NOT;
3878 f2.f_choice = LDAP_FILTER_EQUALITY;
3880 f2.f_av_desc = slap_schema.si_ad_objectClass;
3881 BER_BVSTR( &f2.f_av_value, "glue" );
3882 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3884 op->ors_slimit = SLAP_NO_LIMIT;
3885 op->ors_scope = LDAP_SCOPE_SUBTREE;
3886 op->ors_attrs = slap_anlist_no_attrs;
3888 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3890 op->o_callback->sc_private = &rs.sr_nentries;
3892 rc = op->o_bd->be_search( op, &rs );
3894 cm->cur_entries = rs.sr_nentries;
3908 slap_overinst *on = (slap_overinst *)be->bd_info;
3909 cache_manager *cm = on->on_bi.bi_private;
3910 query_manager* qm = cm->qm;
3911 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3913 /* check attr sets */
3914 for ( i = 0; i < cm->numattrsets; i++) {
3915 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3916 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3917 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3921 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3925 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3926 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3931 if ( ncf || rf || nrf ) {
3932 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3933 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3934 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3941 /* need to inherit something from the original database... */
3942 cm->db.be_def_limit = be->be_def_limit;
3943 cm->db.be_limits = be->be_limits;
3944 cm->db.be_acl = be->be_acl;
3945 cm->db.be_dfltaccess = be->be_dfltaccess;
3947 if ( SLAP_DBMONITORING( be ) ) {
3948 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3951 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3954 if ( !cm->defer_db_open )
3955 rc = pcache_db_open2( on, cr );
3961 pcache_free_qbase( void *v )
3967 tavl_free( qb->scopes[i], NULL );
3977 slap_overinst *on = (slap_overinst *)be->bd_info;
3978 cache_manager *cm = on->on_bi.bi_private;
3979 query_manager *qm = cm->qm;
3983 if ( cm->save_queries ) {
3985 BerVarray vals = NULL;
3988 Connection conn = { 0 };
3989 OperationBuffer opbuf;
3991 slap_callback cb = { 0 };
3993 SlapReply rs = { REP_RESULT };
3994 Modifications mod = {{ 0 }};
3996 thrctx = ldap_pvt_thread_pool_context();
3998 connection_fake_init( &conn, &opbuf, thrctx );
4001 if ( qm->templates != NULL ) {
4002 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4003 for ( qc = tm->query; qc; qc = qc->next ) {
4006 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4007 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4014 op->o_dn = cm->db.be_rootdn;
4015 op->o_ndn = cm->db.be_rootndn;
4017 op->o_tag = LDAP_REQ_MODIFY;
4018 op->o_protocol = LDAP_VERSION3;
4019 cb.sc_response = slap_null_cb;
4020 op->o_callback = &cb;
4021 op->o_time = slap_get_time();
4022 op->o_do_not_cache = 1;
4023 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4025 op->o_req_dn = op->o_bd->be_suffix[0];
4026 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4028 mod.sml_op = LDAP_MOD_REPLACE;
4030 mod.sml_desc = ad_cachedQueryURL;
4031 mod.sml_type = ad_cachedQueryURL->ad_cname;
4032 mod.sml_values = vals;
4033 mod.sml_nvalues = NULL;
4034 mod.sml_numvals = 1;
4035 mod.sml_next = NULL;
4036 Debug( pcache_debug,
4037 "%sSETTING CACHED QUERY URLS\n",
4038 vals == NULL ? "RE" : "", 0, 0 );
4040 op->orm_modlist = &mod;
4042 op->o_bd->be_modify( op, &rs );
4044 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4047 /* cleanup stuff inherited from the original database... */
4048 cm->db.be_limits = NULL;
4049 cm->db.be_acl = NULL;
4051 /* stop the thread ... */
4053 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4054 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4055 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4057 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4058 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4061 if ( cm->db.bd_info->bi_db_close ) {
4062 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4064 while ( (tm = qm->templates) != NULL ) {
4065 CachedQuery *qc, *qn;
4066 qm->templates = tm->qmnext;
4067 for ( qc = tm->query; qc; qc = qn ) {
4071 avl_free( tm->qbase, pcache_free_qbase );
4072 free( tm->querystr.bv_val );
4073 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4074 free( tm->t_attrs.attrs );
4078 for ( i=0; i<cm->numattrsets; i++ ) {
4079 free( qm->attr_sets[i].attrs );
4081 free( qm->attr_sets );
4082 qm->attr_sets = NULL;
4093 slap_overinst *on = (slap_overinst *)be->bd_info;
4094 cache_manager *cm = on->on_bi.bi_private;
4095 query_manager *qm = cm->qm;
4097 if ( cm->db.be_private != NULL ) {
4098 backend_stopdown_one( &cm->db );
4101 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4102 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4109 #ifdef PCACHE_CONTROL_PRIVDB
4111 Control ::= SEQUENCE {
4112 controlType LDAPOID,
4113 criticality BOOLEAN DEFAULT FALSE,
4114 controlValue OCTET STRING OPTIONAL }
4116 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4118 * criticality must be TRUE; controlValue must be absent.
4126 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4127 rs->sr_text = "privateDB control specified multiple times";
4128 return LDAP_PROTOCOL_ERROR;
4131 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4132 rs->sr_text = "privateDB control value not absent";
4133 return LDAP_PROTOCOL_ERROR;
4136 if ( !ctrl->ldctl_iscritical ) {
4137 rs->sr_text = "privateDB control criticality required";
4138 return LDAP_PROTOCOL_ERROR;
4141 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4143 return LDAP_SUCCESS;
4146 static char *extops[] = {
4147 LDAP_EXOP_MODIFY_PASSWD,
4150 #endif /* PCACHE_CONTROL_PRIVDB */
4152 #ifdef PCACHE_EXOP_QUERY_DELETE
4153 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4155 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4156 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4157 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
4160 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
4161 requestName [0] LDAPOID,
4162 requestValue [1] OCTET STRING OPTIONAL }
4164 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
4166 requestValue ::= SEQUENCE { CHOICE {
4168 entryDN [1] LDAPDN },
4169 queryID [2] OCTET STRING (SIZE(16))
4170 -- constrained to UUID }
4172 * Either baseDN or entryDN must be present, to allow database selection.
4174 * 1. if baseDN and queryID are present, then the query corresponding
4175 * to queryID is deleted;
4176 * 2. if baseDN is present and queryID is absent, then all queries
4178 * 3. if entryDN is present and queryID is absent, then all queries
4179 * corresponding to the queryID values present in entryDN are deleted;
4180 * 4. if entryDN and queryID are present, then all queries
4181 * corresponding to the queryID values present in entryDN are deleted,
4182 * but only if the value of queryID is contained in the entry;
4184 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
4185 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
4186 * or by removing the database files.
4188 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
4189 COMPONENTS OF LDAPResult,
4190 responseName [10] LDAPOID OPTIONAL,
4191 responseValue [11] OCTET STRING OPTIONAL }
4193 * responseName and responseValue must be absent.
4197 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
4198 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
4199 * - if ndn != NULL, it is set to the normalized DN in the request
4200 * corresponding to either the baseDN or the entryDN, according
4201 * to *tagp; memory is malloc'ed on the Operation's slab, and must
4202 * be freed by the caller.
4203 * - if uuid != NULL, it is set to point to the normalized UUID;
4204 * memory is malloc'ed on the Operation's slab, and must
4205 * be freed by the caller.
4208 pcache_parse_query_delete(
4212 struct berval *uuid,
4216 int rc = LDAP_SUCCESS;
4219 BerElementBuffer berbuf;
4220 BerElement *ber = (BerElement *)&berbuf;
4221 struct berval reqdata = BER_BVNULL;
4233 if ( in == NULL || in->bv_len == 0 ) {
4234 *text = "empty request data field in queryDelete exop";
4235 return LDAP_PROTOCOL_ERROR;
4238 ber_dupbv_x( &reqdata, in, ctx );
4240 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
4241 ber_init2( ber, &reqdata, 0 );
4243 tag = ber_scanf( ber, "{" /*}*/ );
4245 if ( tag == LBER_ERROR ) {
4246 Debug( LDAP_DEBUG_TRACE,
4247 "pcache_parse_query_delete: decoding error.\n",
4249 goto decoding_error;
4252 tag = ber_peek_tag( ber, &len );
4253 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
4254 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
4258 if ( ndn != NULL ) {
4261 tag = ber_scanf( ber, "m", &dn );
4262 if ( tag == LBER_ERROR ) {
4263 Debug( LDAP_DEBUG_TRACE,
4264 "pcache_parse_query_delete: DN parse failed.\n",
4266 goto decoding_error;
4269 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
4270 if ( rc != LDAP_SUCCESS ) {
4271 *text = "invalid DN in queryDelete exop request data";
4276 tag = ber_scanf( ber, "x" /* "m" */ );
4277 if ( tag == LBER_DEFAULT ) {
4278 goto decoding_error;
4282 tag = ber_peek_tag( ber, &len );
4285 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
4286 if ( uuid != NULL ) {
4288 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
4290 tag = ber_scanf( ber, "m", &bv );
4291 if ( tag == LBER_ERROR ) {
4292 Debug( LDAP_DEBUG_TRACE,
4293 "pcache_parse_query_delete: UUID parse failed.\n",
4295 goto decoding_error;
4298 if ( bv.bv_len != 16 ) {
4299 Debug( LDAP_DEBUG_TRACE,
4300 "pcache_parse_query_delete: invalid UUID length %lu.\n",
4301 (unsigned long)bv.bv_len, 0, 0 );
4302 goto decoding_error;
4305 rc = lutil_uuidstr_from_normalized(
4306 bv.bv_val, bv.bv_len,
4307 uuidbuf, sizeof( uuidbuf ) );
4309 goto decoding_error;
4311 ber_str2bv( uuidbuf, rc, 1, uuid );
4315 tag = ber_skip_tag( ber, &len );
4316 if ( tag == LBER_DEFAULT ) {
4317 goto decoding_error;
4321 Debug( LDAP_DEBUG_TRACE,
4322 "pcache_parse_query_delete: invalid UUID length %lu.\n",
4323 (unsigned long)len, 0, 0 );
4324 goto decoding_error;
4328 tag = ber_peek_tag( ber, &len );
4331 if ( tag != LBER_DEFAULT || len != 0 ) {
4333 Debug( LDAP_DEBUG_TRACE,
4334 "pcache_parse_query_delete: decoding error\n",
4336 rc = LDAP_PROTOCOL_ERROR;
4337 *text = "queryDelete data decoding error";
4340 if ( ndn && !BER_BVISNULL( ndn ) ) {
4341 slap_sl_free( ndn->bv_val, ctx );
4345 if ( uuid && !BER_BVISNULL( uuid ) ) {
4346 slap_sl_free( uuid->bv_val, ctx );
4351 if ( !BER_BVISNULL( &reqdata ) ) {
4352 ber_memfree_x( reqdata.bv_val, ctx );
4359 pcache_exop_query_delete(
4363 BackendDB *bd = op->o_bd;
4365 struct berval uuid = BER_BVNULL,
4367 char buf[ SLAP_TEXT_BUFLEN ];
4369 ber_tag_t tag = LBER_DEFAULT;
4371 if ( LogTest( LDAP_DEBUG_STATS ) ) {
4375 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
4376 &tag, &op->o_req_ndn, uuidp,
4377 &rs->sr_text, op->o_tmpmemctx );
4378 if ( rs->sr_err != LDAP_SUCCESS ) {
4382 if ( LogTest( LDAP_DEBUG_STATS ) ) {
4383 assert( !BER_BVISNULL( &op->o_req_ndn ) );
4384 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
4386 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
4387 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
4390 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
4391 op->o_log_prefix, buf, 0 );
4393 op->o_req_dn = op->o_req_ndn;
4395 op->o_bd = select_backend( &op->o_req_ndn, 0 );
4396 rs->sr_err = backend_check_restrictions( op, rs,
4397 (struct berval *)&pcache_exop_QUERY_DELETE );
4398 if ( rs->sr_err != LDAP_SUCCESS ) {
4402 if ( op->o_bd->be_extended == NULL ) {
4403 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
4404 "backend does not support extended operations" );
4408 op->o_bd->be_extended( op, rs );
4411 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
4412 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
4413 BER_BVZERO( &op->o_req_ndn );
4414 BER_BVZERO( &op->o_req_dn );
4417 if ( !BER_BVISNULL( &uuid ) ) {
4418 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
4427 pcache_op_extended( Operation *op, SlapReply *rs )
4429 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
4430 cache_manager *cm = on->on_bi.bi_private;
4432 #ifdef PCACHE_CONTROL_PRIVDB
4433 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
4434 return pcache_op_privdb( op, rs );
4436 #endif /* PCACHE_CONTROL_PRIVDB */
4438 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
4439 struct berval uuid = BER_BVNULL;
4440 ber_tag_t tag = LBER_DEFAULT;
4442 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
4443 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
4444 assert( rs->sr_err == LDAP_SUCCESS );
4446 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
4447 /* remove all queries related to the selected entry */
4448 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
4449 cm, &op->o_req_ndn, &uuid );
4451 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
4452 if ( !BER_BVISNULL( &uuid ) ) {
4453 /* remove the selected query */
4454 rs->sr_err = pcache_remove_query_from_cache( op,
4458 /* TODO: remove all queries */
4459 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4460 rs->sr_text = "deletion of all queries not implemented";
4464 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
4469 #endif /* PCACHE_EXOP_QUERY_DELETE */
4471 static slap_overinst pcache;
4473 static char *obsolete_names[] = {
4478 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4480 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
4485 struct berval debugbv = BER_BVC("pcache");
4487 code = slap_loglevel_get( &debugbv, &pcache_debug );
4492 #ifdef PCACHE_CONTROL_PRIVDB
4493 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
4494 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
4495 parse_privdb_ctrl, &privDB_cid );
4496 if ( code != LDAP_SUCCESS ) {
4497 Debug( LDAP_DEBUG_ANY,
4498 "pcache_initialize: failed to register control %s (%d)\n",
4499 PCACHE_CONTROL_PRIVDB, code, 0 );
4502 #endif /* PCACHE_CONTROL_PRIVDB */
4504 #ifdef PCACHE_EXOP_QUERY_DELETE
4505 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
4506 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
4508 if ( code != LDAP_SUCCESS ) {
4509 Debug( LDAP_DEBUG_ANY,
4510 "pcache_initialize: unable to register queryDelete exop: %d.\n",
4514 #endif /* PCACHE_EXOP_QUERY_DELETE */
4516 for ( i = 0; as[i].desc != NULL; i++ ) {
4517 code = register_at( as[i].desc, as[i].adp, 0 );
4519 Debug( LDAP_DEBUG_ANY,
4520 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
4523 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
4526 pcache.on_bi.bi_type = "pcache";
4527 pcache.on_bi.bi_obsolete_names = obsolete_names;
4528 pcache.on_bi.bi_db_init = pcache_db_init;
4529 pcache.on_bi.bi_db_config = pcache_db_config;
4530 pcache.on_bi.bi_db_open = pcache_db_open;
4531 pcache.on_bi.bi_db_close = pcache_db_close;
4532 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
4534 pcache.on_bi.bi_op_search = pcache_op_search;
4535 #ifdef PCACHE_CONTROL_PRIVDB
4536 pcache.on_bi.bi_op_bind = pcache_op_privdb;
4537 pcache.on_bi.bi_op_compare = pcache_op_privdb;
4538 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
4539 pcache.on_bi.bi_op_modify = pcache_op_privdb;
4540 pcache.on_bi.bi_op_add = pcache_op_privdb;
4541 pcache.on_bi.bi_op_delete = pcache_op_privdb;
4542 #endif /* PCACHE_CONTROL_PRIVDB */
4543 #ifdef PCACHE_EXOP_QUERY_DELETE
4544 pcache.on_bi.bi_extended = pcache_op_extended;
4545 #elif defined( PCACHE_CONTROL_PRIVDB )
4546 pcache.on_bi.bi_extended = pcache_op_privdb;
4549 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
4551 pcache.on_bi.bi_cf_ocs = pcocs;
4553 code = config_register_schema( pccfg, pcocs );
4554 if ( code ) return code;
4556 return overlay_register( &pcache );
4559 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4560 int init_module(int argc, char *argv[]) {
4561 return pcache_initialize();
4565 #endif /* defined(SLAPD_OVER_PROXYCACHE) */