2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2007 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 valid */
78 struct cached_query_s *next; /* next query in the template */
79 struct cached_query_s *prev; /* previous query in the template */
80 struct cached_query_s *lru_up; /* previous query in the LRU list */
81 struct cached_query_s *lru_down; /* next query in the LRU list */
87 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
89 * <base> ::= CachedQuery.qbase->base
90 * <scope> ::= CachedQuery.scope
91 * <filter> ::= filter2bv(CachedQuery.filter)
92 * <uuid> ::= CachedQuery.q_uuid
93 * <attrset> ::= CachedQuery.qtemp->attr_set_index
94 * <expiry> ::= CachedQuery.expiry_time
96 * quick hack: parse URI, call add_query() and then fix
97 * CachedQuery.expiry_time and CachedQuery.q_uuid
101 * Represents a set of projected attributes.
105 struct query_template_s *templates;
106 AttributeName* attrs; /* specifies the set */
108 #define PC_CONFIGURED (0x1)
109 #define PC_REFERENCED (0x2)
110 #define PC_GOT_OC (0x4)
111 int count; /* number of attributes */
114 /* struct representing a query template
115 * e.g. template string = &(cn=)(mail=)
117 typedef struct query_template_s {
118 struct query_template_s *qtnext;
119 struct query_template_s *qmnext;
122 CachedQuery* query; /* most recent query cached for the template */
123 CachedQuery* query_last; /* oldest query cached for the template */
124 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
125 struct berval querystr; /* Filter string corresponding to the QT */
127 int attr_set_index; /* determines the projected attributes */
128 int no_of_queries; /* Total number of queries in the template */
129 time_t ttl; /* TTL for the queries of this template */
130 time_t negttl; /* TTL for negative results */
131 time_t limitttl; /* TTL for sizelimit exceeding results */
132 struct attr_set t_attrs; /* filter attrs + attr_set */
140 } pc_caching_reason_t;
142 static const char *pc_caching_reason_str[] = {
151 struct query_manager_s;
153 /* prototypes for functions for 1) query containment
154 * 2) query addition, 3) cache replacement
156 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
157 Query*, QueryTemplate*);
158 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
159 Query*, QueryTemplate*, pc_caching_reason_t);
160 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
162 /* LDAP query cache */
163 typedef struct query_manager_s {
164 struct attr_set* attr_sets; /* possible sets of projected attributes */
165 QueryTemplate* templates; /* cacheable templates */
167 CachedQuery* lru_top; /* top and bottom of LRU list */
168 CachedQuery* lru_bottom;
170 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
172 /* Query cache methods */
173 QCfunc *qcfunc; /* Query containment*/
174 CRfunc *crfunc; /* cache replacement */
175 AddQueryfunc *addfunc; /* add query */
178 /* LDAP query cache manager */
179 typedef struct cache_manager_s {
180 BackendDB db; /* underlying database */
181 unsigned long num_cached_queries; /* total number of cached queries */
182 unsigned long max_queries; /* upper bound on # of cached queries */
183 int save_queries; /* save cached queries across restarts */
184 int numattrsets; /* number of attribute sets */
185 int cur_entries; /* current number of entries cached */
186 int max_entries; /* max number of entries cached */
187 int num_entries_limit; /* max # of entries in a cacheable query */
189 char response_cb; /* install the response callback
190 * at the tail of the callback list */
191 #define PCACHE_RESPONSE_CB_HEAD 0
192 #define PCACHE_RESPONSE_CB_TAIL 1
194 time_t cc_period; /* interval between successive consistency checks (sec) */
198 ldap_pvt_thread_mutex_t cache_mutex;
200 query_manager* qm; /* query cache managed by the cache manager */
203 static int pcache_debug;
205 #ifdef PCACHE_CONTROL_PRIVDB
206 static int privDB_cid;
207 #endif /* PCACHE_CONTROL_PRIVDB */
209 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
212 AttributeDescription **adp;
214 { "( 1.3.6.1.4.1.4203.666.11.9.1.1 "
216 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
217 "EQUALITY octetStringMatch "
218 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
219 "NO-USER-MODIFICATION "
220 "USAGE directoryOperation )",
222 { "( 1.3.6.1.4.1.4203.666.11.9.1.2 "
223 "NAME 'cachedQueryURL' "
224 "DESC 'URI describing a cached query' "
225 "EQUALITY caseExactMatch "
226 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
227 "NO-USER-MODIFICATION "
228 "USAGE directoryOperation )",
229 &ad_cachedQueryURL },
238 AttributeName** filter_attrs,
240 int* filter_got_oc );
247 QueryTemplate *templ,
248 pc_caching_reason_t why );
254 struct berval *query_uuid );
257 * Turn a cached query into its URL representation
260 query2url( Operation *op, CachedQuery *q, struct berval *urlbv )
262 struct berval bv_scope,
264 char attrset_buf[ 32 ],
267 ber_len_t attrset_len,
270 ldap_pvt_scope2bv( q->scope, &bv_scope );
271 filter2bv_x( op, q->filter, &bv_filter );
272 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
273 "%lu", (unsigned long)q->qtemp->attr_set_index );
274 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
275 "%lu", (unsigned long)q->expiry_time );
277 urlbv->bv_len = STRLENOF( "ldap:///" )
278 + q->qbase->base.bv_len
283 + STRLENOF( "?x-uuid=" )
285 + STRLENOF( ",x-attrset=" )
287 + STRLENOF( ",x-expiry=" )
289 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
290 ptr = lutil_strcopy( ptr, "ldap:///" );
291 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
292 ptr = lutil_strcopy( ptr, "??" );
293 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
294 ptr = lutil_strcopy( ptr, "?" );
295 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
296 ptr = lutil_strcopy( ptr, "?x-uuid=" );
297 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
298 ptr = lutil_strcopy( ptr, ",x-attrset=" );
299 ptr = lutil_strcopy( ptr, attrset_buf );
300 ptr = lutil_strcopy( ptr, ",x-expiry=" );
301 ptr = lutil_strcopy( ptr, expiry_buf );
303 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
309 * Turn an URL representing a formerly cached query into a cached query,
310 * and try to cache it
321 LDAPURLDesc *lud = NULL;
323 tempstr = BER_BVNULL,
333 rc = ldap_url_parse( url, &lud );
334 if ( rc != LDAP_URL_SUCCESS ) {
338 /* non-allowed fields */
339 if ( lud->lud_host != NULL ) {
344 if ( lud->lud_attrs != NULL ) {
350 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
355 /* required fields */
356 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
361 switch ( lud->lud_scope ) {
362 case LDAP_SCOPE_BASE:
363 case LDAP_SCOPE_ONELEVEL:
364 case LDAP_SCOPE_SUBTREE:
365 case LDAP_SCOPE_SUBORDINATE:
373 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
378 if ( lud->lud_exts == NULL ) {
383 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
384 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
385 struct berval tmpUUID;
386 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
388 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
389 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
390 if ( rc != LDAP_SUCCESS ) {
395 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
396 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
402 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
405 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
409 expiry_time = (time_t)l;
423 if ( !got_attrset ) {
433 /* ignore expired queries */
434 if ( expiry_time <= slap_get_time()) {
436 SlapReply rs2 = { 0 };
438 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
440 (void)remove_query_data( &op2, &rs2, &uuid );
445 ber_str2bv( lud->lud_dn, 0, 0, &base );
446 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
447 if ( rc != LDAP_SUCCESS ) {
450 query.scope = lud->lud_scope;
451 query.filter = str2filter( lud->lud_filter );
453 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
455 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
456 ch_free( tempstr.bv_val );
461 /* check for query containment */
462 qt = qm->attr_sets[attrset].templates;
463 for ( ; qt; qt = qt->qtnext ) {
464 /* find if template i can potentially answer tempstr */
465 if ( bvmatch( &qt->querystr, &tempstr ) ) {
475 cq = add_query( op, qm, &query, qt, PC_POSITIVE );
477 cq->expiry_time = expiry_time;
480 /* it's now into cq->filter */
490 if ( query.filter != NULL ) filter_free( query.filter );
491 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
492 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
493 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
494 if ( lud != NULL ) ldap_free_urldesc( lud );
499 /* Return 1 for an added entry, else 0 */
504 struct berval* query_uuid )
507 Modifications* modlist = NULL;
508 const char* text = NULL;
510 char textbuf[SLAP_TEXT_BUFLEN];
511 size_t textlen = sizeof(textbuf);
513 SlapReply sreply = {REP_RESULT};
515 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
520 /* add queryId attribute */
521 attr_merge_one( e, ad_queryId, query_uuid, NULL );
523 /* append the attribute list from the fetched entry */
524 e->e_attrs->a_next = attr;
526 op->o_tag = LDAP_REQ_ADD;
527 op->o_protocol = LDAP_VERSION3;
528 op->o_callback = &cb;
529 op->o_time = slap_get_time();
530 op->o_do_not_cache = 1;
533 op->o_req_dn = e->e_name;
534 op->o_req_ndn = e->e_nname;
535 rc = op->o_bd->be_add( op, &sreply );
537 if ( rc != LDAP_SUCCESS ) {
538 if ( rc == LDAP_ALREADY_EXISTS ) {
539 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
540 modlist->sml_op = LDAP_MOD_ADD;
541 op->o_tag = LDAP_REQ_MODIFY;
542 op->orm_modlist = modlist;
543 op->o_bd->be_modify( op, &sreply );
544 slap_mods_free( modlist, 1 );
545 } else if ( rc == LDAP_REFERRAL ||
546 rc == LDAP_NO_SUCH_OBJECT ) {
547 syncrepl_add_glue( op, e );
556 if ( op->ora_e == e )
557 be_entry_release_w( op, e );
564 /* Length-ordered sort on normalized DNs */
565 static int pcache_dn_cmp( const void *v1, const void *v2 )
567 const Qbase *q1 = v1, *q2 = v2;
569 int rc = q1->base.bv_len - q2->base.bv_len;
571 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
575 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
578 dif = bv1->bv_len - bv2->bv_len;
580 if ( dif > 0 ) len -= dif;
581 len = memcmp( bv1->bv_val, bv2->bv_val, len );
587 /* compare the first value in each filter */
588 static int pcache_filter_cmp( const void *v1, const void *v2 )
590 const CachedQuery *q1 = v1, *q2 =v2;
591 int rc, weight1, weight2;
593 switch( q1->first->f_choice ) {
594 case LDAP_FILTER_PRESENT:
597 case LDAP_FILTER_EQUALITY:
605 switch( q2->first->f_choice ) {
606 case LDAP_FILTER_PRESENT:
609 case LDAP_FILTER_EQUALITY:
617 rc = weight1 - weight2;
622 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
625 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
627 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
628 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
629 rc = lex_bvcmp( &q1->first->f_sub_initial,
630 &q2->first->f_sub_initial );
634 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
638 if ( q1->first->f_sub_any ) {
639 if ( q2->first->f_sub_any ) {
640 rc = lex_bvcmp( q1->first->f_sub_any,
641 q2->first->f_sub_any );
645 } else if ( q2->first->f_sub_any ) {
649 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
650 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
651 rc = lex_bvcmp( &q1->first->f_sub_final,
652 &q2->first->f_sub_final );
656 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
660 rc = lex_bvcmp( &q1->first->f_mr_value,
661 &q2->first->f_mr_value );
670 /* add query on top of LRU list */
672 add_query_on_top (query_manager* qm, CachedQuery* qc)
674 CachedQuery* top = qm->lru_top;
685 Debug( pcache_debug, "Base of added query = %s\n",
686 qc->qbase->base.bv_val, 0, 0 );
689 /* remove_query from LRU list */
692 remove_query (query_manager* qm, CachedQuery* qc)
715 qc->lru_up = qc->lru_down = NULL;
718 /* find and remove string2 from string1
719 * from start if position = 1,
720 * from end if position = 3,
721 * from anywhere if position = 2
722 * string1 is overwritten if position = 2.
726 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
737 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
738 ber2->bv_val, ber2->bv_len )) {
740 ber1->bv_val += ber2->bv_len;
741 ber1->bv_len -= ber2->bv_len;
746 ber1->bv_val[ber1->bv_len] = '\0';
747 temp = strstr( ber1->bv_val, ber2->bv_val );
749 strcpy( temp, temp+ber2->bv_len );
750 ber1->bv_len -= ber2->bv_len;
756 if ( ber1->bv_len >= ber2->bv_len &&
757 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
760 ber1->bv_len -= ber2->bv_len;
768 static struct berval*
769 merge_init_final(Operation *op, struct berval* init, struct berval* any,
770 struct berval* final)
772 struct berval* merged, *temp;
773 int i, any_count, count;
775 for (any_count=0; any && any[any_count].bv_val; any_count++)
785 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
790 ber_dupbv_x( temp, init, op->o_tmpmemctx );
794 for (i=0; i<any_count; i++) {
795 ber_dupbv_x( temp, any, op->o_tmpmemctx );
800 ber_dupbv_x( temp, final, op->o_tmpmemctx );
807 /* Each element in stored must be found in incoming. Incoming is overwritten.
810 strings_containment(struct berval* stored, struct berval* incoming)
812 struct berval* element;
816 for ( element=stored; element->bv_val != NULL; element++ ) {
817 for (j = k; incoming[j].bv_val != NULL; j++) {
818 if (find_and_remove(&(incoming[j]), element, 2)) {
835 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
839 struct berval init_incoming;
840 struct berval final_incoming;
841 struct berval *remaining_incoming = NULL;
843 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
844 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
847 init_incoming = incoming->f_sub_initial;
848 final_incoming = incoming->f_sub_final;
850 if (find_and_remove(&init_incoming,
851 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
852 &(stored->f_sub_final), 3))
854 if (stored->f_sub_any == NULL) {
858 remaining_incoming = merge_init_final(op, &init_incoming,
859 incoming->f_sub_any, &final_incoming);
860 rc = strings_containment(stored->f_sub_any, remaining_incoming);
861 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
868 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
870 struct berval incoming_val[2];
873 incoming_val[1] = incoming->f_av_value;
875 if (find_and_remove(incoming_val+1,
876 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
877 &(stored->f_sub_final), 3)) {
878 if (stored->f_sub_any == NULL){
882 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
883 BER_BVZERO( incoming_val+1 );
884 rc = strings_containment(stored->f_sub_any, incoming_val);
885 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
892 filter_first( Filter *f )
894 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
901 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
905 MatchingRule* mrule = NULL;
906 int res=0, eqpass= 0;
914 /* substring matches sort to the end, and we just have to
915 * walk the entire list.
917 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
918 ptr = tavl_end( root, 1 );
921 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
922 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
931 /* an incoming substr query can only be satisfied by a cached
934 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
935 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
938 /* an incoming eq query can be satisfied by a cached eq or substr
941 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
943 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
944 nextpass: eqpass = 1;
945 ptr = tavl_end( root, 1 );
950 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
956 switch (fs->f_choice) {
957 case LDAP_FILTER_EQUALITY:
958 if (fi->f_choice == LDAP_FILTER_EQUALITY)
959 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
965 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
972 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
973 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
974 &(fi->f_ava->aa_value),
975 &(fs->f_ava->aa_value), &text);
976 if (rc != LDAP_SUCCESS) {
979 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
982 switch (fs->f_choice) {
984 case LDAP_FILTER_AND:
989 case LDAP_FILTER_SUBSTRINGS:
990 /* check if the equality query can be
991 * answered with cached substring query */
992 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
993 && substr_containment_equality( op,
996 /* check if the substring query can be
997 * answered with cached substring query */
998 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
999 ) && substr_containment_substr( op,
1005 case LDAP_FILTER_PRESENT:
1010 case LDAP_FILTER_EQUALITY:
1016 case LDAP_FILTER_GE:
1017 if (mrule && ret >= 0)
1022 case LDAP_FILTER_LE:
1023 if (mrule && ret <= 0)
1028 case LDAP_FILTER_NOT:
1034 } while((res) && (fi != NULL) && (fs != NULL));
1038 ptr = tavl_next( ptr, dir );
1043 /* check whether query is contained in any of
1044 * the cached queries in template
1046 static CachedQuery *
1047 query_containment(Operation *op, query_manager *qm,
1049 QueryTemplate *templa)
1052 int depth = 0, tscope;
1053 Qbase qbase, *qbptr = NULL;
1056 if (query->filter != NULL) {
1059 Debug( pcache_debug, "Lock QC index = %p\n",
1060 (void *) templa, 0, 0 );
1061 qbase.base = query->base;
1063 first = filter_first( query->filter );
1065 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1068 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1070 tscope = query->scope;
1071 /* Find a matching scope:
1072 * match at depth 0 OK
1075 * subord at depth > 0 OK
1076 * subtree at any depth OK
1078 * subtree or subord at any depth OK
1080 * subtree or subord at any depth OK
1082 * subord at depth > 0 OK
1083 * subtree at any depth OK
1085 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1086 switch ( query->scope ) {
1087 case LDAP_SCOPE_BASE:
1088 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1089 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1090 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1092 case LDAP_SCOPE_ONE:
1093 if ( tscope == LDAP_SCOPE_BASE )
1094 tscope = LDAP_SCOPE_ONE;
1095 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1096 if ( !depth ) break;
1097 if ( tscope < LDAP_SCOPE_SUBTREE )
1098 tscope = LDAP_SCOPE_SUBTREE;
1100 case LDAP_SCOPE_SUBTREE:
1101 if ( tscope < LDAP_SCOPE_SUBTREE )
1102 tscope = LDAP_SCOPE_SUBTREE;
1103 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1105 case LDAP_SCOPE_CHILDREN:
1106 if ( tscope < LDAP_SCOPE_SUBTREE )
1107 tscope = LDAP_SCOPE_SUBTREE;
1110 if ( !qbptr->scopes[tscope] ) continue;
1113 qc = find_filter( op, qbptr->scopes[tscope],
1114 query->filter, first );
1116 if ( qc->q_sizelimit ) {
1117 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1120 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1121 if (qm->lru_top != qc) {
1122 remove_query(qm, qc);
1123 add_query_on_top(qm, qc);
1125 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1130 if ( be_issuffix( op->o_bd, &qbase.base ))
1133 dnParent( &qbase.base, &pdn );
1138 Debug( pcache_debug,
1139 "Not answerable: Unlock QC index=%p\n",
1140 (void *) templa, 0, 0 );
1141 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1147 free_query (CachedQuery* qc)
1149 free(qc->q_uuid.bv_val);
1150 filter_free(qc->filter);
1155 /* Add query to query cache */
1156 static CachedQuery *
1161 QueryTemplate *templ,
1162 pc_caching_reason_t why )
1164 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1170 new_cached_query->qtemp = templ;
1171 BER_BVZERO( &new_cached_query->q_uuid );
1172 new_cached_query->q_sizelimit = 0;
1180 ttl = templ->negttl;
1184 ttl = templ->limitttl;
1191 new_cached_query->expiry_time = slap_get_time() + ttl;
1192 new_cached_query->lru_up = NULL;
1193 new_cached_query->lru_down = NULL;
1194 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1195 (long) new_cached_query->expiry_time,
1196 pc_caching_reason_str[ why ], 0 );
1198 new_cached_query->scope = query->scope;
1199 new_cached_query->filter = query->filter;
1200 new_cached_query->first = first = filter_first( query->filter );
1202 qb.base = query->base;
1204 /* Adding a query */
1205 Debug( pcache_debug, "Lock AQ index = %p\n",
1206 (void *) templ, 0, 0 );
1207 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1208 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1210 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1211 qbase->base.bv_len = qb.base.bv_len;
1212 qbase->base.bv_val = (char *)(qbase+1);
1213 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1214 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1215 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1217 new_cached_query->next = templ->query;
1218 new_cached_query->prev = NULL;
1219 new_cached_query->qbase = qbase;
1220 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1221 pcache_filter_cmp, avl_dup_error );
1224 if (templ->query == NULL)
1225 templ->query_last = new_cached_query;
1227 templ->query->prev = new_cached_query;
1228 templ->query = new_cached_query;
1229 templ->no_of_queries++;
1231 ch_free( new_cached_query );
1232 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1233 query->filter, first );
1234 filter_free( query->filter );
1236 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1237 (void *) templ, templ->no_of_queries, 0 );
1239 Debug( pcache_debug, "Unlock AQ index = %p \n",
1240 (void *) templ, 0, 0 );
1241 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1243 /* Adding on top of LRU list */
1245 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1246 add_query_on_top(qm, new_cached_query);
1247 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1249 return rc == 0 ? new_cached_query : NULL;
1253 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1255 if (!qc->prev && !qc->next) {
1256 template->query_last = template->query = NULL;
1257 } else if (qc->prev == NULL) {
1258 qc->next->prev = NULL;
1259 template->query = qc->next;
1260 } else if (qc->next == NULL) {
1261 qc->prev->next = NULL;
1262 template->query_last = qc->prev;
1264 qc->next->prev = qc->prev;
1265 qc->prev->next = qc->next;
1267 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1268 qc->qbase->queries--;
1269 if ( qc->qbase->queries == 0 ) {
1270 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1271 ch_free( qc->qbase );
1275 template->no_of_queries--;
1278 /* remove bottom query of LRU list from the query cache */
1280 * NOTE: slight change in functionality.
1282 * - if result->bv_val is NULL, the query at the bottom of the LRU
1284 * - otherwise, the query whose UUID is *result is removed
1285 * - if not found, result->bv_val is zeroed
1288 cache_replacement(query_manager* qm, struct berval *result)
1290 CachedQuery* bottom;
1291 QueryTemplate *temp;
1293 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1294 if ( BER_BVISNULL( result ) ) {
1295 bottom = qm->lru_bottom;
1298 Debug ( pcache_debug,
1299 "Cache replacement invoked without "
1300 "any query in LRU list\n", 0, 0, 0 );
1301 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1306 for ( bottom = qm->lru_bottom;
1308 bottom = bottom->lru_up )
1310 if ( bvmatch( result, &bottom->q_uuid ) ) {
1316 Debug ( pcache_debug,
1317 "Could not find query with uuid=\"%s\""
1318 "in LRU list\n", result->bv_val, 0, 0 );
1319 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1320 BER_BVZERO( result );
1325 temp = bottom->qtemp;
1326 remove_query(qm, bottom);
1327 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1329 *result = bottom->q_uuid;
1330 BER_BVZERO( &bottom->q_uuid );
1332 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1333 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1334 remove_from_template(bottom, temp);
1335 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1336 (void *) temp, temp->no_of_queries, 0 );
1337 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1338 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1343 struct query_info *next;
1355 struct query_info *qi;
1358 if ( rs->sr_type != REP_SEARCH ) return 0;
1360 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1361 if ( attr == NULL ) return 0;
1363 for ( count = 0; !BER_BVISNULL( &attr->a_vals[count] ); count++ )
1365 assert( count > 0 );
1366 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1367 qi->next = op->o_callback->sc_private;
1368 op->o_callback->sc_private = qi;
1369 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1370 qi->del = ( count == 1 );
1379 struct berval *query_uuid )
1381 struct query_info *qi, *qnext;
1382 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1383 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1384 Filter filter = {LDAP_FILTER_EQUALITY};
1385 SlapReply sreply = {REP_RESULT};
1386 slap_callback cb = { NULL, remove_func, NULL, NULL };
1389 sreply.sr_entry = NULL;
1390 sreply.sr_nentries = 0;
1391 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1392 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1393 filter.f_ava = &ava;
1394 filter.f_av_desc = ad_queryId;
1395 filter.f_av_value = *query_uuid;
1397 op->o_tag = LDAP_REQ_SEARCH;
1398 op->o_protocol = LDAP_VERSION3;
1399 op->o_callback = &cb;
1400 op->o_time = slap_get_time();
1401 op->o_do_not_cache = 1;
1403 op->o_req_dn = op->o_bd->be_suffix[0];
1404 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1405 op->ors_scope = LDAP_SCOPE_SUBTREE;
1406 op->ors_deref = LDAP_DEREF_NEVER;
1407 op->ors_slimit = SLAP_NO_LIMIT;
1408 op->ors_tlimit = SLAP_NO_LIMIT;
1409 op->ors_filter = &filter;
1410 op->ors_filterstr.bv_val = filter_str;
1411 op->ors_filterstr.bv_len = strlen(filter_str);
1412 op->ors_attrs = NULL;
1413 op->ors_attrsonly = 0;
1415 op->o_bd->be_search( op, &sreply );
1417 for ( qi=cb.sc_private; qi; qi=qnext ) {
1420 op->o_req_dn = qi->xdn;
1421 op->o_req_ndn = qi->xdn;
1424 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1425 query_uuid->bv_val, 0, 0 );
1427 op->o_tag = LDAP_REQ_DELETE;
1429 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1435 struct berval vals[2];
1437 vals[0] = *query_uuid;
1438 vals[1].bv_val = NULL;
1440 mod.sml_op = LDAP_MOD_DELETE;
1442 mod.sml_desc = ad_queryId;
1443 mod.sml_type = ad_queryId->ad_cname;
1444 mod.sml_values = vals;
1445 mod.sml_nvalues = NULL;
1446 mod.sml_next = NULL;
1447 Debug( pcache_debug,
1448 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1449 query_uuid->bv_val, 0, 0 );
1451 op->orm_modlist = &mod;
1453 op->o_bd->be_modify( op, &sreply );
1455 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1456 op->o_tmpfree( qi, op->o_tmpmemctx );
1463 AttributeName* attrs,
1472 struct berval *fstr,
1473 AttributeName** filter_attrs,
1475 int* filter_got_oc )
1477 AttributeDescription *ad;
1479 switch ( f->f_choice ) {
1480 case LDAP_FILTER_EQUALITY:
1482 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1483 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1486 case LDAP_FILTER_GE:
1488 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1489 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1492 case LDAP_FILTER_LE:
1494 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1495 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1498 case LDAP_FILTER_APPROX:
1500 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1501 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1504 case LDAP_FILTER_SUBSTRINGS:
1506 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1507 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1510 case LDAP_FILTER_PRESENT:
1512 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1513 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1516 case LDAP_FILTER_AND:
1517 case LDAP_FILTER_OR:
1518 case LDAP_FILTER_NOT: {
1520 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1521 f->f_choice == LDAP_FILTER_AND ? '&' :
1522 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1523 fstr->bv_len += sizeof("(%") - 1;
1525 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1526 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1530 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1531 fstr->bv_len += sizeof(")") - 1;
1537 strcpy( fstr->bv_val, "(?=?)" );
1538 fstr->bv_len += sizeof("(?=?)")-1;
1542 if ( filter_attrs != NULL ) {
1543 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1544 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1546 (*filter_attrs)[*filter_cnt].an_desc = ad;
1547 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1548 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1549 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1550 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1552 if ( ad == slap_schema.si_ad_objectClass )
1559 struct search_info {
1562 QueryTemplate *qtemp;
1563 AttributeName* save_attrs; /* original attributes, saved for response */
1568 int slimit_exceeded;
1573 remove_query_and_data(
1577 struct berval *uuid )
1579 query_manager* qm = cm->qm;
1581 qm->crfunc( qm, uuid );
1582 if ( !BER_BVISNULL( uuid ) ) {
1585 Debug( pcache_debug,
1586 "Removing query UUID %s\n",
1587 uuid->bv_val, 0, 0 );
1588 return_val = remove_query_data( op, rs, uuid );
1589 Debug( pcache_debug,
1590 "QUERY REMOVED, SIZE=%d\n",
1592 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1593 cm->cur_entries -= return_val;
1594 cm->num_cached_queries--;
1595 Debug( pcache_debug,
1596 "STORED QUERIES = %lu\n",
1597 cm->num_cached_queries, 0, 0 );
1598 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1599 Debug( pcache_debug,
1600 "QUERY REMOVED, CACHE ="
1602 cm->cur_entries, 0, 0 );
1607 * Callback used to fetch queryId values based on entryUUID;
1608 * used by pcache_remove_entries_from_cache()
1611 fetch_queryId_cb( Operation *op, SlapReply *rs )
1615 /* only care about searchEntry responses */
1616 if ( rs->sr_type != REP_SEARCH ) {
1620 /* allow only one response per entryUUID */
1621 if ( op->o_callback->sc_private != NULL ) {
1627 /* copy all queryId values into callback's private data */
1628 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1630 BerVarray vals = NULL;
1632 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1633 op->o_callback->sc_private = (void *)vals;
1637 /* clear entry if required */
1638 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1639 entry_free( rs->sr_entry );
1640 rs->sr_entry = NULL;
1641 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1648 * Call that allows to remove a set of entries from the cache,
1649 * by forcing the removal of all the related queries.
1652 pcache_remove_entries_from_cache(
1655 BerVarray entryUUIDs )
1657 Connection conn = { 0 };
1658 OperationBuffer opbuf;
1660 slap_callback sc = { 0 };
1661 SlapReply rs = { REP_RESULT };
1663 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1664 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1665 AttributeName attrs[ 2 ] = { 0 };
1669 void *thrctx = ldap_pvt_thread_pool_context();
1671 connection_fake_init( &conn, &opbuf, thrctx );
1679 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1680 op->ors_scope = LDAP_SCOPE_SUBTREE;
1681 op->ors_deref = LDAP_DEREF_NEVER;
1682 f.f_choice = LDAP_FILTER_EQUALITY;
1684 ava.aa_desc = slap_schema.si_ad_entryUUID;
1685 op->ors_filter = &f;
1687 op->ors_tlimit = SLAP_NO_LIMIT;
1688 attrs[ 0 ].an_desc = ad_queryId;
1689 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1690 op->ors_attrs = attrs;
1691 op->ors_attrsonly = 0;
1693 op->o_req_dn = cm->db.be_suffix[ 0 ];
1694 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1696 op->o_tag = LDAP_REQ_SEARCH;
1697 op->o_protocol = LDAP_VERSION3;
1698 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1700 op->o_dn = op->o_bd->be_rootdn;
1701 op->o_ndn = op->o_bd->be_rootndn;
1702 sc.sc_response = fetch_queryId_cb;
1703 op->o_callback = ≻
1705 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1706 BerVarray vals = NULL;
1708 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1709 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1710 op->ors_filterstr.bv_val = filtbuf;
1711 ava.aa_value = entryUUIDs[ s ];
1713 rc = op->o_bd->be_search( op, &rs );
1714 if ( rc != LDAP_SUCCESS ) {
1718 vals = (BerVarray)op->o_callback->sc_private;
1719 if ( vals != NULL ) {
1722 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1723 struct berval val = vals[ i ];
1725 remove_query_and_data( op, &rs, cm, &val );
1727 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1728 ch_free( val.bv_val );
1732 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1733 op->o_callback->sc_private = NULL;
1741 * Call that allows to remove a query from the cache.
1744 pcache_remove_query_from_cache(
1747 struct berval *queryid )
1749 Operation op2 = *op;
1750 SlapReply rs2 = { 0 };
1754 /* remove the selected query */
1755 remove_query_and_data( &op2, &rs2, cm, queryid );
1757 return LDAP_SUCCESS;
1761 * Call that allows to remove a set of queries related to an entry
1762 * from the cache; if queryid is not null, the entry must belong to
1763 * the query indicated by queryid.
1766 pcache_remove_entry_queries_from_cache(
1770 struct berval *queryid )
1772 Connection conn = { 0 };
1773 OperationBuffer opbuf;
1775 slap_callback sc = { 0 };
1776 SlapReply rs = { REP_RESULT };
1778 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1779 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1780 AttributeName attrs[ 2 ] = { 0 };
1783 BerVarray vals = NULL;
1786 void *thrctx = ldap_pvt_thread_pool_context();
1788 connection_fake_init( &conn, &opbuf, thrctx );
1796 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1797 op->ors_scope = LDAP_SCOPE_BASE;
1798 op->ors_deref = LDAP_DEREF_NEVER;
1799 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1800 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1801 f.f_choice = LDAP_FILTER_PRESENT;
1802 f.f_desc = slap_schema.si_ad_objectClass;
1805 op->ors_filterstr.bv_len = snprintf( filter_str,
1806 sizeof( filter_str ), "(%s=%s)",
1807 ad_queryId->ad_cname.bv_val, queryid->bv_val );
1808 f.f_choice = LDAP_FILTER_EQUALITY;
1810 f.f_av_desc = ad_queryId;
1811 f.f_av_value = *queryid;
1813 op->ors_filter = &f;
1815 op->ors_tlimit = SLAP_NO_LIMIT;
1816 attrs[ 0 ].an_desc = ad_queryId;
1817 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1818 op->ors_attrs = attrs;
1819 op->ors_attrsonly = 0;
1821 op->o_req_dn = *ndn;
1822 op->o_req_ndn = *ndn;
1824 op->o_tag = LDAP_REQ_SEARCH;
1825 op->o_protocol = LDAP_VERSION3;
1826 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1828 op->o_dn = op->o_bd->be_rootdn;
1829 op->o_ndn = op->o_bd->be_rootndn;
1830 sc.sc_response = fetch_queryId_cb;
1831 op->o_callback = ≻
1833 rc = op->o_bd->be_search( op, &rs );
1834 if ( rc != LDAP_SUCCESS ) {
1838 vals = (BerVarray)op->o_callback->sc_private;
1839 if ( vals != NULL ) {
1842 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1843 struct berval val = vals[ i ];
1845 remove_query_and_data( op, &rs, cm, &val );
1847 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1848 ch_free( val.bv_val );
1852 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1855 return LDAP_SUCCESS;
1862 struct berval *query_uuid )
1864 struct search_info *si = op->o_callback->sc_private;
1865 slap_overinst *on = si->on;
1866 cache_manager *cm = on->on_bi.bi_private;
1869 struct berval crp_uuid;
1870 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1871 Operation op_tmp = *op;
1873 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1874 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1876 op_tmp.o_bd = &cm->db;
1877 op_tmp.o_dn = cm->db.be_rootdn;
1878 op_tmp.o_ndn = cm->db.be_rootndn;
1880 Debug( pcache_debug, "UUID for query being added = %s\n",
1883 for ( e=si->head; e; e=si->head ) {
1884 si->head = e->e_private;
1885 e->e_private = NULL;
1886 while ( cm->cur_entries > (cm->max_entries) ) {
1887 BER_BVZERO( &crp_uuid );
1888 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1891 return_val = merge_entry(&op_tmp, e, query_uuid);
1892 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1893 cm->cur_entries += return_val;
1894 Debug( pcache_debug,
1895 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1896 cm->cur_entries, 0, 0 );
1898 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1905 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1906 slap_callback *cb = op->o_callback;
1907 struct search_info *si = cb->sc_private;
1909 if ( rs->sr_type == REP_SEARCH ) {
1910 /* don't return more entries than requested by the client */
1911 if ( si->slimit && rs->sr_nentries >= si->slimit ) {
1912 si->slimit_exceeded = 1;
1916 if ( rs->sr_type == REP_RESULT ||
1918 rs->sr_err == SLAPD_ABANDON )
1920 if ( si->save_attrs != NULL ) {
1921 rs->sr_attrs = si->save_attrs;
1922 op->ors_attrs = si->save_attrs;
1924 op->o_callback = op->o_callback->sc_next;
1925 op->o_tmpfree( cb, op->o_tmpmemctx );
1928 return SLAP_CB_CONTINUE;
1936 struct search_info *si = op->o_callback->sc_private;
1937 slap_overinst *on = si->on;
1938 cache_manager *cm = on->on_bi.bi_private;
1939 query_manager* qm = cm->qm;
1941 if ( si->save_attrs != NULL ) {
1942 rs->sr_attrs = si->save_attrs;
1943 op->ors_attrs = si->save_attrs;
1946 if ( rs->sr_type == REP_SEARCH ) {
1948 /* If we haven't exceeded the limit for this query,
1949 * build a chain of answers to store. If we hit the
1950 * limit, empty the chain and ignore the rest.
1953 if ( si->count < si->max ) {
1955 e = entry_dup( rs->sr_entry );
1956 if ( !si->head ) si->head = e;
1957 if ( si->tail ) si->tail->e_private = e;
1963 for (;si->head; si->head=e) {
1964 e = si->head->e_private;
1965 si->head->e_private = NULL;
1966 entry_free(si->head);
1972 /* don't return more entries than requested by the client */
1973 if ( si->slimit_exceeded ) {
1977 } else if ( rs->sr_type == REP_RESULT ) {
1978 pc_caching_reason_t why = PC_IGNORE;
1981 if ( rs->sr_err == LDAP_SUCCESS ) {
1984 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
1985 && si->qtemp->limitttl )
1990 } else if ( si->qtemp->negttl && !si->count && !si->over &&
1991 rs->sr_err == LDAP_SUCCESS )
1996 if ( why != PC_IGNORE ) {
1997 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2003 cache_entries( op, rs, &qc->q_uuid );
2007 qc->q_sizelimit = rs->sr_nentries;
2010 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2011 cm->num_cached_queries++;
2012 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2013 cm->num_cached_queries, 0, 0 );
2014 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2016 /* If the consistency checker suspended itself,
2019 if ( cm->cc_paused ) {
2020 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2021 if ( cm->cc_paused ) {
2023 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2025 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2028 } else if ( si->count ) {
2029 /* duplicate query, free it */
2031 for (;si->head; si->head=e) {
2032 e = si->head->e_private;
2033 si->head->e_private = NULL;
2034 entry_free(si->head);
2039 filter_free( si->query.filter );
2042 if ( si->slimit_exceeded ) {
2043 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2047 return SLAP_CB_CONTINUE;
2053 AttributeName** new_attrs,
2054 struct attr_set *attrs,
2055 AttributeName* filter_attrs,
2065 /* duplicate attrs */
2066 count = attrs->count + fattr_cnt;
2067 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2072 *new_attrs = (AttributeName*)ch_calloc( count + 1,
2073 sizeof(AttributeName) );
2074 for (i=0; i<attrs->count; i++) {
2075 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2076 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2078 BER_BVZERO( &(*new_attrs)[i].an_name );
2079 alluser = an_find(*new_attrs, &AllUser);
2080 allop = an_find(*new_attrs, &AllOper);
2083 for ( i=0; i<fattr_cnt; i++ ) {
2084 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2087 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2091 } else if ( alluser ) {
2094 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2095 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2096 (*new_attrs)[j].an_oc = NULL;
2097 (*new_attrs)[j].an_oc_exclude = 0;
2101 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2102 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2103 (*new_attrs)[j].an_oc = NULL;
2104 (*new_attrs)[j].an_oc_exclude = 0;
2107 BER_BVZERO( &(*new_attrs)[j].an_name );
2112 /* NOTE: this is a quick workaround to let pcache minimally interact
2113 * with pagedResults. A more articulated solutions would be to
2114 * perform the remote query without control and cache all results,
2115 * performing the pagedResults search only within the client
2116 * and the proxy. This requires pcache to understand pagedResults. */
2118 pcache_chk_controls(
2122 const char *non = "";
2123 const char *stripped = "";
2125 switch( op->o_pagedresults ) {
2126 case SLAP_CONTROL_NONCRITICAL:
2128 stripped = "; stripped";
2131 case SLAP_CONTROL_CRITICAL:
2132 Debug( pcache_debug, "%s: "
2133 "%scritical pagedResults control "
2134 "disabled with proxy cache%s.\n",
2135 op->o_log_prefix, non, stripped );
2137 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2141 rs->sr_err = SLAP_CB_CONTINUE;
2148 #ifdef PCACHE_CONTROL_PRIVDB
2154 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2155 cache_manager *cm = on->on_bi.bi_private;
2156 slap_callback *save_cb;
2159 /* skip if control is unset */
2160 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2161 return SLAP_CB_CONTINUE;
2164 /* FIXME: might be a little bit exaggerated... */
2165 if ( !be_isroot( op ) ) {
2166 save_cb = op->o_callback;
2167 op->o_callback = NULL;
2168 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2169 "pcachePrivDB: operation not allowed" );
2170 op->o_callback = save_cb;
2175 /* map tag to operation */
2176 type = slap_req2op( op->o_tag );
2177 if ( type != SLAP_OP_LAST ) {
2181 /* execute, if possible */
2182 func = &cm->db.be_bind;
2183 if ( func[ type ] != NULL ) {
2184 Operation op2 = *op;
2188 rc = func[ type ]( &op2, rs );
2189 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2190 op->o_conn->c_authz_cookie = cm->db.be_private;
2195 /* otherwise fall back to error */
2196 save_cb = op->o_callback;
2197 op->o_callback = NULL;
2198 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2199 "operation not supported with pcachePrivDB control" );
2200 op->o_callback = save_cb;
2204 #endif /* PCACHE_CONTROL_PRIVDB */
2211 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2212 cache_manager *cm = on->on_bi.bi_private;
2213 query_manager* qm = cm->qm;
2217 AttributeName *filter_attrs = NULL;
2220 QueryTemplate *qtemp = NULL;
2223 CachedQuery *answerable = NULL;
2226 int fattr_got_oc = 0;
2228 struct berval tempstr;
2230 #ifdef PCACHE_CONTROL_PRIVDB
2231 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2232 return pcache_op_privdb( op, rs );
2234 #endif /* PCACHE_CONTROL_PRIVDB */
2236 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2238 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2239 &fattr_cnt, &fattr_got_oc )) {
2240 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2241 return SLAP_CB_CONTINUE;
2244 Debug( pcache_debug, "query template of incoming query = %s\n",
2245 tempstr.bv_val, 0, 0 );
2247 /* FIXME: cannot cache/answer requests with pagedResults control */
2250 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2252 query.filter = op->ors_filter;
2253 query.base = op->o_req_ndn;
2254 query.scope = op->ors_scope;
2256 /* check for query containment */
2257 if (attr_set > -1) {
2258 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2259 for (; qt; qt = qt->qtnext ) {
2260 /* find if template i can potentially answer tempstr */
2261 if (qt->querystr.bv_len != tempstr.bv_len ||
2262 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2266 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2267 op->ors_filterstr.bv_val, 0, 0 );
2268 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2274 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2277 /* Need to clear the callbacks of the original operation,
2278 * in case there are other overlays */
2279 BackendDB *save_bd = op->o_bd;
2280 slap_callback *save_cb = op->o_callback;
2282 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2283 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2284 if ( BER_BVISNULL( &answerable->q_uuid )) {
2285 /* No entries cached, just an empty result set */
2287 send_ldap_result( op, rs );
2290 op->o_callback = NULL;
2291 i = cm->db.bd_info->bi_op_search( op, rs );
2293 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2295 op->o_callback = save_cb;
2299 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2301 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2302 if (cm->num_cached_queries >= cm->max_queries) {
2305 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2307 if (op->ors_attrsonly)
2312 struct search_info *si;
2314 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2315 query.filter = filter_dup(op->ors_filter, NULL);
2316 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2317 if ( !qtemp->t_attrs.count ) {
2318 qtemp->t_attrs.count = add_filter_attrs(op,
2319 &qtemp->t_attrs.attrs,
2320 &qm->attr_sets[attr_set],
2321 filter_attrs, fattr_cnt, fattr_got_oc);
2323 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2325 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2326 cb->sc_response = pcache_response;
2327 cb->sc_cleanup = pcache_op_cleanup;
2328 cb->sc_private = (cb+1);
2329 si = cb->sc_private;
2333 si->max = cm->num_entries_limit ;
2337 si->slimit_exceeded = 0;
2338 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2339 si->slimit = op->ors_slimit;
2340 op->ors_slimit = cm->num_entries_limit;
2344 si->save_attrs = op->ors_attrs;
2346 op->ors_attrs = qtemp->t_attrs.attrs;
2348 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2349 cb->sc_next = op->o_callback;
2350 op->o_callback = cb;
2353 slap_callback **pcb;
2355 /* need to move the callback at the end, in case other
2356 * overlays are present, so that the final entry is
2357 * actually cached */
2359 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2364 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2368 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2370 return SLAP_CB_CONTINUE;
2375 AttributeName* attrs,
2383 for ( ; attrs[count].an_name.bv_val; count++ );
2386 /* recognize a single "*" or a "1.1" */
2389 attrs = slap_anlist_all_user_attributes;
2391 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2396 for ( i = 0; i < num; i++ ) {
2400 if ( count > qm->attr_sets[i].count ) {
2405 if ( !qm->attr_sets[i].count ) {
2411 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2412 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2435 struct re_s *rtask = arg;
2436 slap_overinst *on = rtask->arg;
2437 cache_manager *cm = on->on_bi.bi_private;
2438 query_manager *qm = cm->qm;
2439 Connection conn = {0};
2440 OperationBuffer opbuf;
2443 SlapReply rs = {REP_RESULT};
2445 int return_val, pause = 1;
2446 QueryTemplate* templ;
2448 connection_fake_init( &conn, &opbuf, ctx );
2452 op->o_dn = cm->db.be_rootdn;
2453 op->o_ndn = cm->db.be_rootndn;
2457 for (templ = qm->templates; templ; templ=templ->qmnext) {
2458 query = templ->query_last;
2459 if ( query ) pause = 0;
2460 op->o_time = slap_get_time();
2461 while (query && (query->expiry_time < op->o_time)) {
2463 Debug( pcache_debug, "Lock CR index = %p\n",
2464 (void *) templ, 0, 0 );
2465 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2466 if ( query == templ->query_last ) {
2468 remove_from_template(query, templ);
2469 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2470 (void *) templ, templ->no_of_queries, 0 );
2471 Debug( pcache_debug, "Unlock CR index = %p\n",
2472 (void *) templ, 0, 0 );
2474 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2476 query = templ->query_last;
2479 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2480 remove_query(qm, query);
2481 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2482 if ( BER_BVISNULL( &query->q_uuid ))
2485 return_val = remove_query_data(op, &rs, &query->q_uuid);
2486 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2488 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2489 cm->cur_entries -= return_val;
2490 cm->num_cached_queries--;
2491 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2492 cm->num_cached_queries, 0, 0 );
2493 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2494 Debug( pcache_debug,
2495 "STALE QUERY REMOVED, CACHE ="
2497 cm->cur_entries, 0, 0 );
2499 query = templ->query_last;
2502 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2503 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2504 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2506 /* If there were no queries, defer processing for a while */
2507 cm->cc_paused = pause;
2508 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2510 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2515 #define MAX_ATTR_SETS 500
2525 static ConfigDriver pc_cf_gen;
2526 static ConfigLDAPadd pc_ldadd;
2527 static ConfigCfAdd pc_cfadd;
2529 static ConfigTable pccfg[] = {
2530 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2532 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2533 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2534 "DESC 'ProxyCache basic parameters' "
2535 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2536 { "proxyattrset", "index> <attributes...",
2537 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2538 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2539 "DESC 'A set of attributes to cache' "
2540 "SYNTAX OMsDirectoryString )", NULL, NULL },
2541 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2542 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2543 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2544 "DESC 'Filter template, attrset, cache TTL, "
2545 "optional negative TTL, optional sizelimit TTL' "
2546 "SYNTAX OMsDirectoryString )", NULL, NULL },
2547 { "response-callback", "head|tail(default)",
2548 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2549 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2550 "DESC 'Response callback position in overlay stack' "
2551 "SYNTAX OMsDirectoryString )", NULL, NULL },
2552 { "proxyCacheQueries", "queries",
2553 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2554 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2555 "DESC 'Maximum number of queries to cache' "
2556 "SYNTAX OMsInteger )", NULL, NULL },
2557 { "proxySaveQueries", "TRUE|FALSE",
2558 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2559 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2560 "DESC 'Save cached queries for hot restart' "
2561 "SYNTAX OMsBoolean )", NULL, NULL },
2563 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2566 static ConfigOCs pcocs[] = {
2567 { "( OLcfgOvOc:2.1 "
2568 "NAME 'olcPcacheConfig' "
2569 "DESC 'ProxyCache configuration' "
2570 "SUP olcOverlayConfig "
2571 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2572 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2573 Cft_Overlay, pccfg, NULL, pc_cfadd },
2574 { "( OLcfgOvOc:2.2 "
2575 "NAME 'olcPcacheDatabase' "
2576 "DESC 'Cache database configuration' "
2577 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2582 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2587 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2588 p->ce_bi->bi_cf_ocs != pcocs )
2589 return LDAP_CONSTRAINT_VIOLATION;
2591 on = (slap_overinst *)p->ce_bi;
2592 cm = on->on_bi.bi_private;
2594 return LDAP_SUCCESS;
2598 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2600 CfEntryInfo *pe = p->e_private;
2601 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2602 cache_manager *cm = on->on_bi.bi_private;
2605 /* FIXME: should not hardcode "olcDatabase" here */
2606 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2607 bv.bv_val = ca->cr_msg;
2610 /* We can only create this entry if the database is table-driven
2612 if ( cm->db.bd_info->bi_cf_ocs )
2613 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2620 pc_cf_gen( ConfigArgs *c )
2622 slap_overinst *on = (slap_overinst *)c->bi;
2623 cache_manager* cm = on->on_bi.bi_private;
2624 query_manager* qm = cm->qm;
2625 QueryTemplate* temp;
2626 AttributeName* attr_name;
2627 AttributeName* attrarray;
2628 const char* text=NULL;
2633 if ( c->op == SLAP_CONFIG_EMIT ) {
2637 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2638 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2639 cm->num_entries_limit, cm->cc_period );
2640 bv.bv_val = c->cr_msg;
2641 value_add_one( &c->rvalue_vals, &bv );
2644 for (i=0; i<cm->numattrsets; i++) {
2645 if ( !qm->attr_sets[i].count ) continue;
2647 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2649 /* count the attr length */
2650 for ( attr_name = qm->attr_sets[i].attrs;
2651 attr_name->an_name.bv_val; attr_name++ )
2652 bv.bv_len += attr_name->an_name.bv_len + 1;
2654 bv.bv_val = ch_malloc( bv.bv_len+1 );
2655 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2656 for ( attr_name = qm->attr_sets[i].attrs;
2657 attr_name->an_name.bv_val; attr_name++ ) {
2659 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2661 ber_bvarray_add( &c->rvalue_vals, &bv );
2663 if ( !c->rvalue_vals )
2667 for (temp=qm->templates; temp; temp=temp->qmnext) {
2668 /* HEADS-UP: always print all;
2669 * if optional == 0, ignore */
2670 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2672 temp->attr_set_index,
2676 bv.bv_len += temp->querystr.bv_len + 2;
2677 bv.bv_val = ch_malloc( bv.bv_len+1 );
2680 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2682 strcpy( ptr, c->cr_msg );
2683 ber_bvarray_add( &c->rvalue_vals, &bv );
2685 if ( !c->rvalue_vals )
2689 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2690 BER_BVSTR( &bv, "head" );
2692 BER_BVSTR( &bv, "tail" );
2694 value_add_one( &c->rvalue_vals, &bv );
2697 c->value_int = cm->max_queries;
2701 } else if ( c->op == LDAP_MOD_DELETE ) {
2702 return 1; /* FIXME */
2714 if ( cm->numattrsets > 0 ) {
2715 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2716 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2720 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2721 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2723 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2726 if ( cm->numattrsets <= 0 ) {
2727 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2728 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2731 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2732 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2733 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2737 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2738 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2739 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2743 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2744 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2746 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2749 if ( cm->max_entries <= 0 ) {
2750 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2751 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2755 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2756 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2758 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2761 if ( cm->num_entries_limit <= 0 ) {
2762 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2763 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2766 if ( cm->num_entries_limit > cm->max_entries ) {
2767 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2768 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2772 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2773 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2775 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2778 cm->cc_period = (time_t)t;
2779 Debug( pcache_debug,
2780 "Total # of attribute sets to be cached = %d.\n",
2781 cm->numattrsets, 0, 0 );
2782 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2783 sizeof( struct attr_set ) );
2786 if ( cm->numattrsets == 0 ) {
2787 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2788 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2791 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2792 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2794 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2798 if ( num < 0 || num >= cm->numattrsets ) {
2799 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2800 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2801 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2804 qm->attr_sets[num].flags |= PC_CONFIGURED;
2805 if ( c->argc == 2 ) {
2807 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2808 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2809 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2812 } else if ( c->argc == 3 ) {
2813 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2814 qm->attr_sets[num].count = 1;
2815 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2816 sizeof( AttributeName ) );
2817 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2820 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2821 qm->attr_sets[num].count = 1;
2822 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2823 sizeof( AttributeName ) );
2824 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2827 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2830 /* else: fallthru */
2832 } else if ( c->argc == 4 ) {
2833 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2834 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2836 qm->attr_sets[num].count = 2;
2837 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2838 sizeof( AttributeName ) );
2839 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2840 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2843 /* else: fallthru */
2846 if ( c->argc > 2 ) {
2847 int all_user = 0, all_op = 0;
2849 qm->attr_sets[num].count = c->argc - 2;
2850 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2851 sizeof( AttributeName ) );
2852 attr_name = qm->attr_sets[num].attrs;
2853 for ( i = 2; i < c->argc; i++ ) {
2854 attr_name->an_desc = NULL;
2855 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2856 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2857 "invalid attr #%d \"%s\" in attrlist",
2858 i - 2, c->argv[i] );
2859 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2860 ch_free( qm->attr_sets[num].attrs );
2861 qm->attr_sets[num].attrs = NULL;
2862 qm->attr_sets[num].count = 0;
2865 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2867 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2868 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2870 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2872 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2873 strcpy( c->cr_msg, text );
2874 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2875 ch_free( qm->attr_sets[num].attrs );
2876 qm->attr_sets[num].attrs = NULL;
2877 qm->attr_sets[num].count = 0;
2880 attr_name->an_name = attr_name->an_desc->ad_cname;
2882 attr_name->an_oc = NULL;
2883 attr_name->an_oc_exclude = 0;
2884 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2885 qm->attr_sets[num].flags |= PC_GOT_OC;
2887 BER_BVZERO( &attr_name->an_name );
2890 /* warn if list contains both "*" and "+" */
2891 if ( i > 4 && all_user && all_op ) {
2892 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2893 "warning: attribute list contains \"*\" and \"+\"" );
2894 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2899 if ( cm->numattrsets == 0 ) {
2900 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2901 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2904 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2905 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2907 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2911 if ( i < 0 || i >= cm->numattrsets ||
2912 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2913 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2914 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2915 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2918 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2919 temp->qmnext = qm->templates;
2920 qm->templates = temp;
2921 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2922 temp->query = temp->query_last = NULL;
2923 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2924 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2925 "unable to parse template ttl=\"%s\"",
2927 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2930 temp->ttl = (time_t)t;
2931 temp->negttl = (time_t)0;
2932 temp->limitttl = (time_t)0;
2933 switch ( c->argc ) {
2935 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2936 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2937 "unable to parse template sizelimit ttl=\"%s\"",
2939 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2942 temp->limitttl = (time_t)t;
2946 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2947 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2948 "unable to parse template negative ttl=\"%s\"",
2950 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2953 temp->negttl = (time_t)t;
2957 temp->no_of_queries = 0;
2959 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2960 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2961 Debug( pcache_debug, " query template: %s\n",
2962 temp->querystr.bv_val, 0, 0 );
2963 temp->attr_set_index = i;
2964 qm->attr_sets[i].flags |= PC_REFERENCED;
2965 temp->qtnext = qm->attr_sets[i].templates;
2966 qm->attr_sets[i].templates = temp;
2967 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2968 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2969 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2970 Debug( pcache_debug, "\t%s\n",
2971 attrarray[i].an_name.bv_val, 0, 0 );
2975 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2976 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2978 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2979 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2982 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2983 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2988 if ( c->value_int <= 0 ) {
2989 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2990 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2993 cm->max_queries = c->value_int;
3008 slap_overinst *on = (slap_overinst *)be->bd_info;
3009 cache_manager* cm = on->on_bi.bi_private;
3011 /* Something for the cache database? */
3012 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3013 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3015 return SLAP_CONF_UNKNOWN;
3023 slap_overinst *on = (slap_overinst *)be->bd_info;
3027 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3028 on->on_bi.bi_private = cm;
3030 qm = (query_manager*)ch_malloc(sizeof(query_manager));
3033 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3034 cm->db.be_private = NULL;
3035 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
3037 cm->numattrsets = 0;
3038 cm->num_entries_limit = 5;
3039 cm->num_cached_queries = 0;
3040 cm->max_entries = 0;
3041 cm->cur_entries = 0;
3042 cm->max_queries = 10000;
3043 cm->save_queries = 0;
3044 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3045 cm->cc_period = 1000;
3048 qm->attr_sets = NULL;
3049 qm->templates = NULL;
3051 qm->lru_bottom = NULL;
3053 qm->qcfunc = query_containment;
3054 qm->crfunc = cache_replacement;
3055 qm->addfunc = add_query;
3056 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3058 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3063 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3065 assert( op->o_tag == LDAP_REQ_SEARCH );
3067 if ( rs->sr_type == REP_SEARCH ) {
3070 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3074 assert( a->a_nvals != NULL );
3076 valsp = op->o_callback->sc_private;
3077 assert( *valsp == NULL );
3079 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3087 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3089 assert( op->o_tag == LDAP_REQ_SEARCH );
3091 if ( rs->sr_type == REP_SEARCH ) {
3092 int *countp = (int *)op->o_callback->sc_private;
3105 slap_overinst *on = (slap_overinst *)be->bd_info;
3106 cache_manager *cm = on->on_bi.bi_private;
3107 query_manager* qm = cm->qm;
3108 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3110 /* check attr sets */
3111 for ( i = 0; i < cm->numattrsets; i++) {
3112 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3113 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3114 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3118 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3122 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3123 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3128 if ( ncf || rf || nrf ) {
3129 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3130 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3131 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3138 /* need to inherit something from the original database... */
3139 cm->db.be_def_limit = be->be_def_limit;
3140 cm->db.be_limits = be->be_limits;
3141 cm->db.be_acl = be->be_acl;
3142 cm->db.be_dfltaccess = be->be_dfltaccess;
3144 if ( SLAP_DBMONITORING( be ) ) {
3145 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3148 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3151 rc = backend_startup_one( &cm->db, NULL );
3153 /* There is no runqueue in TOOL mode */
3154 if ( slapMode & SLAP_SERVER_MODE ) {
3155 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3156 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3157 consistency_check, on,
3158 "pcache_consistency", be->be_suffix[0].bv_val );
3159 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3161 /* Cached database must have the rootdn */
3162 if ( BER_BVISNULL( &cm->db.be_rootndn )
3163 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3165 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3166 "underlying database of type \"%s\"\n"
3167 " serving naming context \"%s\"\n"
3168 " has no \"rootdn\", required by \"proxycache\".\n",
3169 on->on_info->oi_orig->bi_type,
3170 cm->db.be_suffix[0].bv_val, 0 );
3174 if ( cm->save_queries ) {
3175 void *thrctx = ldap_pvt_thread_pool_context();
3176 Connection conn = { 0 };
3177 OperationBuffer opbuf;
3179 slap_callback cb = { 0 };
3180 SlapReply rs = { 0 };
3181 BerVarray vals = NULL;
3182 Filter f = { 0 }, f2 = { 0 };
3183 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3184 AttributeName attrs[ 2 ] = { 0 };
3186 connection_fake_init( &conn, &opbuf, thrctx );
3191 op->o_tag = LDAP_REQ_SEARCH;
3192 op->o_protocol = LDAP_VERSION3;
3193 cb.sc_response = pcache_cachedquery_open_cb;
3194 cb.sc_private = &vals;
3195 op->o_callback = &cb;
3196 op->o_time = slap_get_time();
3197 op->o_do_not_cache = 1;
3198 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3200 op->o_dn = cm->db.be_rootdn;
3201 op->o_ndn = cm->db.be_rootndn;
3202 op->o_req_dn = cm->db.be_suffix[ 0 ];
3203 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3205 op->ors_scope = LDAP_SCOPE_BASE;
3206 op->ors_deref = LDAP_DEREF_NEVER;
3208 op->ors_tlimit = SLAP_NO_LIMIT;
3209 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3210 f.f_choice = LDAP_FILTER_PRESENT;
3211 f.f_desc = ad_cachedQueryURL;
3212 op->ors_filter = &f;
3213 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3214 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3215 op->ors_attrs = attrs;
3216 op->ors_attrsonly = 0;
3218 rc = op->o_bd->be_search( op, &rs );
3219 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3222 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3223 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3224 cm->num_cached_queries++;
3228 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3231 /* count cached entries */
3232 f.f_choice = LDAP_FILTER_NOT;
3234 f2.f_choice = LDAP_FILTER_EQUALITY;
3236 f2.f_av_desc = slap_schema.si_ad_objectClass;
3237 BER_BVSTR( &f2.f_av_value, "glue" );
3238 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3240 op->ors_slimit = SLAP_NO_LIMIT;
3241 op->ors_scope = LDAP_SCOPE_SUBTREE;
3242 op->ors_attrs = slap_anlist_no_attrs;
3244 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3246 op->o_callback->sc_private = &rs.sr_nentries;
3248 rc = op->o_bd->be_search( op, &rs );
3250 cm->cur_entries = rs.sr_nentries;
3261 pcache_free_qbase( void *v )
3267 tavl_free( qb->scopes[i], NULL );
3277 slap_overinst *on = (slap_overinst *)be->bd_info;
3278 cache_manager *cm = on->on_bi.bi_private;
3279 query_manager *qm = cm->qm;
3283 if ( cm->save_queries ) {
3285 BerVarray vals = NULL;
3288 Connection conn = { 0 };
3289 OperationBuffer opbuf;
3291 slap_callback cb = { 0 };
3293 SlapReply rs = { REP_RESULT };
3294 Modifications mod = { 0 };
3296 thrctx = ldap_pvt_thread_pool_context();
3298 connection_fake_init( &conn, &opbuf, thrctx );
3301 if ( qm->templates != NULL ) {
3302 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3303 for ( qc = tm->query; qc; qc = qc->next ) {
3306 if ( query2url( op, qc, &bv ) == 0 ) {
3307 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3314 op->o_dn = cm->db.be_rootdn;
3315 op->o_ndn = cm->db.be_rootndn;
3317 op->o_tag = LDAP_REQ_MODIFY;
3318 op->o_protocol = LDAP_VERSION3;
3319 cb.sc_response = slap_null_cb;
3320 op->o_callback = &cb;
3321 op->o_time = slap_get_time();
3322 op->o_do_not_cache = 1;
3323 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3325 op->o_req_dn = op->o_bd->be_suffix[0];
3326 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3328 mod.sml_op = LDAP_MOD_REPLACE;
3330 mod.sml_desc = ad_cachedQueryURL;
3331 mod.sml_type = ad_cachedQueryURL->ad_cname;
3332 mod.sml_values = vals;
3333 mod.sml_nvalues = NULL;
3334 mod.sml_next = NULL;
3335 Debug( pcache_debug,
3336 "%sSETTING CACHED QUERY URLS\n",
3337 vals == NULL ? "RE" : "", 0, 0 );
3339 op->orm_modlist = &mod;
3341 op->o_bd->be_modify( op, &rs );
3343 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3346 /* cleanup stuff inherited from the original database... */
3347 cm->db.be_limits = NULL;
3348 cm->db.be_acl = NULL;
3350 /* stop the thread ... */
3352 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3353 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3354 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3356 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3357 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3360 if ( cm->db.bd_info->bi_db_close ) {
3361 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3363 while ( (tm = qm->templates) != NULL ) {
3364 CachedQuery *qc, *qn;
3365 qm->templates = tm->qmnext;
3366 for ( qc = tm->query; qc; qc = qn ) {
3370 avl_free( tm->qbase, pcache_free_qbase );
3371 free( tm->querystr.bv_val );
3372 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3373 free( tm->t_attrs.attrs );
3377 for ( i=0; i<cm->numattrsets; i++ ) {
3378 free( qm->attr_sets[i].attrs );
3380 free( qm->attr_sets );
3381 qm->attr_sets = NULL;
3392 slap_overinst *on = (slap_overinst *)be->bd_info;
3393 cache_manager *cm = on->on_bi.bi_private;
3394 query_manager *qm = cm->qm;
3396 if ( cm->db.be_private != NULL ) {
3397 backend_stopdown_one( &cm->db );
3400 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3401 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3408 #ifdef PCACHE_CONTROL_PRIVDB
3410 Control ::= SEQUENCE {
3411 controlType LDAPOID,
3412 criticality BOOLEAN DEFAULT FALSE,
3413 controlValue OCTET STRING OPTIONAL }
3415 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3417 * criticality must be TRUE; controlValue must be absent.
3425 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3426 rs->sr_text = "privateDB control specified multiple times";
3427 return LDAP_PROTOCOL_ERROR;
3430 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3431 rs->sr_text = "privateDB control value not absent";
3432 return LDAP_PROTOCOL_ERROR;
3435 if ( !ctrl->ldctl_iscritical ) {
3436 rs->sr_text = "privateDB control criticality required";
3437 return LDAP_PROTOCOL_ERROR;
3440 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3442 return LDAP_SUCCESS;
3445 static char *extops[] = {
3446 LDAP_EXOP_MODIFY_PASSWD,
3449 #endif /* PCACHE_CONTROL_PRIVDB */
3451 #ifdef PCACHE_EXOP_QUERY_DELETE
3452 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3454 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3455 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3456 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3459 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3460 requestName [0] LDAPOID,
3461 requestValue [1] OCTET STRING OPTIONAL }
3463 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3465 requestValue ::= SEQUENCE { CHOICE {
3467 entryDN [1] LDAPDN },
3468 queryID [2] OCTET STRING (SIZE(16))
3469 -- constrained to UUID }
3471 * Either baseDN or entryDN must be present, to allow database selection.
3473 * 1. if baseDN and queryID are present, then the query corresponding
3474 * to queryID is deleted;
3475 * 2. if baseDN is present and queryID is absent, then all queries
3477 * 3. if entryDN is present and queryID is absent, then all queries
3478 * corresponding to the queryID values present in entryDN are deleted;
3479 * 4. if entryDN and queryID are present, then all queries
3480 * corresponding to the queryID values present in entryDN are deleted,
3481 * but only if the value of queryID is contained in the entry;
3483 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3484 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3485 * or by removing the database files.
3487 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3488 COMPONENTS OF LDAPResult,
3489 responseName [10] LDAPOID OPTIONAL,
3490 responseValue [11] OCTET STRING OPTIONAL }
3492 * responseName and responseValue must be absent.
3496 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3497 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3498 * - if ndn != NULL, it is set to the normalized DN in the request
3499 * corresponding to either the baseDN or the entryDN, according
3500 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3501 * be freed by the caller.
3502 * - if uuid != NULL, it is set to point to the normalized UUID;
3503 * memory is malloc'ed on the Operation's slab, and must
3504 * be freed by the caller.
3507 pcache_parse_query_delete(
3511 struct berval *uuid,
3515 int rc = LDAP_SUCCESS;
3518 BerElementBuffer berbuf;
3519 BerElement *ber = (BerElement *)&berbuf;
3520 struct berval reqdata = BER_BVNULL;
3532 if ( in == NULL || in->bv_len == 0 ) {
3533 *text = "empty request data field in queryDelete exop";
3534 return LDAP_PROTOCOL_ERROR;
3537 ber_dupbv_x( &reqdata, in, ctx );
3539 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3540 ber_init2( ber, &reqdata, 0 );
3542 tag = ber_scanf( ber, "{" /*}*/ );
3544 if ( tag == LBER_ERROR ) {
3545 Debug( LDAP_DEBUG_TRACE,
3546 "pcache_parse_query_delete: decoding error.\n",
3548 goto decoding_error;
3551 tag = ber_peek_tag( ber, &len );
3552 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3553 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3557 if ( ndn != NULL ) {
3560 tag = ber_scanf( ber, "m", &dn );
3561 if ( tag == LBER_ERROR ) {
3562 Debug( LDAP_DEBUG_TRACE,
3563 "pcache_parse_query_delete: DN parse failed.\n",
3565 goto decoding_error;
3568 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3569 if ( rc != LDAP_SUCCESS ) {
3570 *text = "invalid DN in queryDelete exop request data";
3575 tag = ber_scanf( ber, "x" /* "m" */ );
3576 if ( tag == LBER_DEFAULT ) {
3577 goto decoding_error;
3581 tag = ber_peek_tag( ber, &len );
3584 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3585 if ( uuid != NULL ) {
3587 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3589 tag = ber_scanf( ber, "m", &bv );
3590 if ( tag == LBER_ERROR ) {
3591 Debug( LDAP_DEBUG_TRACE,
3592 "pcache_parse_query_delete: UUID parse failed.\n",
3594 goto decoding_error;
3597 if ( bv.bv_len != 16 ) {
3598 Debug( LDAP_DEBUG_TRACE,
3599 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3600 (unsigned long)bv.bv_len, 0, 0 );
3601 goto decoding_error;
3604 rc = lutil_uuidstr_from_normalized(
3605 bv.bv_val, bv.bv_len,
3606 uuidbuf, sizeof( uuidbuf ) );
3608 goto decoding_error;
3610 ber_str2bv( uuidbuf, rc, 1, uuid );
3614 tag = ber_skip_tag( ber, &len );
3615 if ( tag == LBER_DEFAULT ) {
3616 goto decoding_error;
3620 Debug( LDAP_DEBUG_TRACE,
3621 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3622 (unsigned long)len, 0, 0 );
3623 goto decoding_error;
3627 tag = ber_peek_tag( ber, &len );
3630 if ( tag != LBER_DEFAULT || len != 0 ) {
3632 Debug( LDAP_DEBUG_TRACE,
3633 "pcache_parse_query_delete: decoding error\n",
3635 rc = LDAP_PROTOCOL_ERROR;
3636 *text = "queryDelete data decoding error";
3639 if ( ndn && !BER_BVISNULL( ndn ) ) {
3640 slap_sl_free( ndn->bv_val, ctx );
3644 if ( uuid && !BER_BVISNULL( uuid ) ) {
3645 slap_sl_free( uuid->bv_val, ctx );
3650 if ( !BER_BVISNULL( &reqdata ) ) {
3651 ber_memfree_x( reqdata.bv_val, ctx );
3658 pcache_exop_query_delete(
3662 BackendDB *bd = op->o_bd;
3664 struct berval uuid = BER_BVNULL,
3666 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3668 ber_tag_t tag = LBER_DEFAULT;
3670 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3674 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3675 &tag, &op->o_req_ndn, uuidp,
3676 &rs->sr_text, op->o_tmpmemctx );
3677 if ( rs->sr_err != LDAP_SUCCESS ) {
3681 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3682 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3683 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3685 if ( !BER_BVISNULL( &uuid ) ) {
3686 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3689 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3690 op->o_log_prefix, buf, 0 );
3692 op->o_req_dn = op->o_req_ndn;
3694 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3695 rs->sr_err = backend_check_restrictions( op, rs,
3696 (struct berval *)&pcache_exop_QUERY_DELETE );
3697 if ( rs->sr_err != LDAP_SUCCESS ) {
3701 if ( op->o_bd->be_extended == NULL ) {
3702 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3703 "backend does not support extended operations" );
3707 op->o_bd->be_extended( op, rs );
3710 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3711 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3712 BER_BVZERO( &op->o_req_ndn );
3713 BER_BVZERO( &op->o_req_dn );
3716 if ( !BER_BVISNULL( &uuid ) ) {
3717 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3726 pcache_op_extended( Operation *op, SlapReply *rs )
3728 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3729 cache_manager *cm = on->on_bi.bi_private;
3731 #ifdef PCACHE_CONTROL_PRIVDB
3732 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3733 return pcache_op_privdb( op, rs );
3735 #endif /* PCACHE_CONTROL_PRIVDB */
3737 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3738 struct berval uuid = BER_BVNULL;
3739 ber_tag_t tag = LBER_DEFAULT;
3741 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3742 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3743 assert( rs->sr_err == LDAP_SUCCESS );
3745 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3746 /* remove all queries related to the selected entry */
3747 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3748 cm, &op->o_req_ndn, &uuid );
3750 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3751 if ( !BER_BVISNULL( &uuid ) ) {
3752 /* remove the selected query */
3753 rs->sr_err = pcache_remove_query_from_cache( op,
3757 /* TODO: remove all queries */
3758 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3759 rs->sr_text = "deletion of all queries not implemented";
3763 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3768 #endif /* PCACHE_EXOP_QUERY_DELETE */
3770 static slap_overinst pcache;
3772 static char *obsolete_names[] = {
3777 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3779 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3784 struct berval debugbv = BER_BVC("pcache");
3786 code = slap_loglevel_get( &debugbv, &pcache_debug );
3791 #ifdef PCACHE_CONTROL_PRIVDB
3792 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3793 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3794 parse_privdb_ctrl, &privDB_cid );
3795 if ( code != LDAP_SUCCESS ) {
3796 Debug( LDAP_DEBUG_ANY,
3797 "pcache_initialize: failed to register control %s (%d)\n",
3798 PCACHE_CONTROL_PRIVDB, code, 0 );
3801 #endif /* PCACHE_CONTROL_PRIVDB */
3803 #ifdef PCACHE_EXOP_QUERY_DELETE
3804 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3805 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3807 if ( code != LDAP_SUCCESS ) {
3808 Debug( LDAP_DEBUG_ANY,
3809 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3813 #endif /* PCACHE_EXOP_QUERY_DELETE */
3815 for ( i = 0; as[i].desc != NULL; i++ ) {
3816 code = register_at( as[i].desc, as[i].adp, 0 );
3818 Debug( LDAP_DEBUG_ANY,
3819 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3822 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3825 pcache.on_bi.bi_type = "pcache";
3826 pcache.on_bi.bi_obsolete_names = obsolete_names;
3827 pcache.on_bi.bi_db_init = pcache_db_init;
3828 pcache.on_bi.bi_db_config = pcache_db_config;
3829 pcache.on_bi.bi_db_open = pcache_db_open;
3830 pcache.on_bi.bi_db_close = pcache_db_close;
3831 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3833 pcache.on_bi.bi_op_search = pcache_op_search;
3834 #ifdef PCACHE_CONTROL_PRIVDB
3835 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3836 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3837 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3838 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3839 pcache.on_bi.bi_op_add = pcache_op_privdb;
3840 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3841 #endif /* PCACHE_CONTROL_PRIVDB */
3842 #ifdef PCACHE_EXOP_QUERY_DELETE
3843 pcache.on_bi.bi_extended = pcache_op_extended;
3844 #elif defined( PCACHE_CONTROL_PRIVDB )
3845 pcache.on_bi.bi_extended = pcache_op_privdb;
3848 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3850 pcache.on_bi.bi_cf_ocs = pcocs;
3852 code = config_register_schema( pccfg, pcocs );
3853 if ( code ) return code;
3855 return overlay_register( &pcache );
3858 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3859 int init_module(int argc, char *argv[]) {
3860 return pcache_initialize();
3864 #endif /* defined(SLAPD_OVER_PROXYCACHE) */