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;
2678 typedef struct refresh_info {
2686 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
2688 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
2690 dn->dn.bv_len = bvdn->bv_len;
2691 dn->dn.bv_val = (char *)(dn+1);
2692 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
2693 dn->dn.bv_val[dn->dn.bv_len] = '\0';
2698 refresh_merge( Operation *op, SlapReply *rs )
2700 if ( rs->sr_type == REP_SEARCH ) {
2701 refresh_info *ri = op->o_callback->sc_private;
2702 BackendDB *be = op->o_bd;
2708 ocb = op->o_callback;
2709 /* Find local entry, merge */
2710 op->o_bd = ri->ri_be;
2711 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
2712 if ( rc != LDAP_SUCCESS || e == NULL ) {
2713 /* No local entry, just add it. FIXME: we are not checking
2714 * the cache entry limit here
2716 merge_entry( op, rs->sr_entry, &ri->ri_q->q_uuid );
2718 /* Entry exists, update it */
2721 Modifications *modlist, *mods;
2722 const char* text = NULL;
2723 char textbuf[SLAP_TEXT_BUFLEN];
2724 size_t textlen = sizeof(textbuf);
2725 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
2729 /* Get a copy of only the attrs we requested */
2730 for ( a=e->e_attrs; a; a=a->a_next ) {
2731 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
2732 *b = attr_alloc( a->a_desc );
2734 b = &((*b)->a_next);
2738 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
2739 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
2740 &mods, &modlist, 0 );
2741 be_entry_release_r( op, e );
2742 /* mods is NULL if there are no changes */
2744 struct berval dn = op->o_req_dn;
2745 struct berval ndn = op->o_req_ndn;
2746 op->o_tag = LDAP_REQ_MODIFY;
2747 op->orm_modlist = mods;
2748 op->o_req_dn = rs->sr_entry->e_name;
2749 op->o_req_ndn = rs->sr_entry->e_nname;
2750 op->o_callback = &cb;
2751 op->o_bd->be_modify( op, rs );
2752 slap_mods_free( mods, 1 );
2754 op->o_req_ndn = ndn;
2758 /* Add DN to list */
2759 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
2761 if ( ri->ri_tail ) {
2762 ri->ri_tail->next = dnl;
2767 op->o_callback = ocb;
2773 refresh_purge( Operation *op, SlapReply *rs )
2775 if ( rs->sr_type == REP_SEARCH ) {
2776 refresh_info *ri = op->o_callback->sc_private;
2780 /* Did the entry exist on the remote? */
2781 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
2782 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
2783 dnlist *dnext = (*dn)->next;
2784 op->o_tmpfree( *dn, op->o_tmpmemctx );
2790 /* No, so put it on the list to delete */
2792 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
2793 dnl->next = ri->ri_dels;
2801 refresh_query( Operation *op, SlapReply *rs, CachedQuery *query,
2804 slap_callback cb = { 0 };
2805 refresh_info ri = { 0 };
2806 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
2807 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2808 Filter filter = {LDAP_FILTER_EQUALITY};
2812 cb.sc_response = refresh_merge;
2813 cb.sc_private = &ri;
2816 ri.ri_be = op->o_bd;
2819 op->o_tag = LDAP_REQ_SEARCH;
2820 op->o_protocol = LDAP_VERSION3;
2821 op->o_callback = &cb;
2822 op->o_do_not_cache = 1;
2824 op->o_req_dn = query->qbase->base;
2825 op->o_req_ndn = query->qbase->base;
2826 op->ors_scope = query->scope;
2827 op->ors_slimit = SLAP_NO_LIMIT;
2828 op->ors_tlimit = SLAP_NO_LIMIT;
2829 op->ors_filter = query->filter;
2830 filter2bv_x( op, query->filter, &op->ors_filterstr );
2831 op->ors_attrs = query->qtemp->t_attrs.attrs;
2832 op->ors_attrsonly = 0;
2834 op->o_bd = on->on_info->oi_origdb;
2835 rc = op->o_bd->be_search( op, rs );
2837 op->o_bd = ri.ri_be;
2841 /* Get the DNs of all entries matching this query */
2842 cb.sc_response = refresh_purge;
2844 op->o_bd = ri.ri_be;
2845 op->o_req_dn = op->o_bd->be_suffix[0];
2846 op->o_req_ndn = op->o_bd->be_nsuffix[0];
2847 op->ors_scope = LDAP_SCOPE_SUBTREE;
2848 op->ors_deref = LDAP_DEREF_NEVER;
2849 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
2850 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
2851 filter.f_ava = &ava;
2852 filter.f_av_desc = ad_queryId;
2853 filter.f_av_value = query->q_uuid;
2854 op->ors_attrs = slap_anlist_no_attrs;
2855 op->ors_attrsonly = 1;
2856 rs->sr_entry = NULL;
2857 rs->sr_nentries = 0;
2858 rc = op->o_bd->be_search( op, rs );
2859 if ( rc ) goto leave;
2861 op->o_tag = LDAP_REQ_DELETE;
2862 while (( dn = ri.ri_dels )) {
2863 op->o_req_dn = dn->dn;
2864 op->o_req_ndn = dn->dn;
2865 op->o_bd->be_delete( op, rs );
2866 ri.ri_dels = dn->next;
2867 op->o_tmpfree( dn, op->o_tmpmemctx );
2871 /* reset our local heap, we're done with it */
2872 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
2881 struct re_s *rtask = arg;
2882 slap_overinst *on = rtask->arg;
2883 cache_manager *cm = on->on_bi.bi_private;
2884 query_manager *qm = cm->qm;
2885 Connection conn = {0};
2886 OperationBuffer opbuf;
2889 SlapReply rs = {REP_RESULT};
2890 CachedQuery *query, *qprev;
2891 int return_val, pause = PCACHE_CC_PAUSED;
2892 QueryTemplate *templ;
2894 /* Don't expire anything when we're offline */
2895 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
2896 pause = PCACHE_CC_OFFLINE;
2900 connection_fake_init( &conn, &opbuf, ctx );
2904 op->o_dn = cm->db.be_rootdn;
2905 op->o_ndn = cm->db.be_rootndn;
2909 for (templ = qm->templates; templ; templ=templ->qmnext) {
2911 if ( !templ->query_last ) continue;
2913 op->o_time = slap_get_time();
2914 if ( !templ->ttr ) {
2916 if ( templ->negttl && templ->negttl < ttl )
2917 ttl = templ->negttl;
2918 if ( templ->limitttl && templ->limitttl < ttl )
2919 ttl = templ->limitttl;
2920 /* The oldest timestamp that needs expiration checking */
2924 for ( query=templ->query_last; query; query=qprev ) {
2925 qprev = query->prev;
2926 if ( query->refresh_time && query->refresh_time < op->o_time ) {
2927 /* A refresh will extend the expiry if the query has been
2928 * referenced, but not if it's unreferenced. If the
2929 * expiration has been hit, then skip the refresh since
2930 * we're just going to discard the result anyway.
2932 if ( query->refcnt )
2933 query->expiry_time = op->o_time + templ->ttl;
2934 if ( query->expiry_time > op->o_time ) {
2935 refresh_query( op, &rs, query, on );
2940 if (query->expiry_time < op->o_time) {
2942 Debug( pcache_debug, "Lock CR index = %p\n",
2943 (void *) templ, 0, 0 );
2944 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2945 if ( query == templ->query_last ) {
2947 remove_from_template(query, templ);
2948 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2949 (void *) templ, templ->no_of_queries, 0 );
2950 Debug( pcache_debug, "Unlock CR index = %p\n",
2951 (void *) templ, 0, 0 );
2953 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2957 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2958 remove_query(qm, query);
2959 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2960 if ( BER_BVISNULL( &query->q_uuid ))
2963 return_val = remove_query_data(op, &rs, &query->q_uuid);
2964 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2966 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2967 cm->cur_entries -= return_val;
2968 cm->num_cached_queries--;
2969 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2970 cm->num_cached_queries, 0, 0 );
2971 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2972 Debug( pcache_debug,
2973 "STALE QUERY REMOVED, CACHE ="
2975 cm->cur_entries, 0, 0 );
2977 } else if ( !templ->ttr && query->expiry_time > ttl ) {
2978 /* We don't need to check for refreshes, and this
2979 * query's expiry is too new, and all subsequent queries
2980 * will be newer yet. So stop looking.
2982 * If we have refreshes, then we always have to walk the
2983 * entire query list.
2991 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2992 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2993 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2995 /* If there were no queries, defer processing for a while */
2996 if ( cm->cc_paused != pause )
2997 cm->cc_paused = pause;
2998 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3000 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3005 #define MAX_ATTR_SETS 500
3017 static ConfigDriver pc_cf_gen;
3018 static ConfigLDAPadd pc_ldadd;
3019 static ConfigCfAdd pc_cfadd;
3021 static ConfigTable pccfg[] = {
3022 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3024 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3025 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3026 "DESC 'Proxy Cache basic parameters' "
3027 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3028 { "pcacheAttrset", "index> <attributes...",
3029 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3030 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3031 "DESC 'A set of attributes to cache' "
3032 "SYNTAX OMsDirectoryString )", NULL, NULL },
3033 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3035 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3036 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3037 "DESC 'Filter template, attrset, cache TTL, "
3038 "optional negative TTL, optional sizelimit TTL, "
3040 "SYNTAX OMsDirectoryString )", NULL, NULL },
3041 { "pcachePosition", "head|tail(default)",
3042 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3043 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3044 "DESC 'Response callback position in overlay stack' "
3045 "SYNTAX OMsDirectoryString )", NULL, NULL },
3046 { "pcacheMaxQueries", "queries",
3047 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3048 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3049 "DESC 'Maximum number of queries to cache' "
3050 "SYNTAX OMsInteger )", NULL, NULL },
3051 { "pcachePersist", "TRUE|FALSE",
3052 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3053 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3054 "DESC 'Save cached queries for hot restart' "
3055 "SYNTAX OMsBoolean )", NULL, NULL },
3056 { "pcacheValidate", "TRUE|FALSE",
3057 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3058 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3059 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3060 "SYNTAX OMsBoolean )", NULL, NULL },
3061 { "pcacheOffline", "TRUE|FALSE",
3062 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3063 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3064 "DESC 'Set cache to offline mode and disable expiration' "
3065 "SYNTAX OMsBoolean )", NULL, NULL },
3066 { "pcache-", "private database args",
3067 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3070 /* Legacy keywords */
3071 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3073 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3075 { "proxyattrset", "index> <attributes...",
3076 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3078 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3079 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3081 { "response-callback", "head|tail(default)",
3082 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3084 { "proxyCacheQueries", "queries",
3085 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3087 { "proxySaveQueries", "TRUE|FALSE",
3088 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3090 { "proxyCheckCacheability", "TRUE|FALSE",
3091 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3094 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3097 static ConfigOCs pcocs[] = {
3098 { "( OLcfgOvOc:2.1 "
3099 "NAME 'olcPcacheConfig' "
3100 "DESC 'ProxyCache configuration' "
3101 "SUP olcOverlayConfig "
3102 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3103 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3104 "olcPcacheValidate $ olcPcacheOffline ) )",
3105 Cft_Overlay, pccfg, NULL, pc_cfadd },
3106 { "( OLcfgOvOc:2.2 "
3107 "NAME 'olcPcacheDatabase' "
3108 "DESC 'Cache database configuration' "
3109 "AUXILIARY )", Cft_Misc, olcDatabaseDummy, pc_ldadd },
3113 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3116 pc_ldadd_cleanup( ConfigArgs *c )
3118 slap_overinst *on = c->ca_private;
3119 return pcache_db_open2( on, &c->reply );
3123 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3128 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3129 p->ce_bi->bi_cf_ocs != pcocs )
3130 return LDAP_CONSTRAINT_VIOLATION;
3132 on = (slap_overinst *)p->ce_bi;
3133 cm = on->on_bi.bi_private;
3135 /* Defer open if this is an LDAPadd */
3136 if ( CONFIG_ONLINE_ADD( ca ))
3137 ca->cleanup = pc_ldadd_cleanup;
3139 cm->defer_db_open = 0;
3140 ca->ca_private = on;
3141 return LDAP_SUCCESS;
3145 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3147 CfEntryInfo *pe = p->e_private;
3148 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3149 cache_manager *cm = on->on_bi.bi_private;
3152 /* FIXME: should not hardcode "olcDatabase" here */
3153 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3154 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3155 0, cm->db.bd_info->bi_type );
3156 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3159 bv.bv_val = ca->cr_msg;
3161 cm->defer_db_open = 0;
3163 /* We can only create this entry if the database is table-driven
3165 if ( cm->db.bd_info->bi_cf_ocs )
3166 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3173 pc_cf_gen( ConfigArgs *c )
3175 slap_overinst *on = (slap_overinst *)c->bi;
3176 cache_manager* cm = on->on_bi.bi_private;
3177 query_manager* qm = cm->qm;
3178 QueryTemplate* temp;
3179 AttributeName* attr_name;
3180 AttributeName* attrarray;
3181 const char* text=NULL;
3186 if ( c->op == SLAP_CONFIG_EMIT ) {
3190 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3191 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3192 cm->num_entries_limit, cm->cc_period );
3193 bv.bv_val = c->cr_msg;
3194 value_add_one( &c->rvalue_vals, &bv );
3197 for (i=0; i<cm->numattrsets; i++) {
3198 if ( !qm->attr_sets[i].count ) continue;
3200 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3202 /* count the attr length */
3203 for ( attr_name = qm->attr_sets[i].attrs;
3204 attr_name->an_name.bv_val; attr_name++ )
3205 bv.bv_len += attr_name->an_name.bv_len + 1;
3207 bv.bv_val = ch_malloc( bv.bv_len+1 );
3208 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3209 for ( attr_name = qm->attr_sets[i].attrs;
3210 attr_name->an_name.bv_val; attr_name++ ) {
3212 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3214 ber_bvarray_add( &c->rvalue_vals, &bv );
3216 if ( !c->rvalue_vals )
3220 for (temp=qm->templates; temp; temp=temp->qmnext) {
3221 /* HEADS-UP: always print all;
3222 * if optional == 0, ignore */
3223 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3224 " %d %ld %ld %ld %ld",
3225 temp->attr_set_index,
3230 bv.bv_len += temp->querystr.bv_len + 2;
3231 bv.bv_val = ch_malloc( bv.bv_len+1 );
3234 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3236 strcpy( ptr, c->cr_msg );
3237 ber_bvarray_add( &c->rvalue_vals, &bv );
3239 if ( !c->rvalue_vals )
3243 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3244 BER_BVSTR( &bv, "head" );
3246 BER_BVSTR( &bv, "tail" );
3248 value_add_one( &c->rvalue_vals, &bv );
3251 c->value_int = cm->max_queries;
3254 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3258 } else if ( c->op == LDAP_MOD_DELETE ) {
3261 case PC_ATTR: /* FIXME */
3265 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3274 if ( cm->numattrsets > 0 ) {
3275 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
3276 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3280 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
3281 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
3283 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3286 if ( cm->numattrsets <= 0 ) {
3287 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
3288 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3291 if ( cm->numattrsets > MAX_ATTR_SETS ) {
3292 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
3293 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3297 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
3298 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
3299 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3303 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
3304 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
3306 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3309 if ( cm->max_entries <= 0 ) {
3310 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
3311 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
3315 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
3316 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
3318 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3321 if ( cm->num_entries_limit <= 0 ) {
3322 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
3323 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3326 if ( cm->num_entries_limit > cm->max_entries ) {
3327 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
3328 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3332 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3333 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
3335 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3339 cm->cc_period = (time_t)t;
3340 Debug( pcache_debug,
3341 "Total # of attribute sets to be cached = %d.\n",
3342 cm->numattrsets, 0, 0 );
3343 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
3344 sizeof( struct attr_set ) );
3347 if ( cm->numattrsets == 0 ) {
3348 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3349 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3352 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
3353 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
3355 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3359 if ( num < 0 || num >= cm->numattrsets ) {
3360 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
3361 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3362 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3365 qm->attr_sets[num].flags |= PC_CONFIGURED;
3366 if ( c->argc == 2 ) {
3368 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3369 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
3370 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3373 } else if ( c->argc == 3 ) {
3374 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3375 qm->attr_sets[num].count = 1;
3376 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3377 sizeof( AttributeName ) );
3378 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
3381 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3382 qm->attr_sets[num].count = 1;
3383 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
3384 sizeof( AttributeName ) );
3385 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3388 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
3391 /* else: fallthru */
3393 } else if ( c->argc == 4 ) {
3394 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
3395 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
3397 qm->attr_sets[num].count = 2;
3398 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
3399 sizeof( AttributeName ) );
3400 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
3401 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3404 /* else: fallthru */
3407 if ( c->argc > 2 ) {
3408 int all_user = 0, all_op = 0;
3410 qm->attr_sets[num].count = c->argc - 2;
3411 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
3412 sizeof( AttributeName ) );
3413 attr_name = qm->attr_sets[num].attrs;
3414 for ( i = 2; i < c->argc; i++ ) {
3415 attr_name->an_desc = NULL;
3416 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
3417 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3418 "invalid attr #%d \"%s\" in attrlist",
3419 i - 2, c->argv[i] );
3420 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3421 ch_free( qm->attr_sets[num].attrs );
3422 qm->attr_sets[num].attrs = NULL;
3423 qm->attr_sets[num].count = 0;
3426 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
3428 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
3429 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
3431 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
3433 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
3434 strcpy( c->cr_msg, text );
3435 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3436 ch_free( qm->attr_sets[num].attrs );
3437 qm->attr_sets[num].attrs = NULL;
3438 qm->attr_sets[num].count = 0;
3441 attr_name->an_name = attr_name->an_desc->ad_cname;
3443 attr_name->an_oc = NULL;
3444 attr_name->an_flags = 0;
3445 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
3446 qm->attr_sets[num].flags |= PC_GOT_OC;
3448 BER_BVZERO( &attr_name->an_name );
3451 /* warn if list contains both "*" and "+" */
3452 if ( i > 4 && all_user && all_op ) {
3453 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3454 "warning: attribute list contains \"*\" and \"+\"" );
3455 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3460 if ( cm->numattrsets == 0 ) {
3461 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
3462 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3465 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
3466 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
3468 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3472 if ( i < 0 || i >= cm->numattrsets ||
3473 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
3474 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
3475 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
3476 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3479 temp = ch_calloc( 1, sizeof( QueryTemplate ));
3480 temp->qmnext = qm->templates;
3481 qm->templates = temp;
3482 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
3483 temp->query = temp->query_last = NULL;
3484 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
3485 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3486 "unable to parse template ttl=\"%s\"",
3488 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3491 temp->ttl = (time_t)t;
3492 temp->negttl = (time_t)0;
3493 temp->limitttl = (time_t)0;
3494 temp->ttr = (time_t)0;
3495 switch ( c->argc ) {
3497 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
3498 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3499 "unable to parse template ttr=\"%s\"",
3501 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3504 temp->ttr = (time_t)t;
3508 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
3509 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3510 "unable to parse template sizelimit ttl=\"%s\"",
3512 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3515 temp->limitttl = (time_t)t;
3519 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
3520 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3521 "unable to parse template negative ttl=\"%s\"",
3523 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3526 temp->negttl = (time_t)t;
3530 temp->no_of_queries = 0;
3532 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
3533 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
3534 Debug( pcache_debug, " query template: %s\n",
3535 temp->querystr.bv_val, 0, 0 );
3536 temp->attr_set_index = i;
3537 qm->attr_sets[i].flags |= PC_REFERENCED;
3538 temp->qtnext = qm->attr_sets[i].templates;
3539 qm->attr_sets[i].templates = temp;
3540 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
3541 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
3542 for ( i=0; attrarray[i].an_name.bv_val; i++ )
3543 Debug( pcache_debug, "\t%s\n",
3544 attrarray[i].an_name.bv_val, 0, 0 );
3548 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
3549 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
3551 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
3552 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3555 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
3556 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3561 if ( c->value_int <= 0 ) {
3562 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3563 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3566 cm->max_queries = c->value_int;
3570 cm->cc_paused |= PCACHE_CC_OFFLINE;
3572 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3575 if ( cm->db.be_private == NULL ) {
3576 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3577 "private database must be defined before setting database specific options" );
3578 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3582 if ( cm->db.bd_info->bi_cf_ocs ) {
3585 char *argv0 = c->argv[ 0 ];
3587 c->argv[ 0 ] = &argv0[ STRLENOF( "proxycache-" ) ];
3589 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
3591 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3592 "private database does not recognize specific option '%s'",
3594 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3598 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
3600 c->bi = c->be->bd_info;
3602 rc = config_add_vals( ct, c );
3606 c->table = c2.table;
3609 c->argv[ 0 ] = argv0;
3611 } else if ( cm->db.be_config != NULL ) {
3612 char *argv0 = c->argv[ 0 ];
3614 c->argv[ 0 ] = &argv0[ STRLENOF( "proxycache-" ) ];
3615 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
3616 c->argv[ 0 ] = argv0;
3619 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3620 "no means to set private database specific options" );
3621 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3626 rc = SLAP_CONF_UNKNOWN;
3642 slap_overinst *on = (slap_overinst *)be->bd_info;
3643 cache_manager* cm = on->on_bi.bi_private;
3645 /* Something for the cache database? */
3646 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3647 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3649 return SLAP_CONF_UNKNOWN;
3657 slap_overinst *on = (slap_overinst *)be->bd_info;
3661 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3662 on->on_bi.bi_private = cm;
3664 qm = (query_manager*)ch_malloc(sizeof(query_manager));
3667 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3668 cm->db.be_private = NULL;
3669 cm->db.bd_self = &cm->db;
3671 cm->numattrsets = 0;
3672 cm->num_entries_limit = 5;
3673 cm->num_cached_queries = 0;
3674 cm->max_entries = 0;
3675 cm->cur_entries = 0;
3676 cm->max_queries = 10000;
3677 cm->save_queries = 0;
3678 cm->check_cacheability = 0;
3679 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3680 cm->defer_db_open = 1;
3681 cm->cc_period = 1000;
3685 qm->attr_sets = NULL;
3686 qm->templates = NULL;
3688 qm->lru_bottom = NULL;
3690 qm->qcfunc = query_containment;
3691 qm->crfunc = cache_replacement;
3692 qm->addfunc = add_query;
3693 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3695 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3700 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3702 assert( op->o_tag == LDAP_REQ_SEARCH );
3704 if ( rs->sr_type == REP_SEARCH ) {
3707 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3711 assert( a->a_nvals != NULL );
3713 valsp = op->o_callback->sc_private;
3714 assert( *valsp == NULL );
3716 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3724 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3726 assert( op->o_tag == LDAP_REQ_SEARCH );
3728 if ( rs->sr_type == REP_SEARCH ) {
3729 int *countp = (int *)op->o_callback->sc_private;
3742 cache_manager *cm = on->on_bi.bi_private;
3743 query_manager* qm = cm->qm;
3746 rc = backend_startup_one( &cm->db, cr );
3748 cm->defer_db_open = 0;
3751 /* There is no runqueue in TOOL mode */
3752 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
3753 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3754 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3755 consistency_check, on,
3756 "pcache_consistency", cm->db.be_suffix[0].bv_val );
3757 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3759 /* Cached database must have the rootdn */
3760 if ( BER_BVISNULL( &cm->db.be_rootndn )
3761 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3763 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3764 "underlying database of type \"%s\"\n"
3765 " serving naming context \"%s\"\n"
3766 " has no \"rootdn\", required by \"proxycache\".\n",
3767 on->on_info->oi_orig->bi_type,
3768 cm->db.be_suffix[0].bv_val, 0 );
3772 if ( cm->save_queries ) {
3773 void *thrctx = ldap_pvt_thread_pool_context();
3774 Connection conn = { 0 };
3775 OperationBuffer opbuf;
3777 slap_callback cb = { 0 };
3778 SlapReply rs = { 0 };
3779 BerVarray vals = NULL;
3780 Filter f = { 0 }, f2 = { 0 };
3781 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3782 AttributeName attrs[ 2 ] = {{{ 0 }}};
3784 connection_fake_init( &conn, &opbuf, thrctx );
3789 op->o_tag = LDAP_REQ_SEARCH;
3790 op->o_protocol = LDAP_VERSION3;
3791 cb.sc_response = pcache_cachedquery_open_cb;
3792 cb.sc_private = &vals;
3793 op->o_callback = &cb;
3794 op->o_time = slap_get_time();
3795 op->o_do_not_cache = 1;
3796 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3798 op->o_dn = cm->db.be_rootdn;
3799 op->o_ndn = cm->db.be_rootndn;
3800 op->o_req_dn = cm->db.be_suffix[ 0 ];
3801 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3803 op->ors_scope = LDAP_SCOPE_BASE;
3804 op->ors_deref = LDAP_DEREF_NEVER;
3806 op->ors_tlimit = SLAP_NO_LIMIT;
3807 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3808 f.f_choice = LDAP_FILTER_PRESENT;
3809 f.f_desc = ad_cachedQueryURL;
3810 op->ors_filter = &f;
3811 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3812 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3813 op->ors_attrs = attrs;
3814 op->ors_attrsonly = 0;
3816 rc = op->o_bd->be_search( op, &rs );
3817 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3820 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3821 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3822 cm->num_cached_queries++;
3826 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3829 /* count cached entries */
3830 f.f_choice = LDAP_FILTER_NOT;
3832 f2.f_choice = LDAP_FILTER_EQUALITY;
3834 f2.f_av_desc = slap_schema.si_ad_objectClass;
3835 BER_BVSTR( &f2.f_av_value, "glue" );
3836 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3838 op->ors_slimit = SLAP_NO_LIMIT;
3839 op->ors_scope = LDAP_SCOPE_SUBTREE;
3840 op->ors_attrs = slap_anlist_no_attrs;
3842 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3844 op->o_callback->sc_private = &rs.sr_nentries;
3846 rc = op->o_bd->be_search( op, &rs );
3848 cm->cur_entries = rs.sr_nentries;
3862 slap_overinst *on = (slap_overinst *)be->bd_info;
3863 cache_manager *cm = on->on_bi.bi_private;
3864 query_manager* qm = cm->qm;
3865 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3867 /* check attr sets */
3868 for ( i = 0; i < cm->numattrsets; i++) {
3869 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3870 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3871 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3875 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3879 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3880 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3885 if ( ncf || rf || nrf ) {
3886 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3887 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3888 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3895 /* need to inherit something from the original database... */
3896 cm->db.be_def_limit = be->be_def_limit;
3897 cm->db.be_limits = be->be_limits;
3898 cm->db.be_acl = be->be_acl;
3899 cm->db.be_dfltaccess = be->be_dfltaccess;
3901 if ( SLAP_DBMONITORING( be ) ) {
3902 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3905 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3908 if ( !cm->defer_db_open )
3909 rc = pcache_db_open2( on, cr );
3915 pcache_free_qbase( void *v )
3921 tavl_free( qb->scopes[i], NULL );
3931 slap_overinst *on = (slap_overinst *)be->bd_info;
3932 cache_manager *cm = on->on_bi.bi_private;
3933 query_manager *qm = cm->qm;
3937 if ( cm->save_queries ) {
3939 BerVarray vals = NULL;
3942 Connection conn = { 0 };
3943 OperationBuffer opbuf;
3945 slap_callback cb = { 0 };
3947 SlapReply rs = { REP_RESULT };
3948 Modifications mod = {{ 0 }};
3950 thrctx = ldap_pvt_thread_pool_context();
3952 connection_fake_init( &conn, &opbuf, thrctx );
3955 if ( qm->templates != NULL ) {
3956 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3957 for ( qc = tm->query; qc; qc = qc->next ) {
3960 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
3961 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3968 op->o_dn = cm->db.be_rootdn;
3969 op->o_ndn = cm->db.be_rootndn;
3971 op->o_tag = LDAP_REQ_MODIFY;
3972 op->o_protocol = LDAP_VERSION3;
3973 cb.sc_response = slap_null_cb;
3974 op->o_callback = &cb;
3975 op->o_time = slap_get_time();
3976 op->o_do_not_cache = 1;
3977 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3979 op->o_req_dn = op->o_bd->be_suffix[0];
3980 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3982 mod.sml_op = LDAP_MOD_REPLACE;
3984 mod.sml_desc = ad_cachedQueryURL;
3985 mod.sml_type = ad_cachedQueryURL->ad_cname;
3986 mod.sml_values = vals;
3987 mod.sml_nvalues = NULL;
3988 mod.sml_numvals = 1;
3989 mod.sml_next = NULL;
3990 Debug( pcache_debug,
3991 "%sSETTING CACHED QUERY URLS\n",
3992 vals == NULL ? "RE" : "", 0, 0 );
3994 op->orm_modlist = &mod;
3996 op->o_bd->be_modify( op, &rs );
3998 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4001 /* cleanup stuff inherited from the original database... */
4002 cm->db.be_limits = NULL;
4003 cm->db.be_acl = NULL;
4005 /* stop the thread ... */
4007 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4008 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4009 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4011 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4012 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4015 if ( cm->db.bd_info->bi_db_close ) {
4016 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4018 while ( (tm = qm->templates) != NULL ) {
4019 CachedQuery *qc, *qn;
4020 qm->templates = tm->qmnext;
4021 for ( qc = tm->query; qc; qc = qn ) {
4025 avl_free( tm->qbase, pcache_free_qbase );
4026 free( tm->querystr.bv_val );
4027 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4028 free( tm->t_attrs.attrs );
4032 for ( i=0; i<cm->numattrsets; i++ ) {
4033 free( qm->attr_sets[i].attrs );
4035 free( qm->attr_sets );
4036 qm->attr_sets = NULL;
4047 slap_overinst *on = (slap_overinst *)be->bd_info;
4048 cache_manager *cm = on->on_bi.bi_private;
4049 query_manager *qm = cm->qm;
4051 if ( cm->db.be_private != NULL ) {
4052 backend_stopdown_one( &cm->db );
4055 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4056 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4063 #ifdef PCACHE_CONTROL_PRIVDB
4065 Control ::= SEQUENCE {
4066 controlType LDAPOID,
4067 criticality BOOLEAN DEFAULT FALSE,
4068 controlValue OCTET STRING OPTIONAL }
4070 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4072 * criticality must be TRUE; controlValue must be absent.
4080 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
4081 rs->sr_text = "privateDB control specified multiple times";
4082 return LDAP_PROTOCOL_ERROR;
4085 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
4086 rs->sr_text = "privateDB control value not absent";
4087 return LDAP_PROTOCOL_ERROR;
4090 if ( !ctrl->ldctl_iscritical ) {
4091 rs->sr_text = "privateDB control criticality required";
4092 return LDAP_PROTOCOL_ERROR;
4095 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
4097 return LDAP_SUCCESS;
4100 static char *extops[] = {
4101 LDAP_EXOP_MODIFY_PASSWD,
4104 #endif /* PCACHE_CONTROL_PRIVDB */
4106 #ifdef PCACHE_EXOP_QUERY_DELETE
4107 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
4109 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
4110 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
4111 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
4114 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
4115 requestName [0] LDAPOID,
4116 requestValue [1] OCTET STRING OPTIONAL }
4118 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
4120 requestValue ::= SEQUENCE { CHOICE {
4122 entryDN [1] LDAPDN },
4123 queryID [2] OCTET STRING (SIZE(16))
4124 -- constrained to UUID }
4126 * Either baseDN or entryDN must be present, to allow database selection.
4128 * 1. if baseDN and queryID are present, then the query corresponding
4129 * to queryID is deleted;
4130 * 2. if baseDN is present and queryID is absent, then all queries
4132 * 3. if entryDN is present and queryID is absent, then all queries
4133 * corresponding to the queryID values present in entryDN are deleted;
4134 * 4. if entryDN and queryID are present, then all queries
4135 * corresponding to the queryID values present in entryDN are deleted,
4136 * but only if the value of queryID is contained in the entry;
4138 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
4139 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
4140 * or by removing the database files.
4142 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
4143 COMPONENTS OF LDAPResult,
4144 responseName [10] LDAPOID OPTIONAL,
4145 responseValue [11] OCTET STRING OPTIONAL }
4147 * responseName and responseValue must be absent.
4151 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
4152 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
4153 * - if ndn != NULL, it is set to the normalized DN in the request
4154 * corresponding to either the baseDN or the entryDN, according
4155 * to *tagp; memory is malloc'ed on the Operation's slab, and must
4156 * be freed by the caller.
4157 * - if uuid != NULL, it is set to point to the normalized UUID;
4158 * memory is malloc'ed on the Operation's slab, and must
4159 * be freed by the caller.
4162 pcache_parse_query_delete(
4166 struct berval *uuid,
4170 int rc = LDAP_SUCCESS;
4173 BerElementBuffer berbuf;
4174 BerElement *ber = (BerElement *)&berbuf;
4175 struct berval reqdata = BER_BVNULL;
4187 if ( in == NULL || in->bv_len == 0 ) {
4188 *text = "empty request data field in queryDelete exop";
4189 return LDAP_PROTOCOL_ERROR;
4192 ber_dupbv_x( &reqdata, in, ctx );
4194 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
4195 ber_init2( ber, &reqdata, 0 );
4197 tag = ber_scanf( ber, "{" /*}*/ );
4199 if ( tag == LBER_ERROR ) {
4200 Debug( LDAP_DEBUG_TRACE,
4201 "pcache_parse_query_delete: decoding error.\n",
4203 goto decoding_error;
4206 tag = ber_peek_tag( ber, &len );
4207 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
4208 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
4212 if ( ndn != NULL ) {
4215 tag = ber_scanf( ber, "m", &dn );
4216 if ( tag == LBER_ERROR ) {
4217 Debug( LDAP_DEBUG_TRACE,
4218 "pcache_parse_query_delete: DN parse failed.\n",
4220 goto decoding_error;
4223 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
4224 if ( rc != LDAP_SUCCESS ) {
4225 *text = "invalid DN in queryDelete exop request data";
4230 tag = ber_scanf( ber, "x" /* "m" */ );
4231 if ( tag == LBER_DEFAULT ) {
4232 goto decoding_error;
4236 tag = ber_peek_tag( ber, &len );
4239 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
4240 if ( uuid != NULL ) {
4242 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
4244 tag = ber_scanf( ber, "m", &bv );
4245 if ( tag == LBER_ERROR ) {
4246 Debug( LDAP_DEBUG_TRACE,
4247 "pcache_parse_query_delete: UUID parse failed.\n",
4249 goto decoding_error;
4252 if ( bv.bv_len != 16 ) {
4253 Debug( LDAP_DEBUG_TRACE,
4254 "pcache_parse_query_delete: invalid UUID length %lu.\n",
4255 (unsigned long)bv.bv_len, 0, 0 );
4256 goto decoding_error;
4259 rc = lutil_uuidstr_from_normalized(
4260 bv.bv_val, bv.bv_len,
4261 uuidbuf, sizeof( uuidbuf ) );
4263 goto decoding_error;
4265 ber_str2bv( uuidbuf, rc, 1, uuid );
4269 tag = ber_skip_tag( ber, &len );
4270 if ( tag == LBER_DEFAULT ) {
4271 goto decoding_error;
4275 Debug( LDAP_DEBUG_TRACE,
4276 "pcache_parse_query_delete: invalid UUID length %lu.\n",
4277 (unsigned long)len, 0, 0 );
4278 goto decoding_error;
4282 tag = ber_peek_tag( ber, &len );
4285 if ( tag != LBER_DEFAULT || len != 0 ) {
4287 Debug( LDAP_DEBUG_TRACE,
4288 "pcache_parse_query_delete: decoding error\n",
4290 rc = LDAP_PROTOCOL_ERROR;
4291 *text = "queryDelete data decoding error";
4294 if ( ndn && !BER_BVISNULL( ndn ) ) {
4295 slap_sl_free( ndn->bv_val, ctx );
4299 if ( uuid && !BER_BVISNULL( uuid ) ) {
4300 slap_sl_free( uuid->bv_val, ctx );
4305 if ( !BER_BVISNULL( &reqdata ) ) {
4306 ber_memfree_x( reqdata.bv_val, ctx );
4313 pcache_exop_query_delete(
4317 BackendDB *bd = op->o_bd;
4319 struct berval uuid = BER_BVNULL,
4321 char buf[ SLAP_TEXT_BUFLEN ];
4323 ber_tag_t tag = LBER_DEFAULT;
4325 if ( LogTest( LDAP_DEBUG_STATS ) ) {
4329 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
4330 &tag, &op->o_req_ndn, uuidp,
4331 &rs->sr_text, op->o_tmpmemctx );
4332 if ( rs->sr_err != LDAP_SUCCESS ) {
4336 if ( LogTest( LDAP_DEBUG_STATS ) ) {
4337 assert( !BER_BVISNULL( &op->o_req_ndn ) );
4338 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
4340 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
4341 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
4344 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
4345 op->o_log_prefix, buf, 0 );
4347 op->o_req_dn = op->o_req_ndn;
4349 op->o_bd = select_backend( &op->o_req_ndn, 0 );
4350 rs->sr_err = backend_check_restrictions( op, rs,
4351 (struct berval *)&pcache_exop_QUERY_DELETE );
4352 if ( rs->sr_err != LDAP_SUCCESS ) {
4356 if ( op->o_bd->be_extended == NULL ) {
4357 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
4358 "backend does not support extended operations" );
4362 op->o_bd->be_extended( op, rs );
4365 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
4366 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
4367 BER_BVZERO( &op->o_req_ndn );
4368 BER_BVZERO( &op->o_req_dn );
4371 if ( !BER_BVISNULL( &uuid ) ) {
4372 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
4381 pcache_op_extended( Operation *op, SlapReply *rs )
4383 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
4384 cache_manager *cm = on->on_bi.bi_private;
4386 #ifdef PCACHE_CONTROL_PRIVDB
4387 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
4388 return pcache_op_privdb( op, rs );
4390 #endif /* PCACHE_CONTROL_PRIVDB */
4392 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
4393 struct berval uuid = BER_BVNULL;
4394 ber_tag_t tag = LBER_DEFAULT;
4396 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
4397 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
4398 assert( rs->sr_err == LDAP_SUCCESS );
4400 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
4401 /* remove all queries related to the selected entry */
4402 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
4403 cm, &op->o_req_ndn, &uuid );
4405 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
4406 if ( !BER_BVISNULL( &uuid ) ) {
4407 /* remove the selected query */
4408 rs->sr_err = pcache_remove_query_from_cache( op,
4412 /* TODO: remove all queries */
4413 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4414 rs->sr_text = "deletion of all queries not implemented";
4418 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
4423 #endif /* PCACHE_EXOP_QUERY_DELETE */
4425 static slap_overinst pcache;
4427 static char *obsolete_names[] = {
4432 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4434 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
4439 struct berval debugbv = BER_BVC("pcache");
4441 code = slap_loglevel_get( &debugbv, &pcache_debug );
4446 #ifdef PCACHE_CONTROL_PRIVDB
4447 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
4448 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
4449 parse_privdb_ctrl, &privDB_cid );
4450 if ( code != LDAP_SUCCESS ) {
4451 Debug( LDAP_DEBUG_ANY,
4452 "pcache_initialize: failed to register control %s (%d)\n",
4453 PCACHE_CONTROL_PRIVDB, code, 0 );
4456 #endif /* PCACHE_CONTROL_PRIVDB */
4458 #ifdef PCACHE_EXOP_QUERY_DELETE
4459 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
4460 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
4462 if ( code != LDAP_SUCCESS ) {
4463 Debug( LDAP_DEBUG_ANY,
4464 "pcache_initialize: unable to register queryDelete exop: %d.\n",
4468 #endif /* PCACHE_EXOP_QUERY_DELETE */
4470 for ( i = 0; as[i].desc != NULL; i++ ) {
4471 code = register_at( as[i].desc, as[i].adp, 0 );
4473 Debug( LDAP_DEBUG_ANY,
4474 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
4477 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
4480 pcache.on_bi.bi_type = "pcache";
4481 pcache.on_bi.bi_obsolete_names = obsolete_names;
4482 pcache.on_bi.bi_db_init = pcache_db_init;
4483 pcache.on_bi.bi_db_config = pcache_db_config;
4484 pcache.on_bi.bi_db_open = pcache_db_open;
4485 pcache.on_bi.bi_db_close = pcache_db_close;
4486 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
4488 pcache.on_bi.bi_op_search = pcache_op_search;
4489 #ifdef PCACHE_CONTROL_PRIVDB
4490 pcache.on_bi.bi_op_bind = pcache_op_privdb;
4491 pcache.on_bi.bi_op_compare = pcache_op_privdb;
4492 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
4493 pcache.on_bi.bi_op_modify = pcache_op_privdb;
4494 pcache.on_bi.bi_op_add = pcache_op_privdb;
4495 pcache.on_bi.bi_op_delete = pcache_op_privdb;
4496 #endif /* PCACHE_CONTROL_PRIVDB */
4497 #ifdef PCACHE_EXOP_QUERY_DELETE
4498 pcache.on_bi.bi_extended = pcache_op_extended;
4499 #elif defined( PCACHE_CONTROL_PRIVDB )
4500 pcache.on_bi.bi_extended = pcache_op_privdb;
4503 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
4505 pcache.on_bi.bi_cf_ocs = pcocs;
4507 code = config_register_schema( pccfg, pcocs );
4508 if ( code ) return code;
4510 return overlay_register( &pcache );
4513 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
4514 int init_module(int argc, char *argv[]) {
4515 return pcache_initialize();
4519 #endif /* defined(SLAPD_OVER_PROXYCACHE) */