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 #ifdef LDAP_COMP_MATCH
1384 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1386 AttributeAssertion ava = { NULL, BER_BVNULL };
1388 Filter filter = {LDAP_FILTER_EQUALITY};
1389 SlapReply sreply = {REP_RESULT};
1390 slap_callback cb = { NULL, remove_func, NULL, NULL };
1393 sreply.sr_entry = NULL;
1394 sreply.sr_nentries = 0;
1395 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1396 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1397 filter.f_ava = &ava;
1398 filter.f_av_desc = ad_queryId;
1399 filter.f_av_value = *query_uuid;
1401 op->o_tag = LDAP_REQ_SEARCH;
1402 op->o_protocol = LDAP_VERSION3;
1403 op->o_callback = &cb;
1404 op->o_time = slap_get_time();
1405 op->o_do_not_cache = 1;
1407 op->o_req_dn = op->o_bd->be_suffix[0];
1408 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1409 op->ors_scope = LDAP_SCOPE_SUBTREE;
1410 op->ors_deref = LDAP_DEREF_NEVER;
1411 op->ors_slimit = SLAP_NO_LIMIT;
1412 op->ors_tlimit = SLAP_NO_LIMIT;
1413 op->ors_filter = &filter;
1414 op->ors_filterstr.bv_val = filter_str;
1415 op->ors_filterstr.bv_len = strlen(filter_str);
1416 op->ors_attrs = NULL;
1417 op->ors_attrsonly = 0;
1419 op->o_bd->be_search( op, &sreply );
1421 for ( qi=cb.sc_private; qi; qi=qnext ) {
1424 op->o_req_dn = qi->xdn;
1425 op->o_req_ndn = qi->xdn;
1428 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1429 query_uuid->bv_val, 0, 0 );
1431 op->o_tag = LDAP_REQ_DELETE;
1433 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1439 struct berval vals[2];
1441 vals[0] = *query_uuid;
1442 vals[1].bv_val = NULL;
1444 mod.sml_op = LDAP_MOD_DELETE;
1446 mod.sml_desc = ad_queryId;
1447 mod.sml_type = ad_queryId->ad_cname;
1448 mod.sml_values = vals;
1449 mod.sml_nvalues = NULL;
1450 mod.sml_next = NULL;
1451 Debug( pcache_debug,
1452 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1453 query_uuid->bv_val, 0, 0 );
1455 op->orm_modlist = &mod;
1457 op->o_bd->be_modify( op, &sreply );
1459 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1460 op->o_tmpfree( qi, op->o_tmpmemctx );
1467 AttributeName* attrs,
1476 struct berval *fstr,
1477 AttributeName** filter_attrs,
1479 int* filter_got_oc )
1481 AttributeDescription *ad;
1483 switch ( f->f_choice ) {
1484 case LDAP_FILTER_EQUALITY:
1486 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1487 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1490 case LDAP_FILTER_GE:
1492 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1493 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1496 case LDAP_FILTER_LE:
1498 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1499 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1502 case LDAP_FILTER_APPROX:
1504 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1505 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1508 case LDAP_FILTER_SUBSTRINGS:
1510 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1511 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1514 case LDAP_FILTER_PRESENT:
1516 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1517 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1520 case LDAP_FILTER_AND:
1521 case LDAP_FILTER_OR:
1522 case LDAP_FILTER_NOT: {
1524 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1525 f->f_choice == LDAP_FILTER_AND ? '&' :
1526 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1527 fstr->bv_len += sizeof("(%") - 1;
1529 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1530 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1534 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1535 fstr->bv_len += sizeof(")") - 1;
1541 strcpy( fstr->bv_val, "(?=?)" );
1542 fstr->bv_len += sizeof("(?=?)")-1;
1546 if ( filter_attrs != NULL ) {
1547 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1548 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1550 (*filter_attrs)[*filter_cnt].an_desc = ad;
1551 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1552 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1553 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1554 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1556 if ( ad == slap_schema.si_ad_objectClass )
1563 struct search_info {
1566 QueryTemplate *qtemp;
1567 AttributeName* save_attrs; /* original attributes, saved for response */
1572 int slimit_exceeded;
1577 remove_query_and_data(
1581 struct berval *uuid )
1583 query_manager* qm = cm->qm;
1585 qm->crfunc( qm, uuid );
1586 if ( !BER_BVISNULL( uuid ) ) {
1589 Debug( pcache_debug,
1590 "Removing query UUID %s\n",
1591 uuid->bv_val, 0, 0 );
1592 return_val = remove_query_data( op, rs, uuid );
1593 Debug( pcache_debug,
1594 "QUERY REMOVED, SIZE=%d\n",
1596 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
1597 cm->cur_entries -= return_val;
1598 cm->num_cached_queries--;
1599 Debug( pcache_debug,
1600 "STORED QUERIES = %lu\n",
1601 cm->num_cached_queries, 0, 0 );
1602 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
1603 Debug( pcache_debug,
1604 "QUERY REMOVED, CACHE ="
1606 cm->cur_entries, 0, 0 );
1611 * Callback used to fetch queryId values based on entryUUID;
1612 * used by pcache_remove_entries_from_cache()
1615 fetch_queryId_cb( Operation *op, SlapReply *rs )
1619 /* only care about searchEntry responses */
1620 if ( rs->sr_type != REP_SEARCH ) {
1624 /* allow only one response per entryUUID */
1625 if ( op->o_callback->sc_private != NULL ) {
1631 /* copy all queryId values into callback's private data */
1632 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1634 BerVarray vals = NULL;
1636 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
1637 op->o_callback->sc_private = (void *)vals;
1641 /* clear entry if required */
1642 if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
1643 entry_free( rs->sr_entry );
1644 rs->sr_entry = NULL;
1645 rs->sr_flags ^= REP_ENTRY_MUSTBEFREED;
1652 * Call that allows to remove a set of entries from the cache,
1653 * by forcing the removal of all the related queries.
1656 pcache_remove_entries_from_cache(
1659 BerVarray entryUUIDs )
1661 Connection conn = { 0 };
1662 OperationBuffer opbuf;
1664 slap_callback sc = { 0 };
1665 SlapReply rs = { REP_RESULT };
1667 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
1668 #ifdef LDAP_COMP_MATCH
1669 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1671 AttributeAssertion ava = { NULL, BER_BVNULL };
1673 AttributeName attrs[ 2 ] = { 0 };
1677 void *thrctx = ldap_pvt_thread_pool_context();
1679 connection_fake_init( &conn, &opbuf, thrctx );
1687 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1688 op->ors_scope = LDAP_SCOPE_SUBTREE;
1689 op->ors_deref = LDAP_DEREF_NEVER;
1690 f.f_choice = LDAP_FILTER_EQUALITY;
1692 ava.aa_desc = slap_schema.si_ad_entryUUID;
1693 op->ors_filter = &f;
1695 op->ors_tlimit = SLAP_NO_LIMIT;
1696 attrs[ 0 ].an_desc = ad_queryId;
1697 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1698 op->ors_attrs = attrs;
1699 op->ors_attrsonly = 0;
1701 op->o_req_dn = cm->db.be_suffix[ 0 ];
1702 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
1704 op->o_tag = LDAP_REQ_SEARCH;
1705 op->o_protocol = LDAP_VERSION3;
1706 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1708 op->o_dn = op->o_bd->be_rootdn;
1709 op->o_ndn = op->o_bd->be_rootndn;
1710 sc.sc_response = fetch_queryId_cb;
1711 op->o_callback = ≻
1713 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
1714 BerVarray vals = NULL;
1716 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
1717 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
1718 op->ors_filterstr.bv_val = filtbuf;
1719 ava.aa_value = entryUUIDs[ s ];
1721 rc = op->o_bd->be_search( op, &rs );
1722 if ( rc != LDAP_SUCCESS ) {
1726 vals = (BerVarray)op->o_callback->sc_private;
1727 if ( vals != NULL ) {
1730 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1731 struct berval val = vals[ i ];
1733 remove_query_and_data( op, &rs, cm, &val );
1735 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1736 ch_free( val.bv_val );
1740 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1741 op->o_callback->sc_private = NULL;
1749 * Call that allows to remove a query from the cache.
1752 pcache_remove_query_from_cache(
1755 struct berval *queryid )
1757 Operation op2 = *op;
1758 SlapReply rs2 = { 0 };
1762 /* remove the selected query */
1763 remove_query_and_data( &op2, &rs2, cm, queryid );
1765 return LDAP_SUCCESS;
1769 * Call that allows to remove a set of queries related to an entry
1770 * from the cache; if queryid is not null, the entry must belong to
1771 * the query indicated by queryid.
1774 pcache_remove_entry_queries_from_cache(
1778 struct berval *queryid )
1780 Connection conn = { 0 };
1781 OperationBuffer opbuf;
1783 slap_callback sc = { 0 };
1784 SlapReply rs = { REP_RESULT };
1786 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(queryId=)" ) ];
1787 #ifdef LDAP_COMP_MATCH
1788 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1790 AttributeAssertion ava = { NULL, BER_BVNULL };
1792 AttributeName attrs[ 2 ] = { 0 };
1795 BerVarray vals = NULL;
1798 void *thrctx = ldap_pvt_thread_pool_context();
1800 connection_fake_init( &conn, &opbuf, thrctx );
1808 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
1809 op->ors_scope = LDAP_SCOPE_BASE;
1810 op->ors_deref = LDAP_DEREF_NEVER;
1811 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
1812 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
1813 f.f_choice = LDAP_FILTER_PRESENT;
1814 f.f_desc = slap_schema.si_ad_objectClass;
1817 op->ors_filterstr.bv_len = snprintf( filter_str,
1818 sizeof( filter_str ), "(%s=%s)",
1819 ad_queryId->ad_cname.bv_val, queryid->bv_val );
1820 f.f_choice = LDAP_FILTER_EQUALITY;
1822 f.f_av_desc = ad_queryId;
1823 f.f_av_value = *queryid;
1825 op->ors_filter = &f;
1827 op->ors_tlimit = SLAP_NO_LIMIT;
1828 attrs[ 0 ].an_desc = ad_queryId;
1829 attrs[ 0 ].an_name = ad_queryId->ad_cname;
1830 op->ors_attrs = attrs;
1831 op->ors_attrsonly = 0;
1833 op->o_req_dn = *ndn;
1834 op->o_req_ndn = *ndn;
1836 op->o_tag = LDAP_REQ_SEARCH;
1837 op->o_protocol = LDAP_VERSION3;
1838 op->o_managedsait = SLAP_CONTROL_CRITICAL;
1840 op->o_dn = op->o_bd->be_rootdn;
1841 op->o_ndn = op->o_bd->be_rootndn;
1842 sc.sc_response = fetch_queryId_cb;
1843 op->o_callback = ≻
1845 rc = op->o_bd->be_search( op, &rs );
1846 if ( rc != LDAP_SUCCESS ) {
1850 vals = (BerVarray)op->o_callback->sc_private;
1851 if ( vals != NULL ) {
1854 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
1855 struct berval val = vals[ i ];
1857 remove_query_and_data( op, &rs, cm, &val );
1859 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
1860 ch_free( val.bv_val );
1864 ber_bvarray_free_x( vals, op->o_tmpmemctx );
1867 return LDAP_SUCCESS;
1874 struct berval *query_uuid )
1876 struct search_info *si = op->o_callback->sc_private;
1877 slap_overinst *on = si->on;
1878 cache_manager *cm = on->on_bi.bi_private;
1881 struct berval crp_uuid;
1882 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1883 Operation op_tmp = *op;
1885 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1886 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1888 op_tmp.o_bd = &cm->db;
1889 op_tmp.o_dn = cm->db.be_rootdn;
1890 op_tmp.o_ndn = cm->db.be_rootndn;
1892 Debug( pcache_debug, "UUID for query being added = %s\n",
1895 for ( e=si->head; e; e=si->head ) {
1896 si->head = e->e_private;
1897 e->e_private = NULL;
1898 while ( cm->cur_entries > (cm->max_entries) ) {
1899 BER_BVZERO( &crp_uuid );
1900 remove_query_and_data( &op_tmp, rs, cm, &crp_uuid );
1903 return_val = merge_entry(&op_tmp, e, query_uuid);
1904 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1905 cm->cur_entries += return_val;
1906 Debug( pcache_debug,
1907 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1908 cm->cur_entries, 0, 0 );
1910 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1917 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1918 slap_callback *cb = op->o_callback;
1919 struct search_info *si = cb->sc_private;
1921 if ( rs->sr_type == REP_SEARCH ) {
1922 /* don't return more entries than requested by the client */
1923 if ( si->slimit && rs->sr_nentries >= si->slimit ) {
1924 si->slimit_exceeded = 1;
1928 if ( rs->sr_type == REP_RESULT ||
1930 rs->sr_err == SLAPD_ABANDON )
1932 if ( si->save_attrs != NULL ) {
1933 rs->sr_attrs = si->save_attrs;
1934 op->ors_attrs = si->save_attrs;
1936 op->o_callback = op->o_callback->sc_next;
1937 op->o_tmpfree( cb, op->o_tmpmemctx );
1940 return SLAP_CB_CONTINUE;
1948 struct search_info *si = op->o_callback->sc_private;
1949 slap_overinst *on = si->on;
1950 cache_manager *cm = on->on_bi.bi_private;
1951 query_manager* qm = cm->qm;
1953 if ( si->save_attrs != NULL ) {
1954 rs->sr_attrs = si->save_attrs;
1955 op->ors_attrs = si->save_attrs;
1958 if ( rs->sr_type == REP_SEARCH ) {
1960 /* If we haven't exceeded the limit for this query,
1961 * build a chain of answers to store. If we hit the
1962 * limit, empty the chain and ignore the rest.
1965 if ( si->count < si->max ) {
1967 e = entry_dup( rs->sr_entry );
1968 if ( !si->head ) si->head = e;
1969 if ( si->tail ) si->tail->e_private = e;
1975 for (;si->head; si->head=e) {
1976 e = si->head->e_private;
1977 si->head->e_private = NULL;
1978 entry_free(si->head);
1984 /* don't return more entries than requested by the client */
1985 if ( si->slimit_exceeded ) {
1989 } else if ( rs->sr_type == REP_RESULT ) {
1990 pc_caching_reason_t why = PC_IGNORE;
1993 if ( rs->sr_err == LDAP_SUCCESS ) {
1996 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
1997 && si->qtemp->limitttl )
2002 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2003 rs->sr_err == LDAP_SUCCESS )
2008 if ( why != PC_IGNORE ) {
2009 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2015 cache_entries( op, rs, &qc->q_uuid );
2019 qc->q_sizelimit = rs->sr_nentries;
2022 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2023 cm->num_cached_queries++;
2024 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2025 cm->num_cached_queries, 0, 0 );
2026 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2028 /* If the consistency checker suspended itself,
2031 if ( cm->cc_paused ) {
2032 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2033 if ( cm->cc_paused ) {
2035 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2037 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2040 } else if ( si->count ) {
2041 /* duplicate query, free it */
2043 for (;si->head; si->head=e) {
2044 e = si->head->e_private;
2045 si->head->e_private = NULL;
2046 entry_free(si->head);
2051 filter_free( si->query.filter );
2054 if ( si->slimit_exceeded ) {
2055 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2059 return SLAP_CB_CONTINUE;
2065 AttributeName** new_attrs,
2066 struct attr_set *attrs,
2067 AttributeName* filter_attrs,
2077 /* duplicate attrs */
2078 count = attrs->count + fattr_cnt;
2079 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
2084 *new_attrs = (AttributeName*)ch_calloc( count + 1,
2085 sizeof(AttributeName) );
2086 for (i=0; i<attrs->count; i++) {
2087 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
2088 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
2090 BER_BVZERO( &(*new_attrs)[i].an_name );
2091 alluser = an_find(*new_attrs, &AllUser);
2092 allop = an_find(*new_attrs, &AllOper);
2095 for ( i=0; i<fattr_cnt; i++ ) {
2096 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
2099 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
2103 } else if ( alluser ) {
2106 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
2107 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
2108 (*new_attrs)[j].an_oc = NULL;
2109 (*new_attrs)[j].an_oc_exclude = 0;
2113 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
2114 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
2115 (*new_attrs)[j].an_oc = NULL;
2116 (*new_attrs)[j].an_oc_exclude = 0;
2119 BER_BVZERO( &(*new_attrs)[j].an_name );
2124 /* NOTE: this is a quick workaround to let pcache minimally interact
2125 * with pagedResults. A more articulated solutions would be to
2126 * perform the remote query without control and cache all results,
2127 * performing the pagedResults search only within the client
2128 * and the proxy. This requires pcache to understand pagedResults. */
2130 pcache_chk_controls(
2134 const char *non = "";
2135 const char *stripped = "";
2137 switch( op->o_pagedresults ) {
2138 case SLAP_CONTROL_NONCRITICAL:
2140 stripped = "; stripped";
2143 case SLAP_CONTROL_CRITICAL:
2144 Debug( pcache_debug, "%s: "
2145 "%scritical pagedResults control "
2146 "disabled with proxy cache%s.\n",
2147 op->o_log_prefix, non, stripped );
2149 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2153 rs->sr_err = SLAP_CB_CONTINUE;
2160 #ifdef PCACHE_CONTROL_PRIVDB
2166 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2167 cache_manager *cm = on->on_bi.bi_private;
2168 slap_callback *save_cb;
2171 /* skip if control is unset */
2172 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2173 return SLAP_CB_CONTINUE;
2176 /* FIXME: might be a little bit exaggerated... */
2177 if ( !be_isroot( op ) ) {
2178 save_cb = op->o_callback;
2179 op->o_callback = NULL;
2180 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2181 "pcachePrivDB: operation not allowed" );
2182 op->o_callback = save_cb;
2187 /* map tag to operation */
2188 type = slap_req2op( op->o_tag );
2189 if ( type != SLAP_OP_LAST ) {
2193 /* execute, if possible */
2194 func = &cm->db.be_bind;
2195 if ( func[ type ] != NULL ) {
2196 Operation op2 = *op;
2200 rc = func[ type ]( &op2, rs );
2201 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2202 op->o_conn->c_authz_cookie = cm->db.be_private;
2207 /* otherwise fall back to error */
2208 save_cb = op->o_callback;
2209 op->o_callback = NULL;
2210 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2211 "operation not supported with pcachePrivDB control" );
2212 op->o_callback = save_cb;
2216 #endif /* PCACHE_CONTROL_PRIVDB */
2223 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2224 cache_manager *cm = on->on_bi.bi_private;
2225 query_manager* qm = cm->qm;
2229 AttributeName *filter_attrs = NULL;
2232 QueryTemplate *qtemp = NULL;
2235 CachedQuery *answerable = NULL;
2238 int fattr_got_oc = 0;
2240 struct berval tempstr;
2242 #ifdef PCACHE_CONTROL_PRIVDB
2243 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2244 return pcache_op_privdb( op, rs );
2246 #endif /* PCACHE_CONTROL_PRIVDB */
2248 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
2250 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
2251 &fattr_cnt, &fattr_got_oc )) {
2252 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2253 return SLAP_CB_CONTINUE;
2256 Debug( pcache_debug, "query template of incoming query = %s\n",
2257 tempstr.bv_val, 0, 0 );
2259 /* FIXME: cannot cache/answer requests with pagedResults control */
2262 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
2264 query.filter = op->ors_filter;
2265 query.base = op->o_req_ndn;
2266 query.scope = op->ors_scope;
2268 /* check for query containment */
2269 if (attr_set > -1) {
2270 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
2271 for (; qt; qt = qt->qtnext ) {
2272 /* find if template i can potentially answer tempstr */
2273 if (qt->querystr.bv_len != tempstr.bv_len ||
2274 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
2278 Debug( pcache_debug, "Entering QC, querystr = %s\n",
2279 op->ors_filterstr.bv_val, 0, 0 );
2280 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
2286 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
2289 /* Need to clear the callbacks of the original operation,
2290 * in case there are other overlays */
2291 BackendDB *save_bd = op->o_bd;
2292 slap_callback *save_cb = op->o_callback;
2294 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
2295 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2296 if ( BER_BVISNULL( &answerable->q_uuid )) {
2297 /* No entries cached, just an empty result set */
2299 send_ldap_result( op, rs );
2302 op->o_callback = NULL;
2303 i = cm->db.bd_info->bi_op_search( op, rs );
2305 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
2307 op->o_callback = save_cb;
2311 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
2313 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2314 if (cm->num_cached_queries >= cm->max_queries) {
2317 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2319 if (op->ors_attrsonly)
2324 struct search_info *si;
2326 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
2327 query.filter = filter_dup(op->ors_filter, NULL);
2328 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
2329 if ( !qtemp->t_attrs.count ) {
2330 qtemp->t_attrs.count = add_filter_attrs(op,
2331 &qtemp->t_attrs.attrs,
2332 &qm->attr_sets[attr_set],
2333 filter_attrs, fattr_cnt, fattr_got_oc);
2335 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
2337 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
2338 cb->sc_response = pcache_response;
2339 cb->sc_cleanup = pcache_op_cleanup;
2340 cb->sc_private = (cb+1);
2341 si = cb->sc_private;
2345 si->max = cm->num_entries_limit ;
2349 si->slimit_exceeded = 0;
2350 if ( op->ors_slimit && op->ors_slimit < cm->num_entries_limit ) {
2351 si->slimit = op->ors_slimit;
2352 op->ors_slimit = cm->num_entries_limit;
2356 si->save_attrs = op->ors_attrs;
2358 op->ors_attrs = qtemp->t_attrs.attrs;
2360 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2361 cb->sc_next = op->o_callback;
2362 op->o_callback = cb;
2365 slap_callback **pcb;
2367 /* need to move the callback at the end, in case other
2368 * overlays are present, so that the final entry is
2369 * actually cached */
2371 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
2376 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
2380 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
2382 return SLAP_CB_CONTINUE;
2387 AttributeName* attrs,
2395 for ( ; attrs[count].an_name.bv_val; count++ );
2398 /* recognize a single "*" or a "1.1" */
2401 attrs = slap_anlist_all_user_attributes;
2403 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
2408 for ( i = 0; i < num; i++ ) {
2412 if ( count > qm->attr_sets[i].count ) {
2417 if ( !qm->attr_sets[i].count ) {
2423 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
2424 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
2447 struct re_s *rtask = arg;
2448 slap_overinst *on = rtask->arg;
2449 cache_manager *cm = on->on_bi.bi_private;
2450 query_manager *qm = cm->qm;
2451 Connection conn = {0};
2452 OperationBuffer opbuf;
2455 SlapReply rs = {REP_RESULT};
2457 int return_val, pause = 1;
2458 QueryTemplate* templ;
2460 connection_fake_init( &conn, &opbuf, ctx );
2464 op->o_dn = cm->db.be_rootdn;
2465 op->o_ndn = cm->db.be_rootndn;
2469 for (templ = qm->templates; templ; templ=templ->qmnext) {
2470 query = templ->query_last;
2471 if ( query ) pause = 0;
2472 op->o_time = slap_get_time();
2473 while (query && (query->expiry_time < op->o_time)) {
2475 Debug( pcache_debug, "Lock CR index = %p\n",
2476 (void *) templ, 0, 0 );
2477 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
2478 if ( query == templ->query_last ) {
2480 remove_from_template(query, templ);
2481 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
2482 (void *) templ, templ->no_of_queries, 0 );
2483 Debug( pcache_debug, "Unlock CR index = %p\n",
2484 (void *) templ, 0, 0 );
2486 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
2488 query = templ->query_last;
2491 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
2492 remove_query(qm, query);
2493 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
2494 if ( BER_BVISNULL( &query->q_uuid ))
2497 return_val = remove_query_data(op, &rs, &query->q_uuid);
2498 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
2500 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2501 cm->cur_entries -= return_val;
2502 cm->num_cached_queries--;
2503 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2504 cm->num_cached_queries, 0, 0 );
2505 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2506 Debug( pcache_debug,
2507 "STALE QUERY REMOVED, CACHE ="
2509 cm->cur_entries, 0, 0 );
2511 query = templ->query_last;
2514 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2515 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2516 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2518 /* If there were no queries, defer processing for a while */
2519 cm->cc_paused = pause;
2520 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2522 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2527 #define MAX_ATTR_SETS 500
2537 static ConfigDriver pc_cf_gen;
2538 static ConfigLDAPadd pc_ldadd;
2539 static ConfigCfAdd pc_cfadd;
2541 static ConfigTable pccfg[] = {
2542 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2544 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2545 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2546 "DESC 'ProxyCache basic parameters' "
2547 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2548 { "proxyattrset", "index> <attributes...",
2549 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2550 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2551 "DESC 'A set of attributes to cache' "
2552 "SYNTAX OMsDirectoryString )", NULL, NULL },
2553 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2554 4, 6, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2555 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2556 "DESC 'Filter template, attrset, cache TTL, "
2557 "optional negative TTL, optional sizelimit TTL' "
2558 "SYNTAX OMsDirectoryString )", NULL, NULL },
2559 { "response-callback", "head|tail(default)",
2560 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2561 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2562 "DESC 'Response callback position in overlay stack' "
2563 "SYNTAX OMsDirectoryString )", NULL, NULL },
2564 { "proxyCacheQueries", "queries",
2565 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2566 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2567 "DESC 'Maximum number of queries to cache' "
2568 "SYNTAX OMsInteger )", NULL, NULL },
2569 { "proxySaveQueries", "TRUE|FALSE",
2570 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2571 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2572 "DESC 'Save cached queries for hot restart' "
2573 "SYNTAX OMsBoolean )", NULL, NULL },
2575 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2578 static ConfigOCs pcocs[] = {
2579 { "( OLcfgOvOc:2.1 "
2580 "NAME 'olcPcacheConfig' "
2581 "DESC 'ProxyCache configuration' "
2582 "SUP olcOverlayConfig "
2583 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2584 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2585 Cft_Overlay, pccfg, NULL, pc_cfadd },
2586 { "( OLcfgOvOc:2.2 "
2587 "NAME 'olcPcacheDatabase' "
2588 "DESC 'Cache database configuration' "
2589 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2594 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2599 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2600 p->ce_bi->bi_cf_ocs != pcocs )
2601 return LDAP_CONSTRAINT_VIOLATION;
2603 on = (slap_overinst *)p->ce_bi;
2604 cm = on->on_bi.bi_private;
2606 return LDAP_SUCCESS;
2610 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2612 CfEntryInfo *pe = p->e_private;
2613 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2614 cache_manager *cm = on->on_bi.bi_private;
2617 /* FIXME: should not hardcode "olcDatabase" here */
2618 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2619 bv.bv_val = ca->cr_msg;
2622 /* We can only create this entry if the database is table-driven
2624 if ( cm->db.bd_info->bi_cf_ocs )
2625 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2632 pc_cf_gen( ConfigArgs *c )
2634 slap_overinst *on = (slap_overinst *)c->bi;
2635 cache_manager* cm = on->on_bi.bi_private;
2636 query_manager* qm = cm->qm;
2637 QueryTemplate* temp;
2638 AttributeName* attr_name;
2639 AttributeName* attrarray;
2640 const char* text=NULL;
2645 if ( c->op == SLAP_CONFIG_EMIT ) {
2649 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2650 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2651 cm->num_entries_limit, cm->cc_period );
2652 bv.bv_val = c->cr_msg;
2653 value_add_one( &c->rvalue_vals, &bv );
2656 for (i=0; i<cm->numattrsets; i++) {
2657 if ( !qm->attr_sets[i].count ) continue;
2659 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2661 /* count the attr length */
2662 for ( attr_name = qm->attr_sets[i].attrs;
2663 attr_name->an_name.bv_val; attr_name++ )
2664 bv.bv_len += attr_name->an_name.bv_len + 1;
2666 bv.bv_val = ch_malloc( bv.bv_len+1 );
2667 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2668 for ( attr_name = qm->attr_sets[i].attrs;
2669 attr_name->an_name.bv_val; attr_name++ ) {
2671 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2673 ber_bvarray_add( &c->rvalue_vals, &bv );
2675 if ( !c->rvalue_vals )
2679 for (temp=qm->templates; temp; temp=temp->qmnext) {
2680 /* HEADS-UP: always print all;
2681 * if optional == 0, ignore */
2682 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2684 temp->attr_set_index,
2688 bv.bv_len += temp->querystr.bv_len + 2;
2689 bv.bv_val = ch_malloc( bv.bv_len+1 );
2692 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2694 strcpy( ptr, c->cr_msg );
2695 ber_bvarray_add( &c->rvalue_vals, &bv );
2697 if ( !c->rvalue_vals )
2701 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2702 BER_BVSTR( &bv, "head" );
2704 BER_BVSTR( &bv, "tail" );
2706 value_add_one( &c->rvalue_vals, &bv );
2709 c->value_int = cm->max_queries;
2713 } else if ( c->op == LDAP_MOD_DELETE ) {
2714 return 1; /* FIXME */
2726 if ( cm->numattrsets > 0 ) {
2727 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2728 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2732 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2733 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2735 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2738 if ( cm->numattrsets <= 0 ) {
2739 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2740 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2743 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2744 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2745 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2749 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2750 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2751 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2755 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2756 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2758 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2761 if ( cm->max_entries <= 0 ) {
2762 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2763 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2767 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2768 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2770 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2773 if ( cm->num_entries_limit <= 0 ) {
2774 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2775 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2778 if ( cm->num_entries_limit > cm->max_entries ) {
2779 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2780 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2784 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2785 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2787 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2790 cm->cc_period = (time_t)t;
2791 Debug( pcache_debug,
2792 "Total # of attribute sets to be cached = %d.\n",
2793 cm->numattrsets, 0, 0 );
2794 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2795 sizeof( struct attr_set ) );
2798 if ( cm->numattrsets == 0 ) {
2799 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2800 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2803 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2804 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2806 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2810 if ( num < 0 || num >= cm->numattrsets ) {
2811 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2812 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2813 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2816 qm->attr_sets[num].flags |= PC_CONFIGURED;
2817 if ( c->argc == 2 ) {
2819 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2820 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2821 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2824 } else if ( c->argc == 3 ) {
2825 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2826 qm->attr_sets[num].count = 1;
2827 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2828 sizeof( AttributeName ) );
2829 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2832 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2833 qm->attr_sets[num].count = 1;
2834 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2835 sizeof( AttributeName ) );
2836 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2839 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2842 /* else: fallthru */
2844 } else if ( c->argc == 4 ) {
2845 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2846 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2848 qm->attr_sets[num].count = 2;
2849 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2850 sizeof( AttributeName ) );
2851 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2852 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2855 /* else: fallthru */
2858 if ( c->argc > 2 ) {
2859 int all_user = 0, all_op = 0;
2861 qm->attr_sets[num].count = c->argc - 2;
2862 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2863 sizeof( AttributeName ) );
2864 attr_name = qm->attr_sets[num].attrs;
2865 for ( i = 2; i < c->argc; i++ ) {
2866 attr_name->an_desc = NULL;
2867 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2868 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2869 "invalid attr #%d \"%s\" in attrlist",
2870 i - 2, c->argv[i] );
2871 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2872 ch_free( qm->attr_sets[num].attrs );
2873 qm->attr_sets[num].attrs = NULL;
2874 qm->attr_sets[num].count = 0;
2877 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2879 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2880 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2882 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2884 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2885 strcpy( c->cr_msg, text );
2886 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2887 ch_free( qm->attr_sets[num].attrs );
2888 qm->attr_sets[num].attrs = NULL;
2889 qm->attr_sets[num].count = 0;
2892 attr_name->an_name = attr_name->an_desc->ad_cname;
2894 attr_name->an_oc = NULL;
2895 attr_name->an_oc_exclude = 0;
2896 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2897 qm->attr_sets[num].flags |= PC_GOT_OC;
2899 BER_BVZERO( &attr_name->an_name );
2902 /* warn if list contains both "*" and "+" */
2903 if ( i > 4 && all_user && all_op ) {
2904 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2905 "warning: attribute list contains \"*\" and \"+\"" );
2906 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2911 if ( cm->numattrsets == 0 ) {
2912 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2913 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2916 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2917 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2919 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2923 if ( i < 0 || i >= cm->numattrsets ||
2924 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2925 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2926 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2927 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2930 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2931 temp->qmnext = qm->templates;
2932 qm->templates = temp;
2933 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2934 temp->query = temp->query_last = NULL;
2935 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2936 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2937 "unable to parse template ttl=\"%s\"",
2939 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2942 temp->ttl = (time_t)t;
2943 temp->negttl = (time_t)0;
2944 temp->limitttl = (time_t)0;
2945 switch ( c->argc ) {
2947 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2948 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2949 "unable to parse template sizelimit ttl=\"%s\"",
2951 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2954 temp->limitttl = (time_t)t;
2958 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2959 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2960 "unable to parse template negative ttl=\"%s\"",
2962 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2965 temp->negttl = (time_t)t;
2969 temp->no_of_queries = 0;
2971 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2972 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2973 Debug( pcache_debug, " query template: %s\n",
2974 temp->querystr.bv_val, 0, 0 );
2975 temp->attr_set_index = i;
2976 qm->attr_sets[i].flags |= PC_REFERENCED;
2977 temp->qtnext = qm->attr_sets[i].templates;
2978 qm->attr_sets[i].templates = temp;
2979 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2980 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2981 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2982 Debug( pcache_debug, "\t%s\n",
2983 attrarray[i].an_name.bv_val, 0, 0 );
2987 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2988 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2990 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2991 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2994 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2995 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3000 if ( c->value_int <= 0 ) {
3001 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
3002 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
3005 cm->max_queries = c->value_int;
3020 slap_overinst *on = (slap_overinst *)be->bd_info;
3021 cache_manager* cm = on->on_bi.bi_private;
3023 /* Something for the cache database? */
3024 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
3025 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
3027 return SLAP_CONF_UNKNOWN;
3035 slap_overinst *on = (slap_overinst *)be->bd_info;
3039 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
3040 on->on_bi.bi_private = cm;
3042 qm = (query_manager*)ch_malloc(sizeof(query_manager));
3045 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3046 cm->db.be_private = NULL;
3047 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
3049 cm->numattrsets = 0;
3050 cm->num_entries_limit = 5;
3051 cm->num_cached_queries = 0;
3052 cm->max_entries = 0;
3053 cm->cur_entries = 0;
3054 cm->max_queries = 10000;
3055 cm->save_queries = 0;
3056 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
3057 cm->cc_period = 1000;
3060 qm->attr_sets = NULL;
3061 qm->templates = NULL;
3063 qm->lru_bottom = NULL;
3065 qm->qcfunc = query_containment;
3066 qm->crfunc = cache_replacement;
3067 qm->addfunc = add_query;
3068 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
3070 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
3075 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
3077 assert( op->o_tag == LDAP_REQ_SEARCH );
3079 if ( rs->sr_type == REP_SEARCH ) {
3082 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
3086 assert( a->a_nvals != NULL );
3088 valsp = op->o_callback->sc_private;
3089 assert( *valsp == NULL );
3091 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
3099 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
3101 assert( op->o_tag == LDAP_REQ_SEARCH );
3103 if ( rs->sr_type == REP_SEARCH ) {
3104 int *countp = (int *)op->o_callback->sc_private;
3117 slap_overinst *on = (slap_overinst *)be->bd_info;
3118 cache_manager *cm = on->on_bi.bi_private;
3119 query_manager* qm = cm->qm;
3120 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
3122 /* check attr sets */
3123 for ( i = 0; i < cm->numattrsets; i++) {
3124 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
3125 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
3126 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
3130 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
3134 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
3135 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
3140 if ( ncf || rf || nrf ) {
3141 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
3142 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
3143 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
3150 /* need to inherit something from the original database... */
3151 cm->db.be_def_limit = be->be_def_limit;
3152 cm->db.be_limits = be->be_limits;
3153 cm->db.be_acl = be->be_acl;
3154 cm->db.be_dfltaccess = be->be_dfltaccess;
3156 if ( SLAP_DBMONITORING( be ) ) {
3157 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
3160 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
3163 rc = backend_startup_one( &cm->db, NULL );
3165 /* There is no runqueue in TOOL mode */
3166 if ( slapMode & SLAP_SERVER_MODE ) {
3167 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3168 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
3169 consistency_check, on,
3170 "pcache_consistency", be->be_suffix[0].bv_val );
3171 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3173 /* Cached database must have the rootdn */
3174 if ( BER_BVISNULL( &cm->db.be_rootndn )
3175 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
3177 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
3178 "underlying database of type \"%s\"\n"
3179 " serving naming context \"%s\"\n"
3180 " has no \"rootdn\", required by \"proxycache\".\n",
3181 on->on_info->oi_orig->bi_type,
3182 cm->db.be_suffix[0].bv_val, 0 );
3186 if ( cm->save_queries ) {
3187 void *thrctx = ldap_pvt_thread_pool_context();
3188 Connection conn = { 0 };
3189 OperationBuffer opbuf;
3191 slap_callback cb = { 0 };
3192 SlapReply rs = { 0 };
3193 BerVarray vals = NULL;
3194 Filter f = { 0 }, f2 = { 0 };
3195 #ifdef LDAP_COMP_MATCH
3196 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
3198 AttributeAssertion ava = { NULL, BER_BVNULL };
3200 AttributeName attrs[ 2 ] = { 0 };
3202 connection_fake_init( &conn, &opbuf, thrctx );
3207 op->o_tag = LDAP_REQ_SEARCH;
3208 op->o_protocol = LDAP_VERSION3;
3209 cb.sc_response = pcache_cachedquery_open_cb;
3210 cb.sc_private = &vals;
3211 op->o_callback = &cb;
3212 op->o_time = slap_get_time();
3213 op->o_do_not_cache = 1;
3214 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3216 op->o_dn = cm->db.be_rootdn;
3217 op->o_ndn = cm->db.be_rootndn;
3218 op->o_req_dn = cm->db.be_suffix[ 0 ];
3219 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
3221 op->ors_scope = LDAP_SCOPE_BASE;
3222 op->ors_deref = LDAP_DEREF_NEVER;
3224 op->ors_tlimit = SLAP_NO_LIMIT;
3225 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
3226 f.f_choice = LDAP_FILTER_PRESENT;
3227 f.f_desc = ad_cachedQueryURL;
3228 op->ors_filter = &f;
3229 attrs[ 0 ].an_desc = ad_cachedQueryURL;
3230 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
3231 op->ors_attrs = attrs;
3232 op->ors_attrsonly = 0;
3234 rc = op->o_bd->be_search( op, &rs );
3235 if ( rc == LDAP_SUCCESS && vals != NULL ) {
3238 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
3239 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
3240 cm->num_cached_queries++;
3244 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3247 /* count cached entries */
3248 f.f_choice = LDAP_FILTER_NOT;
3250 f2.f_choice = LDAP_FILTER_EQUALITY;
3252 f2.f_av_desc = slap_schema.si_ad_objectClass;
3253 BER_BVSTR( &f2.f_av_value, "glue" );
3254 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
3256 op->ors_slimit = SLAP_NO_LIMIT;
3257 op->ors_scope = LDAP_SCOPE_SUBTREE;
3258 op->ors_attrs = slap_anlist_no_attrs;
3260 op->o_callback->sc_response = pcache_cachedquery_count_cb;
3262 op->o_callback->sc_private = &rs.sr_nentries;
3264 rc = op->o_bd->be_search( op, &rs );
3266 cm->cur_entries = rs.sr_nentries;
3277 pcache_free_qbase( void *v )
3283 tavl_free( qb->scopes[i], NULL );
3293 slap_overinst *on = (slap_overinst *)be->bd_info;
3294 cache_manager *cm = on->on_bi.bi_private;
3295 query_manager *qm = cm->qm;
3299 if ( cm->save_queries ) {
3301 BerVarray vals = NULL;
3304 Connection conn = { 0 };
3305 OperationBuffer opbuf;
3307 slap_callback cb = { 0 };
3309 SlapReply rs = { REP_RESULT };
3310 Modifications mod = { 0 };
3312 thrctx = ldap_pvt_thread_pool_context();
3314 connection_fake_init( &conn, &opbuf, thrctx );
3317 if ( qm->templates != NULL ) {
3318 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
3319 for ( qc = tm->query; qc; qc = qc->next ) {
3322 if ( query2url( op, qc, &bv ) == 0 ) {
3323 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
3330 op->o_dn = cm->db.be_rootdn;
3331 op->o_ndn = cm->db.be_rootndn;
3333 op->o_tag = LDAP_REQ_MODIFY;
3334 op->o_protocol = LDAP_VERSION3;
3335 cb.sc_response = slap_null_cb;
3336 op->o_callback = &cb;
3337 op->o_time = slap_get_time();
3338 op->o_do_not_cache = 1;
3339 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3341 op->o_req_dn = op->o_bd->be_suffix[0];
3342 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3344 mod.sml_op = LDAP_MOD_REPLACE;
3346 mod.sml_desc = ad_cachedQueryURL;
3347 mod.sml_type = ad_cachedQueryURL->ad_cname;
3348 mod.sml_values = vals;
3349 mod.sml_nvalues = NULL;
3350 mod.sml_next = NULL;
3351 Debug( pcache_debug,
3352 "%sSETTING CACHED QUERY URLS\n",
3353 vals == NULL ? "RE" : "", 0, 0 );
3355 op->orm_modlist = &mod;
3357 op->o_bd->be_modify( op, &rs );
3359 ber_bvarray_free_x( vals, op->o_tmpmemctx );
3362 /* cleanup stuff inherited from the original database... */
3363 cm->db.be_limits = NULL;
3364 cm->db.be_acl = NULL;
3366 /* stop the thread ... */
3368 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3369 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
3370 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
3372 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
3373 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3376 if ( cm->db.bd_info->bi_db_close ) {
3377 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
3379 while ( (tm = qm->templates) != NULL ) {
3380 CachedQuery *qc, *qn;
3381 qm->templates = tm->qmnext;
3382 for ( qc = tm->query; qc; qc = qn ) {
3386 avl_free( tm->qbase, pcache_free_qbase );
3387 free( tm->querystr.bv_val );
3388 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
3389 free( tm->t_attrs.attrs );
3393 for ( i=0; i<cm->numattrsets; i++ ) {
3394 free( qm->attr_sets[i].attrs );
3396 free( qm->attr_sets );
3397 qm->attr_sets = NULL;
3408 slap_overinst *on = (slap_overinst *)be->bd_info;
3409 cache_manager *cm = on->on_bi.bi_private;
3410 query_manager *qm = cm->qm;
3412 if ( cm->db.be_private != NULL ) {
3413 backend_stopdown_one( &cm->db );
3416 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
3417 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
3424 #ifdef PCACHE_CONTROL_PRIVDB
3426 Control ::= SEQUENCE {
3427 controlType LDAPOID,
3428 criticality BOOLEAN DEFAULT FALSE,
3429 controlValue OCTET STRING OPTIONAL }
3431 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
3433 * criticality must be TRUE; controlValue must be absent.
3441 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
3442 rs->sr_text = "privateDB control specified multiple times";
3443 return LDAP_PROTOCOL_ERROR;
3446 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
3447 rs->sr_text = "privateDB control value not absent";
3448 return LDAP_PROTOCOL_ERROR;
3451 if ( !ctrl->ldctl_iscritical ) {
3452 rs->sr_text = "privateDB control criticality required";
3453 return LDAP_PROTOCOL_ERROR;
3456 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
3458 return LDAP_SUCCESS;
3461 static char *extops[] = {
3462 LDAP_EXOP_MODIFY_PASSWD,
3465 #endif /* PCACHE_CONTROL_PRIVDB */
3467 #ifdef PCACHE_EXOP_QUERY_DELETE
3468 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
3470 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
3471 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
3472 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
3475 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
3476 requestName [0] LDAPOID,
3477 requestValue [1] OCTET STRING OPTIONAL }
3479 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
3481 requestValue ::= SEQUENCE { CHOICE {
3483 entryDN [1] LDAPDN },
3484 queryID [2] OCTET STRING (SIZE(16))
3485 -- constrained to UUID }
3487 * Either baseDN or entryDN must be present, to allow database selection.
3489 * 1. if baseDN and queryID are present, then the query corresponding
3490 * to queryID is deleted;
3491 * 2. if baseDN is present and queryID is absent, then all queries
3493 * 3. if entryDN is present and queryID is absent, then all queries
3494 * corresponding to the queryID values present in entryDN are deleted;
3495 * 4. if entryDN and queryID are present, then all queries
3496 * corresponding to the queryID values present in entryDN are deleted,
3497 * but only if the value of queryID is contained in the entry;
3499 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
3500 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
3501 * or by removing the database files.
3503 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3504 COMPONENTS OF LDAPResult,
3505 responseName [10] LDAPOID OPTIONAL,
3506 responseValue [11] OCTET STRING OPTIONAL }
3508 * responseName and responseValue must be absent.
3512 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
3513 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
3514 * - if ndn != NULL, it is set to the normalized DN in the request
3515 * corresponding to either the baseDN or the entryDN, according
3516 * to *tagp; memory is malloc'ed on the Operation's slab, and must
3517 * be freed by the caller.
3518 * - if uuid != NULL, it is set to point to the normalized UUID;
3519 * memory is malloc'ed on the Operation's slab, and must
3520 * be freed by the caller.
3523 pcache_parse_query_delete(
3527 struct berval *uuid,
3531 int rc = LDAP_SUCCESS;
3534 BerElementBuffer berbuf;
3535 BerElement *ber = (BerElement *)&berbuf;
3536 struct berval reqdata = BER_BVNULL;
3548 if ( in == NULL || in->bv_len == 0 ) {
3549 *text = "empty request data field in queryDelete exop";
3550 return LDAP_PROTOCOL_ERROR;
3553 ber_dupbv_x( &reqdata, in, ctx );
3555 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
3556 ber_init2( ber, &reqdata, 0 );
3558 tag = ber_scanf( ber, "{" /*}*/ );
3560 if ( tag == LBER_ERROR ) {
3561 Debug( LDAP_DEBUG_TRACE,
3562 "pcache_parse_query_delete: decoding error.\n",
3564 goto decoding_error;
3567 tag = ber_peek_tag( ber, &len );
3568 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
3569 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
3573 if ( ndn != NULL ) {
3576 tag = ber_scanf( ber, "m", &dn );
3577 if ( tag == LBER_ERROR ) {
3578 Debug( LDAP_DEBUG_TRACE,
3579 "pcache_parse_query_delete: DN parse failed.\n",
3581 goto decoding_error;
3584 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
3585 if ( rc != LDAP_SUCCESS ) {
3586 *text = "invalid DN in queryDelete exop request data";
3591 tag = ber_scanf( ber, "x" /* "m" */ );
3592 if ( tag == LBER_DEFAULT ) {
3593 goto decoding_error;
3597 tag = ber_peek_tag( ber, &len );
3600 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
3601 if ( uuid != NULL ) {
3603 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
3605 tag = ber_scanf( ber, "m", &bv );
3606 if ( tag == LBER_ERROR ) {
3607 Debug( LDAP_DEBUG_TRACE,
3608 "pcache_parse_query_delete: UUID parse failed.\n",
3610 goto decoding_error;
3613 if ( bv.bv_len != 16 ) {
3614 Debug( LDAP_DEBUG_TRACE,
3615 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3616 (unsigned long)bv.bv_len, 0, 0 );
3617 goto decoding_error;
3620 rc = lutil_uuidstr_from_normalized(
3621 bv.bv_val, bv.bv_len,
3622 uuidbuf, sizeof( uuidbuf ) );
3624 goto decoding_error;
3626 ber_str2bv( uuidbuf, rc, 1, uuid );
3630 tag = ber_skip_tag( ber, &len );
3631 if ( tag == LBER_DEFAULT ) {
3632 goto decoding_error;
3636 Debug( LDAP_DEBUG_TRACE,
3637 "pcache_parse_query_delete: invalid UUID length %lu.\n",
3638 (unsigned long)len, 0, 0 );
3639 goto decoding_error;
3643 tag = ber_peek_tag( ber, &len );
3646 if ( tag != LBER_DEFAULT || len != 0 ) {
3648 Debug( LDAP_DEBUG_TRACE,
3649 "pcache_parse_query_delete: decoding error\n",
3651 rc = LDAP_PROTOCOL_ERROR;
3652 *text = "queryDelete data decoding error";
3655 if ( ndn && !BER_BVISNULL( ndn ) ) {
3656 slap_sl_free( ndn->bv_val, ctx );
3660 if ( uuid && !BER_BVISNULL( uuid ) ) {
3661 slap_sl_free( uuid->bv_val, ctx );
3666 if ( !BER_BVISNULL( &reqdata ) ) {
3667 ber_memfree_x( reqdata.bv_val, ctx );
3674 pcache_exop_query_delete(
3678 BackendDB *bd = op->o_bd;
3680 struct berval uuid = BER_BVNULL,
3682 char buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
3684 ber_tag_t tag = LBER_DEFAULT;
3686 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3690 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3691 &tag, &op->o_req_ndn, uuidp,
3692 &rs->sr_text, op->o_tmpmemctx );
3693 if ( rs->sr_err != LDAP_SUCCESS ) {
3697 if ( LogTest( LDAP_DEBUG_STATS ) ) {
3698 assert( !BER_BVISNULL( &op->o_req_ndn ) );
3699 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
3701 if ( !BER_BVISNULL( &uuid ) ) {
3702 snprintf( &buf[ len ], sizeof( buf ) - len, " queryId=\"%s\"", uuid.bv_val );
3705 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
3706 op->o_log_prefix, buf, 0 );
3708 op->o_req_dn = op->o_req_ndn;
3710 op->o_bd = select_backend( &op->o_req_ndn, 0 );
3711 rs->sr_err = backend_check_restrictions( op, rs,
3712 (struct berval *)&pcache_exop_QUERY_DELETE );
3713 if ( rs->sr_err != LDAP_SUCCESS ) {
3717 if ( op->o_bd->be_extended == NULL ) {
3718 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
3719 "backend does not support extended operations" );
3723 op->o_bd->be_extended( op, rs );
3726 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
3727 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
3728 BER_BVZERO( &op->o_req_ndn );
3729 BER_BVZERO( &op->o_req_dn );
3732 if ( !BER_BVISNULL( &uuid ) ) {
3733 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3742 pcache_op_extended( Operation *op, SlapReply *rs )
3744 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3745 cache_manager *cm = on->on_bi.bi_private;
3747 #ifdef PCACHE_CONTROL_PRIVDB
3748 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
3749 return pcache_op_privdb( op, rs );
3751 #endif /* PCACHE_CONTROL_PRIVDB */
3753 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
3754 struct berval uuid = BER_BVNULL;
3755 ber_tag_t tag = LBER_DEFAULT;
3757 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
3758 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
3759 assert( rs->sr_err == LDAP_SUCCESS );
3761 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
3762 /* remove all queries related to the selected entry */
3763 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
3764 cm, &op->o_req_ndn, &uuid );
3766 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
3767 if ( !BER_BVISNULL( &uuid ) ) {
3768 /* remove the selected query */
3769 rs->sr_err = pcache_remove_query_from_cache( op,
3773 /* TODO: remove all queries */
3774 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3775 rs->sr_text = "deletion of all queries not implemented";
3779 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
3784 #endif /* PCACHE_EXOP_QUERY_DELETE */
3786 static slap_overinst pcache;
3788 static char *obsolete_names[] = {
3793 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3795 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
3800 struct berval debugbv = BER_BVC("pcache");
3802 code = slap_loglevel_get( &debugbv, &pcache_debug );
3807 #ifdef PCACHE_CONTROL_PRIVDB
3808 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
3809 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
3810 parse_privdb_ctrl, &privDB_cid );
3811 if ( code != LDAP_SUCCESS ) {
3812 Debug( LDAP_DEBUG_ANY,
3813 "pcache_initialize: failed to register control %s (%d)\n",
3814 PCACHE_CONTROL_PRIVDB, code, 0 );
3817 #endif /* PCACHE_CONTROL_PRIVDB */
3819 #ifdef PCACHE_EXOP_QUERY_DELETE
3820 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
3821 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
3823 if ( code != LDAP_SUCCESS ) {
3824 Debug( LDAP_DEBUG_ANY,
3825 "pcache_initialize: unable to register queryDelete exop: %d.\n",
3829 #endif /* PCACHE_EXOP_QUERY_DELETE */
3831 for ( i = 0; as[i].desc != NULL; i++ ) {
3832 code = register_at( as[i].desc, as[i].adp, 0 );
3834 Debug( LDAP_DEBUG_ANY,
3835 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
3838 (*as[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
3841 pcache.on_bi.bi_type = "pcache";
3842 pcache.on_bi.bi_obsolete_names = obsolete_names;
3843 pcache.on_bi.bi_db_init = pcache_db_init;
3844 pcache.on_bi.bi_db_config = pcache_db_config;
3845 pcache.on_bi.bi_db_open = pcache_db_open;
3846 pcache.on_bi.bi_db_close = pcache_db_close;
3847 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
3849 pcache.on_bi.bi_op_search = pcache_op_search;
3850 #ifdef PCACHE_CONTROL_PRIVDB
3851 pcache.on_bi.bi_op_bind = pcache_op_privdb;
3852 pcache.on_bi.bi_op_compare = pcache_op_privdb;
3853 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
3854 pcache.on_bi.bi_op_modify = pcache_op_privdb;
3855 pcache.on_bi.bi_op_add = pcache_op_privdb;
3856 pcache.on_bi.bi_op_delete = pcache_op_privdb;
3857 #endif /* PCACHE_CONTROL_PRIVDB */
3858 #ifdef PCACHE_EXOP_QUERY_DELETE
3859 pcache.on_bi.bi_extended = pcache_op_extended;
3860 #elif defined( PCACHE_CONTROL_PRIVDB )
3861 pcache.on_bi.bi_extended = pcache_op_privdb;
3864 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
3866 pcache.on_bi.bi_cf_ocs = pcocs;
3868 code = config_register_schema( pccfg, pcocs );
3869 if ( code ) return code;
3871 return overlay_register( &pcache );
3874 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
3875 int init_module(int argc, char *argv[]) {
3876 return pcache_initialize();
3880 #endif /* defined(SLAPD_OVER_PROXYCACHE) */