1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3 *
4 * Copyright 2003-2021 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003-2009 Symas Corporation.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
11 * Public License.
12 *
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>.
16 */
17 /* ACKNOWLEDGEMENTS:
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
20 */
21
22 #include "portable.h"
23
24 #ifdef SLAPD_OVER_PROXYCACHE
25
26 #include <stdio.h>
27
28 #include <ac/string.h>
29 #include <ac/time.h>
30
31 #include "slap.h"
32 #include "lutil.h"
33 #include "ldap_rq.h"
34 #include "ldap_avl.h"
35
36 #include "../back-monitor/back-monitor.h"
37
38 #include "slap-config.h"
39
40 /*
41 * Control that allows to access the private DB
42 * instead of the public one
43 */
44 #define PCACHE_CONTROL_PRIVDB "1.3.6.1.4.1.4203.666.11.9.5.1"
45
46 /*
47 * Extended Operation that allows to remove a query from the cache
48 */
49 #define PCACHE_EXOP_QUERY_DELETE "1.3.6.1.4.1.4203.666.11.9.6.1"
50
51 /*
52 * Monitoring
53 */
54 #define PCACHE_MONITOR
55
56 /* query cache structs */
57 /* query */
58
59 typedef struct Query_s {
60 Filter* filter; /* Search Filter */
61 struct berval base; /* Search Base */
62 int scope; /* Search scope */
63 } Query;
64
65 struct query_template_s;
66
67 typedef struct Qbase_s {
68 TAvlnode *scopes[4]; /* threaded AVL trees of cached queries */
69 struct berval base;
70 int queries;
71 } Qbase;
72
73 /* struct representing a cached query */
74 typedef struct cached_query_s {
75 Filter *filter;
76 Filter *first;
77 Qbase *qbase;
78 int scope;
79 struct berval q_uuid; /* query identifier */
80 int q_sizelimit;
81 struct query_template_s *qtemp; /* template of the query */
82 time_t expiry_time; /* time till the query is considered invalid */
83 time_t refresh_time; /* time till the query is refreshed */
84 time_t bindref_time; /* time till the bind is refreshed */
85 int bind_refcnt; /* number of bind operation referencing this query */
86 unsigned long answerable_cnt; /* how many times it was answerable */
87 int refcnt; /* references since last refresh */
88 int in_lru; /* query is in LRU list */
89 ldap_pvt_thread_mutex_t answerable_cnt_mutex;
90 struct cached_query_s *next; /* next query in the template */
91 struct cached_query_s *prev; /* previous query in the template */
92 struct cached_query_s *lru_up; /* previous query in the LRU list */
93 struct cached_query_s *lru_down; /* next query in the LRU list */
94 ldap_pvt_thread_rdwr_t rwlock;
95 } CachedQuery;
96
97 /*
98 * URL representation:
99 *
100 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>,x-refresh=<refresh>
101 *
102 * <base> ::= CachedQuery.qbase->base
103 * <scope> ::= CachedQuery.scope
104 * <filter> ::= filter2bv(CachedQuery.filter)
105 * <uuid> ::= CachedQuery.q_uuid
106 * <attrset> ::= CachedQuery.qtemp->attr_set_index
107 * <expiry> ::= CachedQuery.expiry_time
108 * <refresh> ::= CachedQuery.refresh_time
109 *
110 * quick hack: parse URI, call add_query() and then fix
111 * CachedQuery.expiry_time and CachedQuery.q_uuid
112 *
113 * NOTE: if the <attrset> changes, all stored URLs will be invalidated.
114 */
115
116 /*
117 * Represents a set of projected attributes.
118 */
119
120 struct attr_set {
121 struct query_template_s *templates;
122 AttributeName* attrs; /* specifies the set */
123 unsigned flags;
124 #define PC_CONFIGURED (0x1)
125 #define PC_REFERENCED (0x2)
126 #define PC_GOT_OC (0x4)
127 int count; /* number of attributes */
128 };
129
130 /* struct representing a query template
131 * e.g. template string = &(cn=)(mail=)
132 */
133 typedef struct query_template_s {
134 struct query_template_s *qtnext;
135 struct query_template_s *qmnext;
136
137 Avlnode* qbase;
138 CachedQuery* query; /* most recent query cached for the template */
139 CachedQuery* query_last; /* oldest query cached for the template */
140 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
141 struct berval querystr; /* Filter string corresponding to the QT */
142 struct berval bindbase; /* base DN for Bind request */
143 struct berval bindfilterstr; /* Filter string for Bind request */
144 struct berval bindftemp; /* bind filter template */
145 Filter *bindfilter;
146 AttributeDescription **bindfattrs; /* attrs to substitute in ftemp */
147
148 int bindnattrs; /* number of bindfattrs */
149 int bindscope;
150 int attr_set_index; /* determines the projected attributes */
151 int no_of_queries; /* Total number of queries in the template */
152 time_t ttl; /* TTL for the queries of this template */
153 time_t negttl; /* TTL for negative results */
154 time_t limitttl; /* TTL for sizelimit exceeding results */
155 time_t ttr; /* time to refresh */
156 time_t bindttr; /* TTR for cached binds */
157 struct attr_set t_attrs; /* filter attrs + attr_set */
158 } QueryTemplate;
159
160 typedef enum {
161 PC_IGNORE = 0,
162 PC_POSITIVE,
163 PC_NEGATIVE,
164 PC_SIZELIMIT
165 } pc_caching_reason_t;
166
167 static const char *pc_caching_reason_str[] = {
168 "IGNORE",
169 "POSITIVE",
170 "NEGATIVE",
171 "SIZELIMIT",
172
173 NULL
174 };
175
176 struct query_manager_s;
177
178 /* prototypes for functions for 1) query containment
179 * 2) query addition, 3) cache replacement
180 */
181 typedef CachedQuery *(QCfunc)(Operation *op, struct query_manager_s*,
182 Query*, QueryTemplate*);
183 typedef CachedQuery *(AddQueryfunc)(Operation *op, struct query_manager_s*,
184 Query*, QueryTemplate*, pc_caching_reason_t, int wlock);
185 typedef void (CRfunc)(struct query_manager_s*, struct berval*);
186
187 /* LDAP query cache */
188 typedef struct query_manager_s {
189 struct attr_set* attr_sets; /* possible sets of projected attributes */
190 QueryTemplate* templates; /* cacheable templates */
191
192 CachedQuery* lru_top; /* top and bottom of LRU list */
193 CachedQuery* lru_bottom;
194
195 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
196
197 /* Query cache methods */
198 QCfunc *qcfunc; /* Query containment*/
199 CRfunc *crfunc; /* cache replacement */
200 AddQueryfunc *addfunc; /* add query */
201 } query_manager;
202
203 /* LDAP query cache manager */
204 typedef struct cache_manager_s {
205 BackendDB db; /* underlying database */
206 unsigned long num_cached_queries; /* total number of cached queries */
207 unsigned long max_queries; /* upper bound on # of cached queries */
208 int save_queries; /* save cached queries across restarts */
209 int check_cacheability; /* check whether a query is cacheable */
210 int numattrsets; /* number of attribute sets */
211 int cur_entries; /* current number of entries cached */
212 int max_entries; /* max number of entries cached */
213 int num_entries_limit; /* max # of entries in a cacheable query */
214
215 char response_cb; /* install the response callback
216 * at the tail of the callback list */
217 #define PCACHE_RESPONSE_CB_HEAD 0
218 #define PCACHE_RESPONSE_CB_TAIL 1
219 char defer_db_open; /* defer open for online add */
220 char cache_binds; /* cache binds or just passthru */
221
222 time_t cc_period; /* interval between successive consistency checks (sec) */
223 #define PCACHE_CC_PAUSED 1
224 #define PCACHE_CC_OFFLINE 2
225 int cc_paused;
226 void *cc_arg;
227
228 ldap_pvt_thread_mutex_t cache_mutex;
229
230 query_manager* qm; /* query cache managed by the cache manager */
231
232 #ifdef PCACHE_MONITOR
233 void *monitor_cb;
234 struct berval monitor_ndn;
235 #endif /* PCACHE_MONITOR */
236 } cache_manager;
237
238 #ifdef PCACHE_MONITOR
239 static int pcache_monitor_db_init( BackendDB *be );
240 static int pcache_monitor_db_open( BackendDB *be );
241 static int pcache_monitor_db_close( BackendDB *be );
242 static int pcache_monitor_db_destroy( BackendDB *be );
243 #endif /* PCACHE_MONITOR */
244
245 static int pcache_debug;
246
247 #ifdef PCACHE_CONTROL_PRIVDB
248 static int privDB_cid;
249 #endif /* PCACHE_CONTROL_PRIVDB */
250
251 static AttributeDescription *ad_queryId, *ad_cachedQueryURL;
252
253 #ifdef PCACHE_MONITOR
254 static AttributeDescription *ad_numQueries, *ad_numEntries;
255 static ObjectClass *oc_olmPCache;
256 #endif /* PCACHE_MONITOR */
257
258 static struct {
259 char *name;
260 char *oid;
261 } s_oid[] = {
262 { "PCacheOID", "1.3.6.1.4.1.4203.666.11.9.1" },
263 { "PCacheAttributes", "PCacheOID:1" },
264 { "PCacheObjectClasses", "PCacheOID:2" },
265
266 { NULL }
267 };
268
269 static struct {
270 char *desc;
271 AttributeDescription **adp;
272 } s_ad[] = {
273 { "( PCacheAttributes:1 "
274 "NAME 'pcacheQueryID' "
275 "DESC 'ID of query the entry belongs to, formatted as a UUID' "
276 "EQUALITY octetStringMatch "
277 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
278 "NO-USER-MODIFICATION "
279 "USAGE directoryOperation )",
280 &ad_queryId },
281 { "( PCacheAttributes:2 "
282 "NAME 'pcacheQueryURL' "
283 "DESC 'URI describing a cached query' "
284 "EQUALITY caseExactMatch "
285 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
286 "NO-USER-MODIFICATION "
287 "USAGE directoryOperation )",
288 &ad_cachedQueryURL },
289 #ifdef PCACHE_MONITOR
290 { "( PCacheAttributes:3 "
291 "NAME 'pcacheNumQueries' "
292 "DESC 'Number of cached queries' "
293 "EQUALITY integerMatch "
294 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
295 "NO-USER-MODIFICATION "
296 "USAGE directoryOperation )",
297 &ad_numQueries },
298 { "( PCacheAttributes:4 "
299 "NAME 'pcacheNumEntries' "
300 "DESC 'Number of cached entries' "
301 "EQUALITY integerMatch "
302 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 "
303 "NO-USER-MODIFICATION "
304 "USAGE directoryOperation )",
305 &ad_numEntries },
306 #endif /* PCACHE_MONITOR */
307
308 { NULL }
309 };
310
311 static struct {
312 char *desc;
313 ObjectClass **ocp;
314 } s_oc[] = {
315 #ifdef PCACHE_MONITOR
316 /* augments an existing object, so it must be AUXILIARY */
317 { "( PCacheObjectClasses:1 "
318 "NAME ( 'olmPCache' ) "
319 "SUP top AUXILIARY "
320 "MAY ( "
321 "pcacheQueryURL "
322 "$ pcacheNumQueries "
323 "$ pcacheNumEntries "
324 " ) )",
325 &oc_olmPCache },
326 #endif /* PCACHE_MONITOR */
327
328 { NULL }
329 };
330
331 static int
332 filter2template(
333 Operation *op,
334 Filter *f,
335 struct berval *fstr );
336
337 static CachedQuery *
338 add_query(
339 Operation *op,
340 query_manager* qm,
341 Query* query,
342 QueryTemplate *templ,
343 pc_caching_reason_t why,
344 int wlock);
345
346 static int
347 remove_query_data(
348 Operation *op,
349 struct berval *query_uuid );
350
351 /*
352 * Turn a cached query into its URL representation
353 */
354 static int
query2url(Operation * op,CachedQuery * q,struct berval * urlbv,int dolock)355 query2url( Operation *op, CachedQuery *q, struct berval *urlbv, int dolock )
356 {
357 struct berval bv_scope,
358 bv_filter;
359 char attrset_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
360 expiry_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
361 refresh_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
362 answerable_buf[ LDAP_PVT_INTTYPE_CHARS( unsigned long ) ],
363 *ptr;
364 ber_len_t attrset_len,
365 expiry_len,
366 refresh_len,
367 answerable_len;
368
369 if ( dolock ) {
370 ldap_pvt_thread_rdwr_rlock( &q->rwlock );
371 }
372
373 ldap_pvt_scope2bv( q->scope, &bv_scope );
374 filter2bv_x( op, q->filter, &bv_filter );
375 attrset_len = sprintf( attrset_buf,
376 "%lu", (unsigned long)q->qtemp->attr_set_index );
377 expiry_len = sprintf( expiry_buf,
378 "%lu", (unsigned long)q->expiry_time );
379 answerable_len = snprintf( answerable_buf, sizeof( answerable_buf ),
380 "%lu", q->answerable_cnt );
381 if ( q->refresh_time )
382 refresh_len = sprintf( refresh_buf,
383 "%lu", (unsigned long)q->refresh_time );
384 else
385 refresh_len = 0;
386
387 urlbv->bv_len = STRLENOF( "ldap:///" )
388 + q->qbase->base.bv_len
389 + STRLENOF( "??" )
390 + bv_scope.bv_len
391 + STRLENOF( "?" )
392 + bv_filter.bv_len
393 + STRLENOF( "?x-uuid=" )
394 + q->q_uuid.bv_len
395 + STRLENOF( ",x-attrset=" )
396 + attrset_len
397 + STRLENOF( ",x-expiry=" )
398 + expiry_len
399 + STRLENOF( ",x-answerable=" )
400 + answerable_len;
401 if ( refresh_len )
402 urlbv->bv_len += STRLENOF( ",x-refresh=" )
403 + refresh_len;
404
405 ptr = urlbv->bv_val = ber_memalloc_x( urlbv->bv_len + 1, op->o_tmpmemctx );
406 ptr = lutil_strcopy( ptr, "ldap:///" );
407 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
408 ptr = lutil_strcopy( ptr, "??" );
409 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
410 ptr = lutil_strcopy( ptr, "?" );
411 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
412 ptr = lutil_strcopy( ptr, "?x-uuid=" );
413 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
414 ptr = lutil_strcopy( ptr, ",x-attrset=" );
415 ptr = lutil_strcopy( ptr, attrset_buf );
416 ptr = lutil_strcopy( ptr, ",x-expiry=" );
417 ptr = lutil_strcopy( ptr, expiry_buf );
418 ptr = lutil_strcopy( ptr, ",x-answerable=" );
419 ptr = lutil_strcopy( ptr, answerable_buf );
420 if ( refresh_len ) {
421 ptr = lutil_strcopy( ptr, ",x-refresh=" );
422 ptr = lutil_strcopy( ptr, refresh_buf );
423 }
424
425 ber_memfree_x( bv_filter.bv_val, op->o_tmpmemctx );
426
427 if ( dolock ) {
428 ldap_pvt_thread_rdwr_runlock( &q->rwlock );
429 }
430
431 return 0;
432 }
433
434 /* Find and record the empty filter clauses */
435
436 static int
ftemp_attrs(struct berval * ftemp,struct berval * template,AttributeDescription *** ret,const char ** text)437 ftemp_attrs( struct berval *ftemp, struct berval *template,
438 AttributeDescription ***ret, const char **text )
439 {
440 int i;
441 int attr_cnt=0;
442 struct berval bv;
443 char *p1, *p2, *t1;
444 AttributeDescription *ad;
445 AttributeDescription **descs = NULL;
446 char *temp2;
447
448 temp2 = ch_malloc( ftemp->bv_len + 1 );
449 p1 = ftemp->bv_val;
450 t1 = temp2;
451
452 *ret = NULL;
453
454 for (;;) {
455 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' )
456 *t1++ = *p1++;
457
458 p2 = strchr( p1, '=' );
459 if ( !p2 ) {
460 if ( !descs ) {
461 ch_free( temp2 );
462 return -1;
463 }
464 break;
465 }
466 i = p2 - p1;
467 AC_MEMCPY( t1, p1, i );
468 t1 += i;
469 *t1++ = '=';
470
471 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
472 bv.bv_val = p1;
473 bv.bv_len = p2 - p1;
474 ad = NULL;
475 i = slap_bv2ad( &bv, &ad, text );
476 if ( i ) {
477 ch_free( temp2 );
478 ch_free( descs );
479 return -1;
480 }
481 if ( *p2 == '<' || *p2 == '>' ) p2++;
482 if ( p2[1] != ')' ) {
483 p2++;
484 while ( *p2 != ')' ) p2++;
485 p1 = p2;
486 continue;
487 }
488
489 descs = (AttributeDescription **)ch_realloc(descs,
490 (attr_cnt + 2)*sizeof(AttributeDescription *));
491
492 descs[attr_cnt++] = ad;
493
494 p1 = p2+1;
495 }
496 *t1 = '\0';
497 descs[attr_cnt] = NULL;
498 *ret = descs;
499 template->bv_val = temp2;
500 template->bv_len = t1 - temp2;
501 return attr_cnt;
502 }
503
504 static int
template_attrs(char * template,struct attr_set * set,AttributeName ** ret,const char ** text)505 template_attrs( char *template, struct attr_set *set, AttributeName **ret,
506 const char **text )
507 {
508 int got_oc = 0;
509 int alluser = 0;
510 int allop = 0;
511 int i;
512 int attr_cnt;
513 int t_cnt = 0;
514 struct berval bv;
515 char *p1, *p2;
516 AttributeDescription *ad;
517 AttributeName *attrs;
518
519 p1 = template;
520
521 *ret = NULL;
522
523 attrs = ch_calloc( set->count + 1, sizeof(AttributeName) );
524 for ( i=0; i < set->count; i++ )
525 attrs[i] = set->attrs[i];
526 attr_cnt = i;
527 alluser = an_find( attrs, slap_bv_all_user_attrs );
528 allop = an_find( attrs, slap_bv_all_operational_attrs );
529
530 for (;;) {
531 while ( *p1 == '(' || *p1 == '&' || *p1 == '|' || *p1 == ')' ) p1++;
532 p2 = strchr( p1, '=' );
533 if ( !p2 )
534 break;
535 if ( p2[-1] == '<' || p2[-1] == '>' ) p2--;
536 bv.bv_val = p1;
537 bv.bv_len = p2 - p1;
538 ad = NULL;
539 i = slap_bv2ad( &bv, &ad, text );
540 if ( i ) {
541 ch_free( attrs );
542 return -1;
543 }
544 t_cnt++;
545
546 if ( ad == slap_schema.si_ad_objectClass )
547 got_oc = 1;
548
549 if ( is_at_operational(ad->ad_type)) {
550 if ( allop ) {
551 goto bottom;
552 }
553 } else if ( alluser ) {
554 goto bottom;
555 }
556 if ( !ad_inlist( ad, attrs )) {
557 attrs = (AttributeName *)ch_realloc(attrs,
558 (attr_cnt + 2)*sizeof(AttributeName));
559
560 attrs[attr_cnt].an_desc = ad;
561 attrs[attr_cnt].an_name = ad->ad_cname;
562 attrs[attr_cnt].an_oc = NULL;
563 attrs[attr_cnt].an_flags = 0;
564 BER_BVZERO( &attrs[attr_cnt+1].an_name );
565 attr_cnt++;
566 }
567
568 bottom:
569 p1 = p2+2;
570 }
571 if ( !t_cnt ) {
572 *text = "couldn't parse template";
573 ch_free(attrs);
574 return -1;
575 }
576 if ( !got_oc && !( set->flags & PC_GOT_OC )) {
577 attrs = (AttributeName *)ch_realloc(attrs,
578 (attr_cnt + 2)*sizeof(AttributeName));
579
580 ad = slap_schema.si_ad_objectClass;
581 attrs[attr_cnt].an_desc = ad;
582 attrs[attr_cnt].an_name = ad->ad_cname;
583 attrs[attr_cnt].an_oc = NULL;
584 attrs[attr_cnt].an_flags = 0;
585 BER_BVZERO( &attrs[attr_cnt+1].an_name );
586 attr_cnt++;
587 }
588 *ret = attrs;
589 return attr_cnt;
590 }
591
592 /*
593 * Turn an URL representing a formerly cached query into a cached query,
594 * and try to cache it
595 */
596 static int
url2query(char * url,Operation * op,query_manager * qm)597 url2query(
598 char *url,
599 Operation *op,
600 query_manager *qm )
601 {
602 Query query = { 0 };
603 QueryTemplate *qt;
604 CachedQuery *cq;
605 LDAPURLDesc *lud = NULL;
606 struct berval base,
607 tempstr = BER_BVNULL,
608 uuid = BER_BVNULL;
609 int attrset;
610 time_t expiry_time;
611 time_t refresh_time;
612 unsigned long answerable_cnt;
613 int i,
614 got = 0,
615 #define GOT_UUID 0x1U
616 #define GOT_ATTRSET 0x2U
617 #define GOT_EXPIRY 0x4U
618 #define GOT_ANSWERABLE 0x8U
619 #define GOT_REFRESH 0x10U
620 #define GOT_ALL (GOT_UUID|GOT_ATTRSET|GOT_EXPIRY|GOT_ANSWERABLE)
621 rc = 0;
622
623 rc = ldap_url_parse( url, &lud );
624 if ( rc != LDAP_URL_SUCCESS ) {
625 return -1;
626 }
627
628 /* non-allowed fields */
629 if ( lud->lud_host != NULL ) {
630 rc = 1;
631 goto error;
632 }
633
634 if ( lud->lud_attrs != NULL ) {
635 rc = 1;
636 goto error;
637 }
638
639 /* be pedantic */
640 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
641 rc = 1;
642 goto error;
643 }
644
645 /* required fields */
646 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
647 rc = 1;
648 goto error;
649 }
650
651 switch ( lud->lud_scope ) {
652 case LDAP_SCOPE_BASE:
653 case LDAP_SCOPE_ONELEVEL:
654 case LDAP_SCOPE_SUBTREE:
655 case LDAP_SCOPE_SUBORDINATE:
656 break;
657
658 default:
659 rc = 1;
660 goto error;
661 }
662
663 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
664 rc = 1;
665 goto error;
666 }
667
668 if ( lud->lud_exts == NULL ) {
669 rc = 1;
670 goto error;
671 }
672
673 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
674 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
675 struct berval tmpUUID;
676 Syntax *syn_UUID = slap_schema.si_ad_entryUUID->ad_type->sat_syntax;
677
678 if ( got & GOT_UUID ) {
679 rc = 1;
680 goto error;
681 }
682
683 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &tmpUUID );
684 if ( !BER_BVISEMPTY( &tmpUUID ) ) {
685 rc = syn_UUID->ssyn_pretty( syn_UUID, &tmpUUID, &uuid, NULL );
686 if ( rc != LDAP_SUCCESS ) {
687 goto error;
688 }
689 }
690 got |= GOT_UUID;
691
692 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
693 if ( got & GOT_ATTRSET ) {
694 rc = 1;
695 goto error;
696 }
697
698 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
699 if ( rc ) {
700 goto error;
701 }
702 got |= GOT_ATTRSET;
703
704 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
705 unsigned long l;
706
707 if ( got & GOT_EXPIRY ) {
708 rc = 1;
709 goto error;
710 }
711
712 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
713 if ( rc ) {
714 goto error;
715 }
716 expiry_time = (time_t)l;
717 got |= GOT_EXPIRY;
718
719 } else if ( strncmp( lud->lud_exts[ i ], "x-answerable=", STRLENOF( "x-answerable=" ) ) == 0 ) {
720 if ( got & GOT_ANSWERABLE ) {
721 rc = 1;
722 goto error;
723 }
724
725 rc = lutil_atoul( &answerable_cnt, &lud->lud_exts[ i ][ STRLENOF( "x-answerable=" ) ] );
726 if ( rc ) {
727 goto error;
728 }
729 got |= GOT_ANSWERABLE;
730
731 } else if ( strncmp( lud->lud_exts[ i ], "x-refresh=", STRLENOF( "x-refresh=" ) ) == 0 ) {
732 unsigned long l;
733
734 if ( got & GOT_REFRESH ) {
735 rc = 1;
736 goto error;
737 }
738
739 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-refresh=" ) ] );
740 if ( rc ) {
741 goto error;
742 }
743 refresh_time = (time_t)l;
744 got |= GOT_REFRESH;
745
746 } else {
747 rc = -1;
748 goto error;
749 }
750 }
751
752 if ( got != GOT_ALL ) {
753 rc = 1;
754 goto error;
755 }
756
757 if ( !(got & GOT_REFRESH ))
758 refresh_time = 0;
759
760 /* ignore expired queries */
761 if ( expiry_time <= slap_get_time()) {
762 Operation op2 = *op;
763
764 memset( &op2.oq_search, 0, sizeof( op2.oq_search ) );
765
766 (void)remove_query_data( &op2, &uuid );
767
768 rc = 0;
769
770 } else {
771 ber_str2bv( lud->lud_dn, 0, 0, &base );
772 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
773 if ( rc != LDAP_SUCCESS ) {
774 goto error;
775 }
776 query.scope = lud->lud_scope;
777 query.filter = str2filter( lud->lud_filter );
778 if ( query.filter == NULL ) {
779 rc = -1;
780 goto error;
781 }
782
783 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
784 tempstr.bv_len = 0;
785 if ( filter2template( op, query.filter, &tempstr ) ) {
786 ch_free( tempstr.bv_val );
787 rc = -1;
788 goto error;
789 }
790
791 /* check for query containment */
792 qt = qm->attr_sets[attrset].templates;
793 for ( ; qt; qt = qt->qtnext ) {
794 /* find if template i can potentially answer tempstr */
795 if ( bvmatch( &qt->querystr, &tempstr ) ) {
796 break;
797 }
798 }
799
800 if ( qt == NULL ) {
801 rc = 1;
802 goto error;
803 }
804
805 cq = add_query( op, qm, &query, qt, PC_POSITIVE, 0 );
806 if ( cq != NULL ) {
807 cq->expiry_time = expiry_time;
808 cq->refresh_time = refresh_time;
809 cq->q_uuid = uuid;
810 cq->answerable_cnt = answerable_cnt;
811 cq->refcnt = 0;
812
813 /* it's now into cq->filter */
814 BER_BVZERO( &uuid );
815 query.filter = NULL;
816
817 } else {
818 rc = 1;
819 }
820 }
821
822 error:;
823 if ( query.filter != NULL ) filter_free( query.filter );
824 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
825 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
826 if ( !BER_BVISNULL( &uuid ) ) ch_free( uuid.bv_val );
827 if ( lud != NULL ) ldap_free_urldesc( lud );
828
829 return rc;
830 }
831
832 /* Return 1 for an added entry, else 0 */
833 static int
merge_entry(Operation * op,Entry * e,int dup,struct berval * query_uuid)834 merge_entry(
835 Operation *op,
836 Entry *e,
837 int dup,
838 struct berval* query_uuid )
839 {
840 int rc;
841 Modifications* modlist = NULL;
842 const char* text = NULL;
843 Attribute *attr;
844 char textbuf[SLAP_TEXT_BUFLEN];
845 size_t textlen = sizeof(textbuf);
846
847 SlapReply sreply = {REP_RESULT};
848
849 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
850
851 if ( dup )
852 e = entry_dup( e );
853 attr = e->e_attrs;
854 e->e_attrs = NULL;
855
856 /* add queryId attribute */
857 attr_merge_one( e, ad_queryId, query_uuid, NULL );
858
859 /* append the attribute list from the fetched entry */
860 e->e_attrs->a_next = attr;
861
862 op->o_tag = LDAP_REQ_ADD;
863 op->o_protocol = LDAP_VERSION3;
864 op->o_callback = &cb;
865 op->o_time = slap_get_time();
866 op->o_do_not_cache = 1;
867
868 op->ora_e = e;
869 op->o_req_dn = e->e_name;
870 op->o_req_ndn = e->e_nname;
871 rc = op->o_bd->be_add( op, &sreply );
872
873 if ( rc != LDAP_SUCCESS ) {
874 if ( rc == LDAP_ALREADY_EXISTS ) {
875 rs_reinit( &sreply, REP_RESULT );
876 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
877 modlist->sml_op = LDAP_MOD_ADD;
878 op->o_tag = LDAP_REQ_MODIFY;
879 op->orm_modlist = modlist;
880 op->o_managedsait = SLAP_CONTROL_CRITICAL;
881 op->o_bd->be_modify( op, &sreply );
882 slap_mods_free( modlist, 1 );
883 } else if ( rc == LDAP_REFERRAL ||
884 rc == LDAP_NO_SUCH_OBJECT ) {
885 syncrepl_add_glue( op, e );
886 e = NULL;
887 rc = 1;
888 }
889 if ( e ) {
890 entry_free( e );
891 rc = 0;
892 }
893 } else {
894 if ( op->ora_e == e )
895 entry_free( e );
896 rc = 1;
897 }
898
899 return rc;
900 }
901
902 /* Length-ordered sort on normalized DNs */
pcache_dn_cmp(const void * v1,const void * v2)903 static int pcache_dn_cmp( const void *v1, const void *v2 )
904 {
905 const Qbase *q1 = v1, *q2 = v2;
906
907 int rc = q1->base.bv_len - q2->base.bv_len;
908 if ( rc == 0 )
909 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
910 return rc;
911 }
912
lex_bvcmp(struct berval * bv1,struct berval * bv2)913 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
914 {
915 int len, dif;
916 dif = bv1->bv_len - bv2->bv_len;
917 len = bv1->bv_len;
918 if ( dif > 0 ) len -= dif;
919 len = memcmp( bv1->bv_val, bv2->bv_val, len );
920 if ( !len )
921 len = dif;
922 return len;
923 }
924
925 /* compare the current value in each filter */
pcache_filter_cmp(Filter * f1,Filter * f2)926 static int pcache_filter_cmp( Filter *f1, Filter *f2 )
927 {
928 int rc, weight1, weight2;
929
930 switch( f1->f_choice ) {
931 case LDAP_FILTER_AND:
932 case LDAP_FILTER_OR:
933 weight1 = 0;
934 break;
935 case LDAP_FILTER_PRESENT:
936 weight1 = 1;
937 break;
938 case LDAP_FILTER_EQUALITY:
939 case LDAP_FILTER_GE:
940 case LDAP_FILTER_LE:
941 weight1 = 2;
942 break;
943 default:
944 weight1 = 3;
945 }
946 switch( f2->f_choice ) {
947 case LDAP_FILTER_AND:
948 case LDAP_FILTER_OR:
949 weight2 = 0;
950 break;
951 case LDAP_FILTER_PRESENT:
952 weight2 = 1;
953 break;
954 case LDAP_FILTER_EQUALITY:
955 case LDAP_FILTER_GE:
956 case LDAP_FILTER_LE:
957 weight2 = 2;
958 break;
959 default:
960 weight2 = 3;
961 }
962 rc = weight1 - weight2;
963 if ( !rc ) {
964 switch( weight1 ) {
965 case 0:
966 rc = pcache_filter_cmp( f1->f_and, f2->f_and );
967 break;
968 case 1:
969 break;
970 case 2:
971 rc = lex_bvcmp( &f1->f_av_value, &f2->f_av_value );
972 break;
973 case 3:
974 if ( f1->f_choice == LDAP_FILTER_SUBSTRINGS ) {
975 rc = 0;
976 if ( !BER_BVISNULL( &f1->f_sub_initial )) {
977 if ( !BER_BVISNULL( &f2->f_sub_initial )) {
978 rc = lex_bvcmp( &f1->f_sub_initial,
979 &f2->f_sub_initial );
980 } else {
981 rc = 1;
982 }
983 } else if ( !BER_BVISNULL( &f2->f_sub_initial )) {
984 rc = -1;
985 }
986 if ( rc ) break;
987 if ( f1->f_sub_any ) {
988 if ( f2->f_sub_any ) {
989 rc = lex_bvcmp( f1->f_sub_any,
990 f2->f_sub_any );
991 } else {
992 rc = 1;
993 }
994 } else if ( f2->f_sub_any ) {
995 rc = -1;
996 }
997 if ( rc ) break;
998 if ( !BER_BVISNULL( &f1->f_sub_final )) {
999 if ( !BER_BVISNULL( &f2->f_sub_final )) {
1000 rc = lex_bvcmp( &f1->f_sub_final,
1001 &f2->f_sub_final );
1002 } else {
1003 rc = 1;
1004 }
1005 } else if ( !BER_BVISNULL( &f2->f_sub_final )) {
1006 rc = -1;
1007 }
1008 } else {
1009 rc = lex_bvcmp( &f1->f_mr_value,
1010 &f2->f_mr_value );
1011 }
1012 break;
1013 }
1014 while ( !rc ) {
1015 f1 = f1->f_next;
1016 f2 = f2->f_next;
1017 if ( f1 || f2 ) {
1018 if ( !f1 )
1019 rc = -1;
1020 else if ( !f2 )
1021 rc = 1;
1022 else {
1023 rc = pcache_filter_cmp( f1, f2 );
1024 }
1025 } else {
1026 break;
1027 }
1028 }
1029 }
1030 return rc;
1031 }
1032
1033 /* compare filters in each query */
pcache_query_cmp(const void * v1,const void * v2)1034 static int pcache_query_cmp( const void *v1, const void *v2 )
1035 {
1036 const CachedQuery *q1 = v1, *q2 =v2;
1037 return pcache_filter_cmp( q1->filter, q2->filter );
1038 }
1039
1040 /* add query on top of LRU list */
1041 static void
add_query_on_top(query_manager * qm,CachedQuery * qc)1042 add_query_on_top (query_manager* qm, CachedQuery* qc)
1043 {
1044 CachedQuery* top = qm->lru_top;
1045
1046 qc->in_lru = 1;
1047 qm->lru_top = qc;
1048
1049 if (top)
1050 top->lru_up = qc;
1051 else
1052 qm->lru_bottom = qc;
1053
1054 qc->lru_down = top;
1055 qc->lru_up = NULL;
1056 Debug( pcache_debug, "Base of added query = %s\n",
1057 qc->qbase->base.bv_val );
1058 }
1059
1060 /* remove_query from LRU list */
1061
1062 static void
remove_query(query_manager * qm,CachedQuery * qc)1063 remove_query (query_manager* qm, CachedQuery* qc)
1064 {
1065 CachedQuery* up;
1066 CachedQuery* down;
1067
1068 if (!qc || !qc->in_lru)
1069 return;
1070
1071 qc->in_lru = 0;
1072 up = qc->lru_up;
1073 down = qc->lru_down;
1074
1075 if (!up)
1076 qm->lru_top = down;
1077
1078 if (!down)
1079 qm->lru_bottom = up;
1080
1081 if (down)
1082 down->lru_up = up;
1083
1084 if (up)
1085 up->lru_down = down;
1086
1087 qc->lru_up = qc->lru_down = NULL;
1088 }
1089
1090 /* find and remove string2 from string1
1091 * from start if position = 1,
1092 * from end if position = 3,
1093 * from anywhere if position = 2
1094 * string1 is overwritten if position = 2.
1095 */
1096
1097 static int
find_and_remove(struct berval * ber1,struct berval * ber2,int position)1098 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
1099 {
1100 int ret=0;
1101
1102 if ( !ber2->bv_val )
1103 return 1;
1104 if ( !ber1->bv_val )
1105 return 0;
1106
1107 switch( position ) {
1108 case 1:
1109 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
1110 ber2->bv_val, ber2->bv_len )) {
1111 ret = 1;
1112 ber1->bv_val += ber2->bv_len;
1113 ber1->bv_len -= ber2->bv_len;
1114 }
1115 break;
1116 case 2: {
1117 char *temp;
1118 ber1->bv_val[ber1->bv_len] = '\0';
1119 temp = strstr( ber1->bv_val, ber2->bv_val );
1120 if ( temp ) {
1121 strcpy( temp, temp+ber2->bv_len );
1122 ber1->bv_len -= ber2->bv_len;
1123 ret = 1;
1124 }
1125 break;
1126 }
1127 case 3:
1128 if ( ber1->bv_len >= ber2->bv_len &&
1129 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
1130 ber2->bv_len )) {
1131 ret = 1;
1132 ber1->bv_len -= ber2->bv_len;
1133 }
1134 break;
1135 }
1136 return ret;
1137 }
1138
1139
1140 static struct berval*
merge_init_final(Operation * op,struct berval * init,struct berval * any,struct berval * final)1141 merge_init_final(Operation *op, struct berval* init, struct berval* any,
1142 struct berval* final)
1143 {
1144 struct berval* merged, *temp;
1145 int i, any_count, count;
1146
1147 for (any_count=0; any && any[any_count].bv_val; any_count++)
1148 ;
1149
1150 count = any_count;
1151
1152 if (init->bv_val)
1153 count++;
1154 if (final->bv_val)
1155 count++;
1156
1157 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
1158 op->o_tmpmemctx );
1159 temp = merged;
1160
1161 if (init->bv_val) {
1162 ber_dupbv_x( temp, init, op->o_tmpmemctx );
1163 temp++;
1164 }
1165
1166 for (i=0; i<any_count; i++) {
1167 ber_dupbv_x( temp, any, op->o_tmpmemctx );
1168 temp++; any++;
1169 }
1170
1171 if (final->bv_val){
1172 ber_dupbv_x( temp, final, op->o_tmpmemctx );
1173 temp++;
1174 }
1175 BER_BVZERO( temp );
1176 return merged;
1177 }
1178
1179 /* Each element in stored must be found in incoming. Incoming is overwritten.
1180 */
1181 static int
strings_containment(struct berval * stored,struct berval * incoming)1182 strings_containment(struct berval* stored, struct berval* incoming)
1183 {
1184 struct berval* element;
1185 int k=0;
1186 int j, rc = 0;
1187
1188 for ( element=stored; element->bv_val != NULL; element++ ) {
1189 for (j = k; incoming[j].bv_val != NULL; j++) {
1190 if (find_and_remove(&(incoming[j]), element, 2)) {
1191 k = j;
1192 rc = 1;
1193 break;
1194 }
1195 rc = 0;
1196 }
1197 if ( rc ) {
1198 continue;
1199 } else {
1200 return 0;
1201 }
1202 }
1203 return 1;
1204 }
1205
1206 static int
substr_containment_substr(Operation * op,Filter * stored,Filter * incoming)1207 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
1208 {
1209 int rc = 0;
1210
1211 struct berval init_incoming;
1212 struct berval final_incoming;
1213 struct berval *remaining_incoming = NULL;
1214
1215 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
1216 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
1217 return 0;
1218
1219 init_incoming = incoming->f_sub_initial;
1220 final_incoming = incoming->f_sub_final;
1221
1222 if (find_and_remove(&init_incoming,
1223 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
1224 &(stored->f_sub_final), 3))
1225 {
1226 if (stored->f_sub_any == NULL) {
1227 rc = 1;
1228 goto final;
1229 }
1230 remaining_incoming = merge_init_final(op, &init_incoming,
1231 incoming->f_sub_any, &final_incoming);
1232 rc = strings_containment(stored->f_sub_any, remaining_incoming);
1233 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
1234 }
1235 final:
1236 return rc;
1237 }
1238
1239 static int
substr_containment_equality(Operation * op,Filter * stored,Filter * incoming)1240 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
1241 {
1242 struct berval incoming_val[2];
1243 int rc = 0;
1244
1245 incoming_val[1] = incoming->f_av_value;
1246
1247 if (find_and_remove(incoming_val+1,
1248 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
1249 &(stored->f_sub_final), 3)) {
1250 if (stored->f_sub_any == NULL){
1251 rc = 1;
1252 goto final;
1253 }
1254 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
1255 BER_BVZERO( incoming_val+1 );
1256 rc = strings_containment(stored->f_sub_any, incoming_val);
1257 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
1258 }
1259 final:
1260 return rc;
1261 }
1262
1263 static Filter *
filter_first(Filter * f)1264 filter_first( Filter *f )
1265 {
1266 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
1267 f = f->f_and;
1268 return f;
1269 }
1270
1271 typedef struct fstack {
1272 struct fstack *fs_next;
1273 Filter *fs_fs;
1274 Filter *fs_fi;
1275 } fstack;
1276
1277 static CachedQuery *
find_filter(Operation * op,TAvlnode * root,Filter * inputf,Filter * first)1278 find_filter( Operation *op, TAvlnode *root, Filter *inputf, Filter *first )
1279 {
1280 Filter* fs;
1281 Filter* fi;
1282 MatchingRule* mrule = NULL;
1283 int res=0, eqpass= 0;
1284 int ret, rc, dir;
1285 TAvlnode *ptr;
1286 CachedQuery cq, *qc;
1287 fstack *stack = NULL, *fsp;
1288
1289 cq.filter = inputf;
1290 cq.first = first;
1291
1292 /* substring matches sort to the end, and we just have to
1293 * walk the entire list.
1294 */
1295 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
1296 ptr = ldap_tavl_end( root, 1 );
1297 dir = TAVL_DIR_LEFT;
1298 } else {
1299 ptr = ldap_tavl_find3( root, &cq, pcache_query_cmp, &ret );
1300 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
1301 TAVL_DIR_RIGHT;
1302 }
1303
1304 while (ptr) {
1305 qc = ptr->avl_data;
1306 fi = inputf;
1307 fs = qc->filter;
1308
1309 /* an incoming substr query can only be satisfied by a cached
1310 * substr query.
1311 */
1312 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
1313 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1314 break;
1315
1316 /* an incoming eq query can be satisfied by a cached eq or substr
1317 * query
1318 */
1319 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
1320 if ( eqpass == 0 ) {
1321 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
1322 nextpass: eqpass = 1;
1323 ptr = ldap_tavl_end( root, 1 );
1324 dir = TAVL_DIR_LEFT;
1325 continue;
1326 }
1327 } else {
1328 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
1329 break;
1330 }
1331 }
1332 do {
1333 res=0;
1334 switch (fs->f_choice) {
1335 case LDAP_FILTER_EQUALITY:
1336 if (fi->f_choice == LDAP_FILTER_EQUALITY)
1337 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
1338 else
1339 ret = 1;
1340 break;
1341 case LDAP_FILTER_GE:
1342 case LDAP_FILTER_LE:
1343 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
1344 break;
1345 default:
1346 mrule = NULL;
1347 }
1348 if (mrule) {
1349 const char *text;
1350 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
1351 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
1352 &(fi->f_ava->aa_value),
1353 &(fs->f_ava->aa_value), &text);
1354 if (rc != LDAP_SUCCESS) {
1355 return NULL;
1356 }
1357 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
1358 goto nextpass;
1359 }
1360 switch (fs->f_choice) {
1361 case LDAP_FILTER_OR:
1362 case LDAP_FILTER_AND:
1363 if ( fs->f_next ) {
1364 /* save our stack position */
1365 fsp = op->o_tmpalloc(sizeof(fstack), op->o_tmpmemctx);
1366 fsp->fs_next = stack;
1367 fsp->fs_fs = fs->f_next;
1368 fsp->fs_fi = fi->f_next;
1369 stack = fsp;
1370 }
1371 fs = fs->f_and;
1372 fi = fi->f_and;
1373 res=1;
1374 break;
1375 case LDAP_FILTER_SUBSTRINGS:
1376 /* check if the equality query can be
1377 * answered with cached substring query */
1378 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
1379 && substr_containment_equality( op,
1380 fs, fi))
1381 res=1;
1382 /* check if the substring query can be
1383 * answered with cached substring query */
1384 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
1385 ) && substr_containment_substr( op,
1386 fs, fi))
1387 res= 1;
1388 fs=fs->f_next;
1389 fi=fi->f_next;
1390 break;
1391 case LDAP_FILTER_PRESENT:
1392 res=1;
1393 fs=fs->f_next;
1394 fi=fi->f_next;
1395 break;
1396 case LDAP_FILTER_EQUALITY:
1397 if (ret == 0)
1398 res = 1;
1399 fs=fs->f_next;
1400 fi=fi->f_next;
1401 break;
1402 case LDAP_FILTER_GE:
1403 if (mrule && ret >= 0)
1404 res = 1;
1405 fs=fs->f_next;
1406 fi=fi->f_next;
1407 break;
1408 case LDAP_FILTER_LE:
1409 if (mrule && ret <= 0)
1410 res = 1;
1411 fs=fs->f_next;
1412 fi=fi->f_next;
1413 break;
1414 case LDAP_FILTER_NOT:
1415 res=0;
1416 break;
1417 default:
1418 break;
1419 }
1420 if (!fs && !fi && stack) {
1421 /* pop the stack */
1422 fsp = stack;
1423 stack = fsp->fs_next;
1424 fs = fsp->fs_fs;
1425 fi = fsp->fs_fi;
1426 op->o_tmpfree(fsp, op->o_tmpmemctx);
1427 }
1428 } while((res) && (fi != NULL) && (fs != NULL));
1429
1430 if ( res )
1431 return qc;
1432 ptr = ldap_tavl_next( ptr, dir );
1433 }
1434 return NULL;
1435 }
1436
1437 /* check whether query is contained in any of
1438 * the cached queries in template
1439 */
1440 static CachedQuery *
query_containment(Operation * op,query_manager * qm,Query * query,QueryTemplate * templa)1441 query_containment(Operation *op, query_manager *qm,
1442 Query *query,
1443 QueryTemplate *templa)
1444 {
1445 CachedQuery* qc;
1446 int depth = 0, tscope;
1447 Qbase qbase, *qbptr = NULL;
1448 struct berval pdn;
1449
1450 if (query->filter != NULL) {
1451 Filter *first;
1452
1453 Debug( pcache_debug, "Lock QC index = %p\n",
1454 (void *) templa );
1455 qbase.base = query->base;
1456
1457 first = filter_first( query->filter );
1458
1459 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1460 for( ;; ) {
1461 /* Find the base */
1462 qbptr = ldap_avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1463 if ( qbptr ) {
1464 tscope = query->scope;
1465 /* Find a matching scope:
1466 * match at depth 0 OK
1467 * scope is BASE,
1468 * one at depth 1 OK
1469 * subord at depth > 0 OK
1470 * subtree at any depth OK
1471 * scope is ONE,
1472 * subtree or subord at any depth OK
1473 * scope is SUBORD,
1474 * subtree or subord at any depth OK
1475 * scope is SUBTREE,
1476 * subord at depth > 0 OK
1477 * subtree at any depth OK
1478 */
1479 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1480 switch ( query->scope ) {
1481 case LDAP_SCOPE_BASE:
1482 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1483 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1484 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1485 break;
1486 case LDAP_SCOPE_ONE:
1487 if ( tscope == LDAP_SCOPE_BASE )
1488 tscope = LDAP_SCOPE_ONE;
1489 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1490 if ( !depth ) break;
1491 if ( tscope < LDAP_SCOPE_SUBTREE )
1492 tscope = LDAP_SCOPE_SUBTREE;
1493 break;
1494 case LDAP_SCOPE_SUBTREE:
1495 if ( tscope < LDAP_SCOPE_SUBTREE )
1496 tscope = LDAP_SCOPE_SUBTREE;
1497 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1498 break;
1499 case LDAP_SCOPE_CHILDREN:
1500 if ( tscope < LDAP_SCOPE_SUBTREE )
1501 tscope = LDAP_SCOPE_SUBTREE;
1502 break;
1503 }
1504 if ( !qbptr->scopes[tscope] ) continue;
1505
1506 /* Find filter */
1507 qc = find_filter( op, qbptr->scopes[tscope],
1508 query->filter, first );
1509 if ( qc ) {
1510 if ( qc->q_sizelimit ) {
1511 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1512 return NULL;
1513 }
1514 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1515 if (qm->lru_top != qc) {
1516 remove_query(qm, qc);
1517 add_query_on_top(qm, qc);
1518 }
1519 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1520 return qc;
1521 }
1522 }
1523 }
1524 if ( be_issuffix( op->o_bd, &qbase.base ))
1525 break;
1526 /* Up a level */
1527 dnParent( &qbase.base, &pdn );
1528 qbase.base = pdn;
1529 depth++;
1530 }
1531
1532 Debug( pcache_debug,
1533 "Not answerable: Unlock QC index=%p\n",
1534 (void *) templa );
1535 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1536 }
1537 return NULL;
1538 }
1539
1540 static void
free_query(CachedQuery * qc)1541 free_query (CachedQuery* qc)
1542 {
1543 free(qc->q_uuid.bv_val);
1544 filter_free(qc->filter);
1545 ldap_pvt_thread_mutex_destroy(&qc->answerable_cnt_mutex);
1546 ldap_pvt_thread_rdwr_destroy( &qc->rwlock );
1547 memset(qc, 0, sizeof(*qc));
1548 free(qc);
1549 }
1550
1551
1552 /* Add query to query cache, the returned Query is locked for writing */
1553 static CachedQuery *
add_query(Operation * op,query_manager * qm,Query * query,QueryTemplate * templ,pc_caching_reason_t why,int wlock)1554 add_query(
1555 Operation *op,
1556 query_manager* qm,
1557 Query* query,
1558 QueryTemplate *templ,
1559 pc_caching_reason_t why,
1560 int wlock)
1561 {
1562 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1563 Qbase *qbase, qb;
1564 Filter *first;
1565 int rc;
1566 time_t ttl = 0, ttr = 0;
1567 time_t now;
1568
1569 new_cached_query->qtemp = templ;
1570 BER_BVZERO( &new_cached_query->q_uuid );
1571 new_cached_query->q_sizelimit = 0;
1572
1573 now = slap_get_time();
1574 switch ( why ) {
1575 case PC_POSITIVE:
1576 ttl = templ->ttl;
1577 if ( templ->ttr )
1578 ttr = now + templ->ttr;
1579 break;
1580
1581 case PC_NEGATIVE:
1582 ttl = templ->negttl;
1583 break;
1584
1585 case PC_SIZELIMIT:
1586 ttl = templ->limitttl;
1587 break;
1588
1589 default:
1590 assert( 0 );
1591 break;
1592 }
1593 new_cached_query->expiry_time = now + ttl;
1594 new_cached_query->refresh_time = ttr;
1595 new_cached_query->bindref_time = 0;
1596
1597 new_cached_query->bind_refcnt = 0;
1598 new_cached_query->answerable_cnt = 0;
1599 new_cached_query->refcnt = 1;
1600 ldap_pvt_thread_mutex_init(&new_cached_query->answerable_cnt_mutex);
1601
1602 new_cached_query->lru_up = NULL;
1603 new_cached_query->lru_down = NULL;
1604 Debug( pcache_debug, "Added query expires at %ld (%s)\n",
1605 (long) new_cached_query->expiry_time,
1606 pc_caching_reason_str[ why ] );
1607
1608 new_cached_query->scope = query->scope;
1609 new_cached_query->filter = query->filter;
1610 new_cached_query->first = first = filter_first( query->filter );
1611
1612 ldap_pvt_thread_rdwr_init(&new_cached_query->rwlock);
1613 if (wlock)
1614 ldap_pvt_thread_rdwr_wlock(&new_cached_query->rwlock);
1615
1616 qb.base = query->base;
1617
1618 /* Adding a query */
1619 Debug( pcache_debug, "Lock AQ index = %p\n",
1620 (void *) templ );
1621 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1622 qbase = ldap_avl_find( templ->qbase, &qb, pcache_dn_cmp );
1623 if ( !qbase ) {
1624 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1625 qbase->base.bv_len = qb.base.bv_len;
1626 qbase->base.bv_val = (char *)(qbase+1);
1627 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1628 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1629 ldap_avl_insert( &templ->qbase, qbase, pcache_dn_cmp, ldap_avl_dup_error );
1630 }
1631 new_cached_query->next = templ->query;
1632 new_cached_query->prev = NULL;
1633 new_cached_query->qbase = qbase;
1634 rc = ldap_tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1635 pcache_query_cmp, ldap_avl_dup_error );
1636 if ( rc == 0 ) {
1637 qbase->queries++;
1638 if (templ->query == NULL)
1639 templ->query_last = new_cached_query;
1640 else
1641 templ->query->prev = new_cached_query;
1642 templ->query = new_cached_query;
1643 templ->no_of_queries++;
1644 } else {
1645 ldap_pvt_thread_mutex_destroy(&new_cached_query->answerable_cnt_mutex);
1646 if (wlock)
1647 ldap_pvt_thread_rdwr_wunlock(&new_cached_query->rwlock);
1648 ldap_pvt_thread_rdwr_destroy( &new_cached_query->rwlock );
1649 ch_free( new_cached_query );
1650 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1651 query->filter, first );
1652 filter_free( query->filter );
1653 query->filter = NULL;
1654 }
1655 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1656 (void *) templ, templ->no_of_queries );
1657
1658 /* Adding on top of LRU list */
1659 if ( rc == 0 ) {
1660 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1661 add_query_on_top(qm, new_cached_query);
1662 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1663 }
1664 Debug( pcache_debug, "Unlock AQ index = %p \n",
1665 (void *) templ );
1666 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1667
1668 return rc == 0 ? new_cached_query : NULL;
1669 }
1670
1671 static void
remove_from_template(CachedQuery * qc,QueryTemplate * template)1672 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1673 {
1674 if (!qc->prev && !qc->next) {
1675 template->query_last = template->query = NULL;
1676 } else if (qc->prev == NULL) {
1677 qc->next->prev = NULL;
1678 template->query = qc->next;
1679 } else if (qc->next == NULL) {
1680 qc->prev->next = NULL;
1681 template->query_last = qc->prev;
1682 } else {
1683 qc->next->prev = qc->prev;
1684 qc->prev->next = qc->next;
1685 }
1686 ldap_tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_query_cmp );
1687 qc->qbase->queries--;
1688 if ( qc->qbase->queries == 0 ) {
1689 ldap_avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1690 ch_free( qc->qbase );
1691 qc->qbase = NULL;
1692 }
1693
1694 template->no_of_queries--;
1695 }
1696
1697 /* remove bottom query of LRU list from the query cache */
1698 /*
1699 * NOTE: slight change in functionality.
1700 *
1701 * - if result->bv_val is NULL, the query at the bottom of the LRU
1702 * is removed
1703 * - otherwise, the query whose UUID is *result is removed
1704 * - if not found, result->bv_val is zeroed
1705 */
1706 static void
cache_replacement(query_manager * qm,struct berval * result)1707 cache_replacement(query_manager* qm, struct berval *result)
1708 {
1709 CachedQuery* bottom;
1710 QueryTemplate *temp;
1711
1712 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1713 if ( BER_BVISNULL( result ) ) {
1714 bottom = qm->lru_bottom;
1715
1716 if (!bottom) {
1717 Debug ( pcache_debug,
1718 "Cache replacement invoked without "
1719 "any query in LRU list\n" );
1720 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1721 return;
1722 }
1723
1724 } else {
1725 for ( bottom = qm->lru_bottom;
1726 bottom != NULL;
1727 bottom = bottom->lru_up )
1728 {
1729 if ( bvmatch( result, &bottom->q_uuid ) ) {
1730 break;
1731 }
1732 }
1733
1734 if ( !bottom ) {
1735 Debug ( pcache_debug,
1736 "Could not find query with uuid=\"%s\""
1737 "in LRU list\n", result->bv_val );
1738 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1739 BER_BVZERO( result );
1740 return;
1741 }
1742 }
1743
1744 temp = bottom->qtemp;
1745 remove_query(qm, bottom);
1746 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1747
1748 *result = bottom->q_uuid;
1749 BER_BVZERO( &bottom->q_uuid );
1750
1751 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp );
1752 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1753 remove_from_template(bottom, temp);
1754 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1755 (void *) temp, temp->no_of_queries );
1756 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp );
1757 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1758 free_query(bottom);
1759 }
1760
1761 struct query_info {
1762 struct query_info *next;
1763 struct berval xdn;
1764 int del;
1765 };
1766
1767 static int
remove_func(Operation * op,SlapReply * rs)1768 remove_func (
1769 Operation *op,
1770 SlapReply *rs
1771 )
1772 {
1773 Attribute *attr;
1774 struct query_info *qi;
1775 int count = 0;
1776
1777 if ( rs->sr_type != REP_SEARCH ) return 0;
1778
1779 attr = attr_find( rs->sr_entry->e_attrs, ad_queryId );
1780 if ( attr == NULL ) return 0;
1781
1782 count = attr->a_numvals;
1783 assert( count > 0 );
1784 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1785 qi->next = op->o_callback->sc_private;
1786 op->o_callback->sc_private = qi;
1787 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1788 qi->del = ( count == 1 );
1789
1790 return 0;
1791 }
1792
1793 static int
remove_query_data(Operation * op,struct berval * query_uuid)1794 remove_query_data(
1795 Operation *op,
1796 struct berval *query_uuid )
1797 {
1798 struct query_info *qi, *qnext;
1799 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
1800 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
1801 Filter filter = {LDAP_FILTER_EQUALITY};
1802 SlapReply sreply = {REP_RESULT};
1803 slap_callback cb = { NULL, remove_func, NULL, NULL };
1804 int deleted = 0;
1805
1806 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1807 "(%s=%s)", ad_queryId->ad_cname.bv_val, query_uuid->bv_val);
1808 filter.f_ava = &ava;
1809 filter.f_av_desc = ad_queryId;
1810 filter.f_av_value = *query_uuid;
1811
1812 op->o_tag = LDAP_REQ_SEARCH;
1813 op->o_protocol = LDAP_VERSION3;
1814 op->o_callback = &cb;
1815 op->o_time = slap_get_time();
1816 op->o_do_not_cache = 1;
1817
1818 op->o_req_dn = op->o_bd->be_suffix[0];
1819 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1820 op->ors_scope = LDAP_SCOPE_SUBTREE;
1821 op->ors_deref = LDAP_DEREF_NEVER;
1822 op->ors_slimit = SLAP_NO_LIMIT;
1823 op->ors_tlimit = SLAP_NO_LIMIT;
1824 op->ors_limit = NULL;
1825 op->ors_filter = &filter;
1826 op->ors_filterstr.bv_val = filter_str;
1827 op->ors_filterstr.bv_len = strlen(filter_str);
1828 op->ors_attrs = NULL;
1829 op->ors_attrsonly = 0;
1830
1831 op->o_bd->be_search( op, &sreply );
1832
1833 for ( qi=cb.sc_private; qi; qi=qnext ) {
1834 qnext = qi->next;
1835
1836 op->o_req_dn = qi->xdn;
1837 op->o_req_ndn = qi->xdn;
1838 rs_reinit( &sreply, REP_RESULT );
1839
1840 if ( qi->del ) {
1841 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1842 query_uuid->bv_val );
1843
1844 op->o_tag = LDAP_REQ_DELETE;
1845
1846 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1847 deleted++;
1848 }
1849
1850 } else {
1851 Modifications mod;
1852 struct berval vals[2];
1853
1854 vals[0] = *query_uuid;
1855 vals[1].bv_val = NULL;
1856 vals[1].bv_len = 0;
1857 mod.sml_op = LDAP_MOD_DELETE;
1858 mod.sml_flags = 0;
1859 mod.sml_desc = ad_queryId;
1860 mod.sml_type = ad_queryId->ad_cname;
1861 mod.sml_values = vals;
1862 mod.sml_nvalues = NULL;
1863 mod.sml_numvals = 1;
1864 mod.sml_next = NULL;
1865 Debug( pcache_debug,
1866 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1867 query_uuid->bv_val );
1868
1869 op->orm_modlist = &mod;
1870
1871 op->o_bd->be_modify( op, &sreply );
1872 }
1873 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1874 op->o_tmpfree( qi, op->o_tmpmemctx );
1875 }
1876 return deleted;
1877 }
1878
1879 static int
1880 get_attr_set(
1881 AttributeName* attrs,
1882 query_manager* qm,
1883 int num
1884 );
1885
1886 static int
filter2template(Operation * op,Filter * f,struct berval * fstr)1887 filter2template(
1888 Operation *op,
1889 Filter *f,
1890 struct berval *fstr )
1891 {
1892 AttributeDescription *ad;
1893 int len, ret;
1894
1895 switch ( f->f_choice ) {
1896 case LDAP_FILTER_EQUALITY:
1897 ad = f->f_av_desc;
1898 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1899 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1900 assert( ret == len );
1901 fstr->bv_len += len;
1902 break;
1903
1904 case LDAP_FILTER_GE:
1905 ad = f->f_av_desc;
1906 len = STRLENOF( "(>=)" ) + ad->ad_cname.bv_len;
1907 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s>=)", ad->ad_cname.bv_val);
1908 assert( ret == len );
1909 fstr->bv_len += len;
1910 break;
1911
1912 case LDAP_FILTER_LE:
1913 ad = f->f_av_desc;
1914 len = STRLENOF( "(<=)" ) + ad->ad_cname.bv_len;
1915 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s<=)", ad->ad_cname.bv_val);
1916 assert( ret == len );
1917 fstr->bv_len += len;
1918 break;
1919
1920 case LDAP_FILTER_APPROX:
1921 ad = f->f_av_desc;
1922 len = STRLENOF( "(~=)" ) + ad->ad_cname.bv_len;
1923 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s~=)", ad->ad_cname.bv_val);
1924 assert( ret == len );
1925 fstr->bv_len += len;
1926 break;
1927
1928 case LDAP_FILTER_SUBSTRINGS:
1929 ad = f->f_sub_desc;
1930 len = STRLENOF( "(=)" ) + ad->ad_cname.bv_len;
1931 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=)", ad->ad_cname.bv_val );
1932 assert( ret == len );
1933 fstr->bv_len += len;
1934 break;
1935
1936 case LDAP_FILTER_PRESENT:
1937 ad = f->f_desc;
1938 len = STRLENOF( "(=*)" ) + ad->ad_cname.bv_len;
1939 ret = snprintf( fstr->bv_val+fstr->bv_len, len + 1, "(%s=*)", ad->ad_cname.bv_val );
1940 assert( ret == len );
1941 fstr->bv_len += len;
1942 break;
1943
1944 case LDAP_FILTER_AND:
1945 case LDAP_FILTER_OR:
1946 case LDAP_FILTER_NOT: {
1947 int rc = 0;
1948 fstr->bv_val[fstr->bv_len++] = '(';
1949 switch ( f->f_choice ) {
1950 case LDAP_FILTER_AND:
1951 fstr->bv_val[fstr->bv_len] = '&';
1952 break;
1953 case LDAP_FILTER_OR:
1954 fstr->bv_val[fstr->bv_len] = '|';
1955 break;
1956 case LDAP_FILTER_NOT:
1957 fstr->bv_val[fstr->bv_len] = '!';
1958 break;
1959 }
1960 fstr->bv_len++;
1961
1962 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1963 rc = filter2template( op, f, fstr );
1964 if ( rc ) break;
1965 }
1966 fstr->bv_val[fstr->bv_len++] = ')';
1967 fstr->bv_val[fstr->bv_len] = '\0';
1968
1969 return rc;
1970 }
1971
1972 default:
1973 /* a filter should at least have room for "()",
1974 * an "=" and for a 1-char attr */
1975 strcpy( fstr->bv_val, "(?=)" );
1976 fstr->bv_len += STRLENOF("(?=)");
1977 return -1;
1978 }
1979
1980 return 0;
1981 }
1982
1983 #define BI_HASHED 0x01
1984 #define BI_DIDCB 0x02
1985 #define BI_LOOKUP 0x04
1986
1987 struct search_info;
1988
1989 typedef struct bindinfo {
1990 cache_manager *bi_cm;
1991 CachedQuery *bi_cq;
1992 QueryTemplate *bi_templ;
1993 struct search_info *bi_si;
1994 int bi_flags;
1995 slap_callback bi_cb;
1996 } bindinfo;
1997
1998 struct search_info {
1999 slap_overinst *on;
2000 Query query;
2001 QueryTemplate *qtemp;
2002 AttributeName* save_attrs; /* original attributes, saved for response */
2003 int swap_saved_attrs;
2004 int max;
2005 int over;
2006 int count;
2007 int slimit;
2008 int slimit_exceeded;
2009 pc_caching_reason_t caching_reason;
2010 Entry *head, *tail;
2011 bindinfo *pbi;
2012 };
2013
2014 static void
remove_query_and_data(Operation * op,cache_manager * cm,struct berval * uuid)2015 remove_query_and_data(
2016 Operation *op,
2017 cache_manager *cm,
2018 struct berval *uuid )
2019 {
2020 query_manager* qm = cm->qm;
2021
2022 qm->crfunc( qm, uuid );
2023 if ( !BER_BVISNULL( uuid ) ) {
2024 int return_val;
2025
2026 Debug( pcache_debug,
2027 "Removing query UUID %s\n",
2028 uuid->bv_val );
2029 return_val = remove_query_data( op, uuid );
2030 Debug( pcache_debug,
2031 "QUERY REMOVED, SIZE=%d\n",
2032 return_val );
2033 ldap_pvt_thread_mutex_lock( &cm->cache_mutex );
2034 cm->cur_entries -= return_val;
2035 cm->num_cached_queries--;
2036 Debug( pcache_debug,
2037 "STORED QUERIES = %lu\n",
2038 cm->num_cached_queries );
2039 ldap_pvt_thread_mutex_unlock( &cm->cache_mutex );
2040 Debug( pcache_debug,
2041 "QUERY REMOVED, CACHE ="
2042 "%d entries\n",
2043 cm->cur_entries );
2044 }
2045 }
2046
2047 /*
2048 * Callback used to fetch queryId values based on entryUUID;
2049 * used by pcache_remove_entries_from_cache()
2050 */
2051 static int
fetch_queryId_cb(Operation * op,SlapReply * rs)2052 fetch_queryId_cb( Operation *op, SlapReply *rs )
2053 {
2054 int rc = 0;
2055
2056 /* only care about searchEntry responses */
2057 if ( rs->sr_type != REP_SEARCH ) {
2058 return 0;
2059 }
2060
2061 /* allow only one response per entryUUID */
2062 if ( op->o_callback->sc_private != NULL ) {
2063 rc = 1;
2064
2065 } else {
2066 Attribute *a;
2067
2068 /* copy all queryId values into callback's private data */
2069 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
2070 if ( a != NULL ) {
2071 BerVarray vals = NULL;
2072
2073 ber_bvarray_dup_x( &vals, a->a_nvals, op->o_tmpmemctx );
2074 op->o_callback->sc_private = (void *)vals;
2075 }
2076 }
2077
2078 /* clear entry if required */
2079 rs_flush_entry( op, rs, (slap_overinst *) op->o_bd->bd_info );
2080
2081 return rc;
2082 }
2083
2084 /*
2085 * Call that allows to remove a set of entries from the cache,
2086 * by forcing the removal of all the related queries.
2087 */
2088 int
pcache_remove_entries_from_cache(Operation * op,cache_manager * cm,BerVarray entryUUIDs)2089 pcache_remove_entries_from_cache(
2090 Operation *op,
2091 cache_manager *cm,
2092 BerVarray entryUUIDs )
2093 {
2094 Connection conn = { 0 };
2095 OperationBuffer opbuf;
2096 Operation op2;
2097 slap_callback sc = { 0 };
2098 Filter f = { 0 };
2099 char filtbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(entryUUID=)" ) ];
2100 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2101 AttributeName attrs[ 2 ] = {{{ 0 }}};
2102 int s, rc;
2103
2104 if ( op == NULL ) {
2105 void *thrctx = ldap_pvt_thread_pool_context();
2106
2107 connection_fake_init( &conn, &opbuf, thrctx );
2108 op = &opbuf.ob_op;
2109
2110 } else {
2111 op2 = *op;
2112 op = &op2;
2113 }
2114
2115 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2116 op->ors_scope = LDAP_SCOPE_SUBTREE;
2117 op->ors_deref = LDAP_DEREF_NEVER;
2118 f.f_choice = LDAP_FILTER_EQUALITY;
2119 f.f_ava = &ava;
2120 ava.aa_desc = slap_schema.si_ad_entryUUID;
2121 op->ors_filter = &f;
2122 op->ors_slimit = 1;
2123 op->ors_tlimit = SLAP_NO_LIMIT;
2124 op->ors_limit = NULL;
2125 attrs[ 0 ].an_desc = ad_queryId;
2126 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2127 op->ors_attrs = attrs;
2128 op->ors_attrsonly = 0;
2129
2130 op->o_req_dn = cm->db.be_suffix[ 0 ];
2131 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2132
2133 op->o_tag = LDAP_REQ_SEARCH;
2134 op->o_protocol = LDAP_VERSION3;
2135 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2136 op->o_bd = &cm->db;
2137 op->o_dn = op->o_bd->be_rootdn;
2138 op->o_ndn = op->o_bd->be_rootndn;
2139 sc.sc_response = fetch_queryId_cb;
2140 op->o_callback = ≻
2141
2142 for ( s = 0; !BER_BVISNULL( &entryUUIDs[ s ] ); s++ ) {
2143 BerVarray vals = NULL;
2144 SlapReply rs = { REP_RESULT };
2145
2146 op->ors_filterstr.bv_len = snprintf( filtbuf, sizeof( filtbuf ),
2147 "(entryUUID=%s)", entryUUIDs[ s ].bv_val );
2148 op->ors_filterstr.bv_val = filtbuf;
2149 ava.aa_value = entryUUIDs[ s ];
2150
2151 rc = op->o_bd->be_search( op, &rs );
2152 if ( rc != LDAP_SUCCESS ) {
2153 continue;
2154 }
2155
2156 vals = (BerVarray)op->o_callback->sc_private;
2157 if ( vals != NULL ) {
2158 int i;
2159
2160 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2161 struct berval val = vals[ i ];
2162
2163 remove_query_and_data( op, cm, &val );
2164
2165 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2166 ch_free( val.bv_val );
2167 }
2168 }
2169
2170 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2171 op->o_callback->sc_private = NULL;
2172 }
2173 }
2174
2175 return 0;
2176 }
2177
2178 /*
2179 * Call that allows to remove a query from the cache.
2180 */
2181 int
pcache_remove_query_from_cache(Operation * op,cache_manager * cm,struct berval * queryid)2182 pcache_remove_query_from_cache(
2183 Operation *op,
2184 cache_manager *cm,
2185 struct berval *queryid )
2186 {
2187 Operation op2 = *op;
2188
2189 op2.o_bd = &cm->db;
2190
2191 /* remove the selected query */
2192 remove_query_and_data( &op2, cm, queryid );
2193
2194 return LDAP_SUCCESS;
2195 }
2196
2197 /*
2198 * Call that allows to remove a set of queries related to an entry
2199 * from the cache; if queryid is not null, the entry must belong to
2200 * the query indicated by queryid.
2201 */
2202 int
pcache_remove_entry_queries_from_cache(Operation * op,cache_manager * cm,struct berval * ndn,struct berval * queryid)2203 pcache_remove_entry_queries_from_cache(
2204 Operation *op,
2205 cache_manager *cm,
2206 struct berval *ndn,
2207 struct berval *queryid )
2208 {
2209 Connection conn = { 0 };
2210 OperationBuffer opbuf;
2211 Operation op2;
2212 slap_callback sc = { 0 };
2213 SlapReply rs = { REP_RESULT };
2214 Filter f = { 0 };
2215 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
2216 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2217 AttributeName attrs[ 2 ] = {{{ 0 }}};
2218 int rc;
2219
2220 BerVarray vals = NULL;
2221
2222 if ( op == NULL ) {
2223 void *thrctx = ldap_pvt_thread_pool_context();
2224
2225 connection_fake_init( &conn, &opbuf, thrctx );
2226 op = &opbuf.ob_op;
2227
2228 } else {
2229 op2 = *op;
2230 op = &op2;
2231 }
2232
2233 memset( &op->oq_search, 0, sizeof( op->oq_search ) );
2234 op->ors_scope = LDAP_SCOPE_BASE;
2235 op->ors_deref = LDAP_DEREF_NEVER;
2236 if ( queryid == NULL || BER_BVISNULL( queryid ) ) {
2237 BER_BVSTR( &op->ors_filterstr, "(objectClass=*)" );
2238 f.f_choice = LDAP_FILTER_PRESENT;
2239 f.f_desc = slap_schema.si_ad_objectClass;
2240
2241 } else {
2242 op->ors_filterstr.bv_len = snprintf( filter_str,
2243 sizeof( filter_str ), "(%s=%s)",
2244 ad_queryId->ad_cname.bv_val, queryid->bv_val );
2245 f.f_choice = LDAP_FILTER_EQUALITY;
2246 f.f_ava = &ava;
2247 f.f_av_desc = ad_queryId;
2248 f.f_av_value = *queryid;
2249 }
2250 op->ors_filter = &f;
2251 op->ors_slimit = 1;
2252 op->ors_tlimit = SLAP_NO_LIMIT;
2253 op->ors_limit = NULL;
2254 attrs[ 0 ].an_desc = ad_queryId;
2255 attrs[ 0 ].an_name = ad_queryId->ad_cname;
2256 op->ors_attrs = attrs;
2257 op->ors_attrsonly = 0;
2258
2259 op->o_req_dn = *ndn;
2260 op->o_req_ndn = *ndn;
2261
2262 op->o_tag = LDAP_REQ_SEARCH;
2263 op->o_protocol = LDAP_VERSION3;
2264 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2265 op->o_bd = &cm->db;
2266 op->o_dn = op->o_bd->be_rootdn;
2267 op->o_ndn = op->o_bd->be_rootndn;
2268 sc.sc_response = fetch_queryId_cb;
2269 op->o_callback = ≻
2270
2271 rc = op->o_bd->be_search( op, &rs );
2272 if ( rc != LDAP_SUCCESS ) {
2273 return rc;
2274 }
2275
2276 vals = (BerVarray)op->o_callback->sc_private;
2277 if ( vals != NULL ) {
2278 int i;
2279
2280 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2281 struct berval val = vals[ i ];
2282
2283 remove_query_and_data( op, cm, &val );
2284
2285 if ( !BER_BVISNULL( &val ) && val.bv_val != vals[ i ].bv_val ) {
2286 ch_free( val.bv_val );
2287 }
2288 }
2289
2290 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2291 }
2292
2293 return LDAP_SUCCESS;
2294 }
2295
2296 static int
cache_entries(Operation * op,struct berval * query_uuid)2297 cache_entries(
2298 Operation *op,
2299 struct berval *query_uuid )
2300 {
2301 struct search_info *si = op->o_callback->sc_private;
2302 slap_overinst *on = si->on;
2303 cache_manager *cm = on->on_bi.bi_private;
2304 int return_val = 0;
2305 Entry *e;
2306 struct berval crp_uuid;
2307 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
2308 Operation *op_tmp;
2309 Connection conn = {0};
2310 OperationBuffer opbuf;
2311 void *thrctx = ldap_pvt_thread_pool_context();
2312
2313 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
2314 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
2315
2316 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
2317 op_tmp = &opbuf.ob_op;
2318 op_tmp->o_bd = &cm->db;
2319 op_tmp->o_dn = cm->db.be_rootdn;
2320 op_tmp->o_ndn = cm->db.be_rootndn;
2321
2322 Debug( pcache_debug, "UUID for query being added = %s\n",
2323 uuidbuf );
2324
2325 for ( e=si->head; e; e=si->head ) {
2326 si->head = e->e_private;
2327 e->e_private = NULL;
2328 while ( cm->cur_entries > (cm->max_entries) ) {
2329 BER_BVZERO( &crp_uuid );
2330 remove_query_and_data( op_tmp, cm, &crp_uuid );
2331 }
2332
2333 return_val = merge_entry(op_tmp, e, 0, query_uuid);
2334 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2335 cm->cur_entries += return_val;
2336 Debug( pcache_debug,
2337 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
2338 cm->cur_entries );
2339 return_val = 0;
2340 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2341 }
2342
2343 return return_val;
2344 }
2345
2346 static int
pcache_op_cleanup(Operation * op,SlapReply * rs)2347 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
2348 slap_callback *cb = op->o_callback;
2349 struct search_info *si = cb->sc_private;
2350 slap_overinst *on = si->on;
2351 cache_manager *cm = on->on_bi.bi_private;
2352 query_manager* qm = cm->qm;
2353
2354 if ( rs->sr_type == REP_RESULT ||
2355 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
2356 {
2357 if ( si->swap_saved_attrs ) {
2358 rs->sr_attrs = si->save_attrs;
2359 op->ors_attrs = si->save_attrs;
2360 }
2361 if ( (op->o_abandon || rs->sr_err == SLAPD_ABANDON) &&
2362 si->caching_reason == PC_IGNORE )
2363 {
2364 filter_free( si->query.filter );
2365 if ( si->count ) {
2366 /* duplicate query, free it */
2367 Entry *e;
2368 for (;si->head; si->head=e) {
2369 e = si->head->e_private;
2370 si->head->e_private = NULL;
2371 entry_free(si->head);
2372 }
2373 }
2374
2375 } else if ( si->caching_reason != PC_IGNORE ) {
2376 CachedQuery *qc = qm->addfunc(op, qm, &si->query,
2377 si->qtemp, si->caching_reason, 1 );
2378
2379 if ( qc != NULL ) {
2380 switch ( si->caching_reason ) {
2381 case PC_POSITIVE:
2382 cache_entries( op, &qc->q_uuid );
2383 if ( si->pbi ) {
2384 qc->bind_refcnt++;
2385 si->pbi->bi_cq = qc;
2386 }
2387 break;
2388
2389 case PC_SIZELIMIT:
2390 qc->q_sizelimit = rs->sr_nentries;
2391 break;
2392
2393 case PC_NEGATIVE:
2394 break;
2395
2396 default:
2397 assert( 0 );
2398 break;
2399 }
2400 ldap_pvt_thread_rdwr_wunlock(&qc->rwlock);
2401 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2402 cm->num_cached_queries++;
2403 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2404 cm->num_cached_queries );
2405 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2406
2407 /* If the consistency checker suspended itself,
2408 * wake it back up
2409 */
2410 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2411 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2412 if ( cm->cc_paused == PCACHE_CC_PAUSED ) {
2413 cm->cc_paused = 0;
2414 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
2415 }
2416 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2417 }
2418
2419 } else if ( si->count ) {
2420 /* duplicate query, free it */
2421 Entry *e;
2422 for (;si->head; si->head=e) {
2423 e = si->head->e_private;
2424 si->head->e_private = NULL;
2425 entry_free(si->head);
2426 }
2427 }
2428
2429 } else {
2430 filter_free( si->query.filter );
2431 }
2432
2433 op->o_callback = op->o_callback->sc_next;
2434 op->o_tmpfree( cb, op->o_tmpmemctx );
2435 }
2436
2437 return SLAP_CB_CONTINUE;
2438 }
2439
2440 static int
pcache_response(Operation * op,SlapReply * rs)2441 pcache_response(
2442 Operation *op,
2443 SlapReply *rs )
2444 {
2445 struct search_info *si = op->o_callback->sc_private;
2446
2447 if ( si->swap_saved_attrs ) {
2448 rs->sr_attrs = si->save_attrs;
2449 rs->sr_attr_flags = slap_attr_flags( si->save_attrs );
2450 op->ors_attrs = si->save_attrs;
2451 }
2452
2453 if ( rs->sr_type == REP_SEARCH ) {
2454 Entry *e;
2455
2456 /* don't return more entries than requested by the client */
2457 if ( si->slimit > 0 && rs->sr_nentries >= si->slimit ) {
2458 si->slimit_exceeded = 1;
2459 }
2460
2461 /* If we haven't exceeded the limit for this query,
2462 * build a chain of answers to store. If we hit the
2463 * limit, empty the chain and ignore the rest.
2464 */
2465 if ( !si->over ) {
2466 slap_overinst *on = si->on;
2467 cache_manager *cm = on->on_bi.bi_private;
2468
2469 /* check if the entry contains undefined
2470 * attributes/objectClasses (ITS#5680) */
2471 if ( cm->check_cacheability && test_filter( op, rs->sr_entry, si->query.filter ) != LDAP_COMPARE_TRUE ) {
2472 Debug( pcache_debug, "%s: query not cacheable because of schema issues in DN \"%s\"\n",
2473 op->o_log_prefix, rs->sr_entry->e_name.bv_val );
2474 goto over;
2475 }
2476
2477 /* check for malformed entries: attrs with no values */
2478 {
2479 Attribute *a = rs->sr_entry->e_attrs;
2480 for (; a; a=a->a_next) {
2481 if ( !a->a_numvals ) {
2482 Debug( pcache_debug, "%s: query not cacheable because of attrs without values in DN \"%s\" (%s)\n",
2483 op->o_log_prefix, rs->sr_entry->e_name.bv_val,
2484 a->a_desc->ad_cname.bv_val );
2485 goto over;
2486 }
2487 }
2488 }
2489
2490 if ( si->count < si->max ) {
2491 si->count++;
2492 e = entry_dup( rs->sr_entry );
2493 if ( !si->head ) si->head = e;
2494 if ( si->tail ) si->tail->e_private = e;
2495 si->tail = e;
2496
2497 } else {
2498 over:;
2499 si->over = 1;
2500 si->count = 0;
2501 for (;si->head; si->head=e) {
2502 e = si->head->e_private;
2503 si->head->e_private = NULL;
2504 entry_free(si->head);
2505 }
2506 si->tail = NULL;
2507 }
2508 }
2509 if ( si->slimit_exceeded ) {
2510 return 0;
2511 }
2512 } else if ( rs->sr_type == REP_RESULT ) {
2513
2514 if ( si->count ) {
2515 if ( rs->sr_err == LDAP_SUCCESS ) {
2516 si->caching_reason = PC_POSITIVE;
2517
2518 } else if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED
2519 && si->qtemp->limitttl )
2520 {
2521 Entry *e;
2522
2523 si->caching_reason = PC_SIZELIMIT;
2524 for (;si->head; si->head=e) {
2525 e = si->head->e_private;
2526 si->head->e_private = NULL;
2527 entry_free(si->head);
2528 }
2529 }
2530
2531 } else if ( si->qtemp->negttl && !si->count && !si->over &&
2532 rs->sr_err == LDAP_SUCCESS )
2533 {
2534 si->caching_reason = PC_NEGATIVE;
2535 }
2536
2537
2538 if ( si->slimit_exceeded ) {
2539 rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2540 }
2541 }
2542
2543 return SLAP_CB_CONTINUE;
2544 }
2545
2546 /* NOTE: this is a quick workaround to let pcache minimally interact
2547 * with pagedResults. A more articulated solutions would be to
2548 * perform the remote query without control and cache all results,
2549 * performing the pagedResults search only within the client
2550 * and the proxy. This requires pcache to understand pagedResults. */
2551 static int
pcache_chk_controls(Operation * op,SlapReply * rs)2552 pcache_chk_controls(
2553 Operation *op,
2554 SlapReply *rs )
2555 {
2556 const char *non = "";
2557 const char *stripped = "";
2558
2559 switch( op->o_pagedresults ) {
2560 case SLAP_CONTROL_NONCRITICAL:
2561 non = "non-";
2562 stripped = "; stripped";
2563 /* fallthru */
2564
2565 case SLAP_CONTROL_CRITICAL:
2566 Debug( pcache_debug, "%s: "
2567 "%scritical pagedResults control "
2568 "disabled with proxy cache%s.\n",
2569 op->o_log_prefix, non, stripped );
2570
2571 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
2572 break;
2573
2574 default:
2575 rs->sr_err = SLAP_CB_CONTINUE;
2576 break;
2577 }
2578
2579 return rs->sr_err;
2580 }
2581
2582 static int
pc_setpw(Operation * op,struct berval * pwd,cache_manager * cm)2583 pc_setpw( Operation *op, struct berval *pwd, cache_manager *cm )
2584 {
2585 struct berval vals[2];
2586
2587 {
2588 const char *text = NULL;
2589 BER_BVZERO( &vals[0] );
2590 slap_passwd_hash( pwd, &vals[0], &text );
2591 if ( BER_BVISEMPTY( &vals[0] )) {
2592 Debug( pcache_debug, "pc_setpw: hash failed %s\n",
2593 text );
2594 return LDAP_OTHER;
2595 }
2596 }
2597
2598 BER_BVZERO( &vals[1] );
2599
2600 {
2601 Modifications mod;
2602 SlapReply sr = { REP_RESULT };
2603 slap_callback cb = { 0, slap_null_cb, 0, 0 };
2604 int rc;
2605
2606 mod.sml_op = LDAP_MOD_REPLACE;
2607 mod.sml_flags = 0;
2608 mod.sml_desc = slap_schema.si_ad_userPassword;
2609 mod.sml_type = mod.sml_desc->ad_cname;
2610 mod.sml_values = vals;
2611 mod.sml_nvalues = NULL;
2612 mod.sml_numvals = 1;
2613 mod.sml_next = NULL;
2614
2615 op->o_tag = LDAP_REQ_MODIFY;
2616 op->orm_modlist = &mod;
2617 op->o_bd = &cm->db;
2618 op->o_dn = op->o_bd->be_rootdn;
2619 op->o_ndn = op->o_bd->be_rootndn;
2620 op->o_callback = &cb;
2621 Debug( pcache_debug, "pc_setpw: CACHING BIND for %s\n",
2622 op->o_req_dn.bv_val );
2623 rc = op->o_bd->be_modify( op, &sr );
2624 ch_free( vals[0].bv_val );
2625 return rc;
2626 }
2627 }
2628
2629 typedef struct bindcacheinfo {
2630 slap_overinst *on;
2631 CachedQuery *qc;
2632 } bindcacheinfo;
2633
2634 static int
pc_bind_save(Operation * op,SlapReply * rs)2635 pc_bind_save( Operation *op, SlapReply *rs )
2636 {
2637 if ( rs->sr_err == LDAP_SUCCESS ) {
2638 bindcacheinfo *bci = op->o_callback->sc_private;
2639 slap_overinst *on = bci->on;
2640 cache_manager *cm = on->on_bi.bi_private;
2641 CachedQuery *qc = bci->qc;
2642 int delete = 0;
2643
2644 ldap_pvt_thread_rdwr_wlock( &qc->rwlock );
2645 if ( qc->bind_refcnt-- ) {
2646 Operation op2 = *op;
2647 if ( pc_setpw( &op2, &op->orb_cred, cm ) == LDAP_SUCCESS )
2648 bci->qc->bindref_time = op->o_time + bci->qc->qtemp->bindttr;
2649 } else {
2650 bci->qc = NULL;
2651 delete = 1;
2652 }
2653 ldap_pvt_thread_rdwr_wunlock( &qc->rwlock );
2654 if ( delete ) free_query(qc);
2655 }
2656 return SLAP_CB_CONTINUE;
2657 }
2658
2659 static Filter *
pc_bind_attrs(Operation * op,Entry * e,QueryTemplate * temp,struct berval * fbv)2660 pc_bind_attrs( Operation *op, Entry *e, QueryTemplate *temp,
2661 struct berval *fbv )
2662 {
2663 int i, len = 0;
2664 struct berval *vals, pres = BER_BVC("*");
2665 char *p1, *p2;
2666 Attribute *a;
2667
2668 vals = op->o_tmpalloc( temp->bindnattrs * sizeof( struct berval ),
2669 op->o_tmpmemctx );
2670
2671 for ( i=0; i<temp->bindnattrs; i++ ) {
2672 a = attr_find( e->e_attrs, temp->bindfattrs[i] );
2673 if ( a && a->a_vals ) {
2674 vals[i] = a->a_vals[0];
2675 len += a->a_vals[0].bv_len;
2676 } else {
2677 vals[i] = pres;
2678 }
2679 }
2680 fbv->bv_len = len + temp->bindftemp.bv_len;
2681 fbv->bv_val = op->o_tmpalloc( fbv->bv_len + 1, op->o_tmpmemctx );
2682
2683 p1 = temp->bindftemp.bv_val;
2684 p2 = fbv->bv_val;
2685 i = 0;
2686 while ( *p1 ) {
2687 *p2++ = *p1;
2688 if ( p1[0] == '=' && p1[1] == ')' ) {
2689 AC_MEMCPY( p2, vals[i].bv_val, vals[i].bv_len );
2690 p2 += vals[i].bv_len;
2691 i++;
2692 }
2693 p1++;
2694 }
2695 *p2 = '\0';
2696 op->o_tmpfree( vals, op->o_tmpmemctx );
2697
2698 /* FIXME: are we sure str2filter_x can't fail?
2699 * caller needs to check */
2700 {
2701 Filter *f = str2filter_x( op, fbv->bv_val );
2702 assert( f != NULL );
2703 return f;
2704 }
2705 }
2706
2707 /* Check if the requested entry is from the cache and has a valid
2708 * ttr and password hash
2709 */
2710 static int
pc_bind_search(Operation * op,SlapReply * rs)2711 pc_bind_search( Operation *op, SlapReply *rs )
2712 {
2713 if ( rs->sr_type == REP_SEARCH ) {
2714 bindinfo *pbi = op->o_callback->sc_private;
2715
2716 /* We only care if this is an already cached result and we're
2717 * below the refresh time, or we're offline.
2718 */
2719 if ( pbi->bi_cq ) {
2720 if (( pbi->bi_cm->cc_paused & PCACHE_CC_OFFLINE ) ||
2721 op->o_time < pbi->bi_cq->bindref_time ) {
2722 Attribute *a;
2723
2724 /* See if a recognized password is hashed here */
2725 a = attr_find( rs->sr_entry->e_attrs,
2726 slap_schema.si_ad_userPassword );
2727 if ( a && a->a_vals[0].bv_val[0] == '{' &&
2728 lutil_passwd_scheme( a->a_vals[0].bv_val ))
2729 pbi->bi_flags |= BI_HASHED;
2730 } else {
2731 Debug( pcache_debug, "pc_bind_search: cache is stale, "
2732 "reftime: %ld, current time: %ld\n",
2733 pbi->bi_cq->bindref_time, op->o_time );
2734 }
2735 } else if ( pbi->bi_si ) {
2736 /* This search result is going into the cache */
2737 struct berval fbv;
2738 Filter *f;
2739
2740 filter_free( pbi->bi_si->query.filter );
2741 f = pc_bind_attrs( op, rs->sr_entry, pbi->bi_templ, &fbv );
2742 op->o_tmpfree( fbv.bv_val, op->o_tmpmemctx );
2743 pbi->bi_si->query.filter = filter_dup( f, NULL );
2744 filter_free_x( op, f, 1 );
2745 }
2746 }
2747 return 0;
2748 }
2749
2750 /* We always want pc_bind_search to run after the search handlers */
2751 static int
pc_bind_resp(Operation * op,SlapReply * rs)2752 pc_bind_resp( Operation *op, SlapReply *rs )
2753 {
2754 bindinfo *pbi = op->o_callback->sc_private;
2755 if ( !( pbi->bi_flags & BI_DIDCB )) {
2756 slap_callback *sc = op->o_callback;
2757 while ( sc && sc->sc_response != pcache_response )
2758 sc = sc->sc_next;
2759 if ( !sc )
2760 sc = op->o_callback;
2761 pbi->bi_cb.sc_next = sc->sc_next;
2762 sc->sc_next = &pbi->bi_cb;
2763 pbi->bi_flags |= BI_DIDCB;
2764 }
2765 return SLAP_CB_CONTINUE;
2766 }
2767
2768 #ifdef PCACHE_CONTROL_PRIVDB
2769 static int
pcache_op_privdb(Operation * op,SlapReply * rs)2770 pcache_op_privdb(
2771 Operation *op,
2772 SlapReply *rs )
2773 {
2774 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2775 cache_manager *cm = on->on_bi.bi_private;
2776 slap_callback *save_cb;
2777 slap_op_t type;
2778
2779 /* skip if control is unset */
2780 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_CRITICAL ) {
2781 return SLAP_CB_CONTINUE;
2782 }
2783
2784 /* The cache DB isn't open yet */
2785 if ( cm->defer_db_open ) {
2786 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2787 "pcachePrivDB: cacheDB not available" );
2788 return rs->sr_err;
2789 }
2790
2791 /* FIXME: might be a little bit exaggerated... */
2792 if ( !be_isroot( op ) ) {
2793 save_cb = op->o_callback;
2794 op->o_callback = NULL;
2795 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2796 "pcachePrivDB: operation not allowed" );
2797 op->o_callback = save_cb;
2798
2799 return rs->sr_err;
2800 }
2801
2802 /* map tag to operation */
2803 type = slap_req2op( op->o_tag );
2804 if ( type != SLAP_OP_LAST ) {
2805 BackendInfo *bi = cm->db.bd_info;
2806 int rc;
2807
2808 /* execute, if possible */
2809 if ( (&bi->bi_op_bind)[ type ] ) {
2810 Operation op2 = *op;
2811
2812 op2.o_bd = &cm->db;
2813
2814 rc = (&bi->bi_op_bind)[ type ]( &op2, rs );
2815 if ( type == SLAP_OP_BIND && rc == LDAP_SUCCESS ) {
2816 op->o_conn->c_authz_cookie = cm->db.be_private;
2817 }
2818
2819 return rs->sr_err;
2820 }
2821 }
2822
2823 /* otherwise fall back to error */
2824 save_cb = op->o_callback;
2825 op->o_callback = NULL;
2826 send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
2827 "operation not supported with pcachePrivDB control" );
2828 op->o_callback = save_cb;
2829
2830 return rs->sr_err;
2831 }
2832 #endif /* PCACHE_CONTROL_PRIVDB */
2833
2834 static int
pcache_op_bind(Operation * op,SlapReply * rs)2835 pcache_op_bind(
2836 Operation *op,
2837 SlapReply *rs )
2838 {
2839 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2840 cache_manager *cm = on->on_bi.bi_private;
2841 QueryTemplate *temp;
2842 Entry *e;
2843 slap_callback cb = { 0 }, *sc;
2844 bindinfo bi = { 0 };
2845 bindcacheinfo *bci;
2846 Operation op2;
2847 int rc;
2848
2849 #ifdef PCACHE_CONTROL_PRIVDB
2850 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL )
2851 return pcache_op_privdb( op, rs );
2852 #endif /* PCACHE_CONTROL_PRIVDB */
2853
2854 /* Skip if we're not configured for Binds, or cache DB isn't open yet */
2855 if ( !cm->cache_binds || cm->defer_db_open )
2856 return SLAP_CB_CONTINUE;
2857
2858 /* First find a matching template with Bind info */
2859 for ( temp=cm->qm->templates; temp; temp=temp->qmnext ) {
2860 if ( temp->bindttr && dnIsSuffix( &op->o_req_ndn, &temp->bindbase ))
2861 break;
2862 }
2863 /* Didn't find a suitable template, just passthru */
2864 if ( !temp )
2865 return SLAP_CB_CONTINUE;
2866
2867 /* See if the entry is already locally cached. If so, we can
2868 * populate the query filter to retrieve the cached query. We
2869 * need to check the bindrefresh time in the query.
2870 */
2871 op2 = *op;
2872 op2.o_dn = op->o_bd->be_rootdn;
2873 op2.o_ndn = op->o_bd->be_rootndn;
2874
2875 op2.o_bd = &cm->db;
2876 e = NULL;
2877 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL, NULL, 0, &e );
2878 if ( rc == LDAP_SUCCESS && e ) {
2879 bi.bi_flags |= BI_LOOKUP;
2880 op2.ors_filter = pc_bind_attrs( op, e, temp, &op2.ors_filterstr );
2881 be_entry_release_r( &op2, e );
2882 } else {
2883 op2.ors_filter = temp->bindfilter;
2884 op2.ors_filterstr = temp->bindfilterstr;
2885 }
2886
2887 op2.o_bd = op->o_bd;
2888 op2.o_tag = LDAP_REQ_SEARCH;
2889 op2.ors_scope = LDAP_SCOPE_BASE;
2890 op2.ors_deref = LDAP_DEREF_NEVER;
2891 op2.ors_slimit = 1;
2892 op2.ors_tlimit = SLAP_NO_LIMIT;
2893 op2.ors_limit = NULL;
2894 op2.ors_attrs = cm->qm->attr_sets[temp->attr_set_index].attrs;
2895 op2.ors_attrsonly = 0;
2896
2897 /* We want to invoke search at the same level of the stack
2898 * as we're already at...
2899 */
2900 bi.bi_cm = cm;
2901 bi.bi_templ = temp;
2902
2903 bi.bi_cb.sc_response = pc_bind_search;
2904 bi.bi_cb.sc_private = &bi;
2905 cb.sc_private = &bi;
2906 cb.sc_response = pc_bind_resp;
2907 op2.o_callback = &cb;
2908 overlay_op_walk( &op2, rs, op_search, on->on_info, on );
2909
2910 /* OK, just bind locally */
2911 if ( bi.bi_flags & BI_HASHED ) {
2912 int delete = 0;
2913 BackendDB *be = op->o_bd;
2914 op->o_bd = &cm->db;
2915
2916 Debug( pcache_debug, "pcache_op_bind: CACHED BIND for %s\n",
2917 op->o_req_dn.bv_val );
2918
2919 if ( op->o_bd->be_bind( op, rs ) == LDAP_SUCCESS ) {
2920 op->o_conn->c_authz_cookie = cm->db.be_private;
2921 }
2922 op->o_bd = be;
2923 ldap_pvt_thread_rdwr_wlock( &bi.bi_cq->rwlock );
2924 if ( !bi.bi_cq->bind_refcnt-- ) {
2925 delete = 1;
2926 }
2927 ldap_pvt_thread_rdwr_wunlock( &bi.bi_cq->rwlock );
2928 if ( delete ) free_query( bi.bi_cq );
2929 return rs->sr_err;
2930 }
2931
2932 /* We have a cached query to work with */
2933 if ( bi.bi_cq ) {
2934 sc = op->o_tmpalloc( sizeof(slap_callback) + sizeof(bindcacheinfo),
2935 op->o_tmpmemctx );
2936 sc->sc_response = pc_bind_save;
2937 sc->sc_cleanup = NULL;
2938 sc->sc_private = sc+1;
2939 sc->sc_writewait = NULL;
2940 bci = sc->sc_private;
2941 sc->sc_next = op->o_callback;
2942 op->o_callback = sc;
2943 bci->on = on;
2944 bci->qc = bi.bi_cq;
2945 }
2946 return SLAP_CB_CONTINUE;
2947 }
2948
2949 static slap_response refresh_merge;
2950
2951 static int
pcache_op_search(Operation * op,SlapReply * rs)2952 pcache_op_search(
2953 Operation *op,
2954 SlapReply *rs )
2955 {
2956 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2957 cache_manager *cm = on->on_bi.bi_private;
2958 query_manager* qm = cm->qm;
2959
2960 int i = -1;
2961
2962 Query query;
2963 QueryTemplate *qtemp = NULL;
2964 bindinfo *pbi = NULL;
2965
2966 int attr_set = -1;
2967 CachedQuery *answerable = NULL;
2968 int cacheable = 0;
2969
2970 struct berval tempstr;
2971
2972 #ifdef PCACHE_CONTROL_PRIVDB
2973 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
2974 return pcache_op_privdb( op, rs );
2975 }
2976 #endif /* PCACHE_CONTROL_PRIVDB */
2977
2978 /* The cache DB isn't open yet */
2979 if ( cm->defer_db_open ) {
2980 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
2981 "pcachePrivDB: cacheDB not available" );
2982 return rs->sr_err;
2983 }
2984
2985 /* pickup runtime ACL changes */
2986 cm->db.be_acl = op->o_bd->be_acl;
2987
2988 {
2989 /* See if we're processing a Bind request
2990 * or a cache refresh */
2991 slap_callback *cb = op->o_callback;
2992
2993 for ( ; cb; cb=cb->sc_next ) {
2994 if ( cb->sc_response == pc_bind_resp ) {
2995 pbi = cb->sc_private;
2996 break;
2997 }
2998 if ( cb->sc_response == refresh_merge ) {
2999 /* This is a refresh, do not search the cache */
3000 return SLAP_CB_CONTINUE;
3001 }
3002 }
3003 }
3004
3005 /* FIXME: cannot cache/answer requests with pagedResults control */
3006
3007 query.filter = op->ors_filter;
3008
3009 if ( pbi ) {
3010 query.base = pbi->bi_templ->bindbase;
3011 query.scope = pbi->bi_templ->bindscope;
3012 attr_set = pbi->bi_templ->attr_set_index;
3013 cacheable = 1;
3014 qtemp = pbi->bi_templ;
3015 if ( pbi->bi_flags & BI_LOOKUP )
3016 answerable = qm->qcfunc(op, qm, &query, qtemp);
3017
3018 } else {
3019 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1,
3020 op->o_tmpmemctx );
3021 tempstr.bv_len = 0;
3022 if ( filter2template( op, op->ors_filter, &tempstr ))
3023 {
3024 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3025 return SLAP_CB_CONTINUE;
3026 }
3027
3028 Debug( pcache_debug, "query template of incoming query = %s\n",
3029 tempstr.bv_val );
3030
3031 /* find attr set */
3032 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
3033
3034 query.base = op->o_req_ndn;
3035 query.scope = op->ors_scope;
3036
3037 /* check for query containment */
3038 if (attr_set > -1) {
3039 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
3040 for (; qt; qt = qt->qtnext ) {
3041 /* find if template i can potentially answer tempstr */
3042 if ( ber_bvstrcasecmp( &qt->querystr, &tempstr ) != 0 )
3043 continue;
3044 cacheable = 1;
3045 qtemp = qt;
3046 Debug( pcache_debug, "Entering QC, querystr = %s\n",
3047 op->ors_filterstr.bv_val );
3048 answerable = qm->qcfunc(op, qm, &query, qt);
3049
3050 /* if != NULL, rlocks qtemp->t_rwlock */
3051 if (answerable)
3052 break;
3053 }
3054 }
3055 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
3056 }
3057
3058 if (answerable) {
3059 BackendDB *save_bd = op->o_bd;
3060
3061 ldap_pvt_thread_mutex_lock( &answerable->answerable_cnt_mutex );
3062 answerable->answerable_cnt++;
3063 /* we only care about refcnts if we're refreshing */
3064 if ( answerable->refresh_time )
3065 answerable->refcnt++;
3066 Debug( pcache_debug, "QUERY ANSWERABLE (answered %lu times)\n",
3067 answerable->answerable_cnt );
3068 ldap_pvt_thread_mutex_unlock( &answerable->answerable_cnt_mutex );
3069
3070 ldap_pvt_thread_rdwr_wlock(&answerable->rwlock);
3071 if ( BER_BVISNULL( &answerable->q_uuid )) {
3072 /* No entries cached, just an empty result set */
3073 i = rs->sr_err = 0;
3074 send_ldap_result( op, rs );
3075 } else {
3076 /* Let Bind know we used a cached query */
3077 if ( pbi ) {
3078 answerable->bind_refcnt++;
3079 pbi->bi_cq = answerable;
3080 }
3081
3082 op->o_bd = &cm->db;
3083 if ( cm->response_cb == PCACHE_RESPONSE_CB_TAIL ) {
3084 slap_callback cb;
3085 /* The cached entry was already processed by any
3086 * other overlays, so don't let it get processed again.
3087 *
3088 * This loop removes over_back_response from the stack.
3089 */
3090 if ( overlay_callback_after_backover( op, &cb, 0) == 0 ) {
3091 slap_callback **scp;
3092 for ( scp = &op->o_callback; *scp != NULL;
3093 scp = &(*scp)->sc_next ) {
3094 if ( (*scp)->sc_next == &cb ) {
3095 *scp = cb.sc_next;
3096 break;
3097 }
3098 }
3099 }
3100 }
3101 i = cm->db.bd_info->bi_op_search( op, rs );
3102 }
3103 ldap_pvt_thread_rdwr_wunlock(&answerable->rwlock);
3104 /* locked by qtemp->qcfunc (query_containment) */
3105 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
3106 op->o_bd = save_bd;
3107 return i;
3108 }
3109
3110 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n" );
3111
3112 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3113 if (cm->num_cached_queries >= cm->max_queries) {
3114 cacheable = 0;
3115 }
3116 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3117
3118 if (op->ors_attrsonly)
3119 cacheable = 0;
3120
3121 if (cacheable) {
3122 slap_callback *cb;
3123 struct search_info *si;
3124
3125 Debug( pcache_debug, "QUERY CACHEABLE\n" );
3126 query.filter = filter_dup(op->ors_filter, NULL);
3127
3128 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
3129 cb->sc_response = pcache_response;
3130 cb->sc_cleanup = pcache_op_cleanup;
3131 cb->sc_private = (cb+1);
3132 cb->sc_writewait = 0;
3133 si = cb->sc_private;
3134 si->on = on;
3135 si->query = query;
3136 si->qtemp = qtemp;
3137 si->max = cm->num_entries_limit ;
3138 si->over = 0;
3139 si->count = 0;
3140 si->slimit = 0;
3141 si->slimit_exceeded = 0;
3142 si->caching_reason = PC_IGNORE;
3143 if ( op->ors_slimit > 0 && op->ors_slimit < cm->num_entries_limit ) {
3144 si->slimit = op->ors_slimit;
3145 op->ors_slimit = cm->num_entries_limit;
3146 }
3147 si->head = NULL;
3148 si->tail = NULL;
3149 si->swap_saved_attrs = 1;
3150 si->save_attrs = op->ors_attrs;
3151 si->pbi = pbi;
3152 if ( pbi )
3153 pbi->bi_si = si;
3154
3155 op->ors_attrs = qtemp->t_attrs.attrs;
3156
3157 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3158 cb->sc_next = op->o_callback;
3159 op->o_callback = cb;
3160
3161 } else {
3162 slap_callback **pcb;
3163
3164 /* need to move the callback at the end, in case other
3165 * overlays are present, so that the final entry is
3166 * actually cached */
3167 cb->sc_next = NULL;
3168 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
3169 *pcb = cb;
3170 }
3171
3172 } else {
3173 Debug( pcache_debug, "QUERY NOT CACHEABLE\n" );
3174 }
3175
3176 return SLAP_CB_CONTINUE;
3177 }
3178
3179 static int
get_attr_set(AttributeName * attrs,query_manager * qm,int num)3180 get_attr_set(
3181 AttributeName* attrs,
3182 query_manager* qm,
3183 int num )
3184 {
3185 int i = 0;
3186 int count = 0;
3187
3188 if ( attrs ) {
3189 for ( ; attrs[i].an_name.bv_val; i++ ) {
3190 /* only count valid attribute names
3191 * (searches ignore others, this overlay does the same) */
3192 if ( attrs[i].an_desc ) {
3193 count++;
3194 }
3195 }
3196 }
3197
3198 /* recognize default or explicit single "*" */
3199 if ( ! attrs ||
3200 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_all_user_attrs ) ) )
3201 {
3202 count = 1;
3203 attrs = slap_anlist_all_user_attributes;
3204
3205 /* recognize implicit (no valid attributes) or explicit single "1.1" */
3206 } else if ( count == 0 ||
3207 ( i == 1 && bvmatch( &attrs[0].an_name, slap_bv_no_attrs ) ) )
3208 {
3209 count = 0;
3210 attrs = NULL;
3211 }
3212
3213 for ( i = 0; i < num; i++ ) {
3214 AttributeName *a2;
3215 int found = 1;
3216
3217 if ( count > qm->attr_sets[i].count ) {
3218 if ( qm->attr_sets[i].count &&
3219 bvmatch( &qm->attr_sets[i].attrs[0].an_name, slap_bv_all_user_attrs )) {
3220 break;
3221 }
3222 continue;
3223 }
3224
3225 if ( !count ) {
3226 if ( !qm->attr_sets[i].count ) {
3227 break;
3228 }
3229 continue;
3230 }
3231
3232 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
3233 if ( !a2->an_desc && !bvmatch( &a2->an_name, slap_bv_all_user_attrs ) ) continue;
3234
3235 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
3236 found = 0;
3237 break;
3238 }
3239 }
3240
3241 if ( found ) {
3242 break;
3243 }
3244 }
3245
3246 if ( i == num ) {
3247 i = -1;
3248 }
3249
3250 return i;
3251 }
3252
3253 /* Refresh a cached query:
3254 * 1: Replay the query on the remote DB and merge each entry into
3255 * the local DB. Remember the DNs of each remote entry.
3256 * 2: Search the local DB for all entries matching this queryID.
3257 * Delete any entry whose DN is not in the list from (1).
3258 */
3259 typedef struct dnlist {
3260 struct dnlist *next;
3261 struct berval dn;
3262 char delete;
3263 } dnlist;
3264
3265 typedef struct refresh_info {
3266 dnlist *ri_dns;
3267 dnlist *ri_tail;
3268 dnlist *ri_dels;
3269 BackendDB *ri_be;
3270 CachedQuery *ri_q;
3271 } refresh_info;
3272
dnl_alloc(Operation * op,struct berval * bvdn)3273 static dnlist *dnl_alloc( Operation *op, struct berval *bvdn )
3274 {
3275 dnlist *dn = op->o_tmpalloc( sizeof(dnlist) + bvdn->bv_len + 1,
3276 op->o_tmpmemctx );
3277 dn->dn.bv_len = bvdn->bv_len;
3278 dn->dn.bv_val = (char *)(dn+1);
3279 AC_MEMCPY( dn->dn.bv_val, bvdn->bv_val, dn->dn.bv_len );
3280 dn->dn.bv_val[dn->dn.bv_len] = '\0';
3281 return dn;
3282 }
3283
3284 static int
refresh_merge(Operation * op,SlapReply * rs)3285 refresh_merge( Operation *op, SlapReply *rs )
3286 {
3287 if ( rs->sr_type == REP_SEARCH ) {
3288 refresh_info *ri = op->o_callback->sc_private;
3289 Entry *e;
3290 dnlist *dnl;
3291 slap_callback *ocb;
3292 int rc;
3293
3294 ocb = op->o_callback;
3295 /* Find local entry, merge */
3296 op->o_bd = ri->ri_be;
3297 rc = be_entry_get_rw( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &e );
3298 if ( rc != LDAP_SUCCESS || e == NULL ) {
3299 /* No local entry, just add it. FIXME: we are not checking
3300 * the cache entry limit here
3301 */
3302 merge_entry( op, rs->sr_entry, 1, &ri->ri_q->q_uuid );
3303 } else {
3304 /* Entry exists, update it */
3305 Entry ne;
3306 Attribute *a, **b;
3307 Modifications *modlist, *mods = NULL;
3308 const char* text = NULL;
3309 char textbuf[SLAP_TEXT_BUFLEN];
3310 size_t textlen = sizeof(textbuf);
3311 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
3312
3313 ne = *e;
3314 b = &ne.e_attrs;
3315 /* Get a copy of only the attrs we requested */
3316 for ( a=e->e_attrs; a; a=a->a_next ) {
3317 if ( ad_inlist( a->a_desc, rs->sr_attrs )) {
3318 *b = attr_alloc( a->a_desc );
3319 *(*b) = *a;
3320 /* The actual values still belong to e */
3321 (*b)->a_flags |= SLAP_ATTR_DONT_FREE_VALS |
3322 SLAP_ATTR_DONT_FREE_DATA;
3323 b = &((*b)->a_next);
3324 }
3325 }
3326 *b = NULL;
3327 slap_entry2mods( rs->sr_entry, &modlist, &text, textbuf, textlen );
3328 syncrepl_diff_entry( op, ne.e_attrs, rs->sr_entry->e_attrs,
3329 &mods, &modlist, 0 );
3330 be_entry_release_r( op, e );
3331 attrs_free( ne.e_attrs );
3332 slap_mods_free( modlist, 1 );
3333 /* mods is NULL if there are no changes */
3334 if ( mods ) {
3335 SlapReply rs2 = { REP_RESULT };
3336 struct berval dn = op->o_req_dn;
3337 struct berval ndn = op->o_req_ndn;
3338 op->o_tag = LDAP_REQ_MODIFY;
3339 op->orm_modlist = mods;
3340 op->o_req_dn = rs->sr_entry->e_name;
3341 op->o_req_ndn = rs->sr_entry->e_nname;
3342 op->o_callback = &cb;
3343 op->o_bd->be_modify( op, &rs2 );
3344 rs->sr_err = rs2.sr_err;
3345 rs_assert_done( &rs2 );
3346 slap_mods_free( mods, 1 );
3347 op->o_req_dn = dn;
3348 op->o_req_ndn = ndn;
3349 }
3350 }
3351
3352 /* Add DN to list */
3353 dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3354 dnl->next = NULL;
3355 if ( ri->ri_tail ) {
3356 ri->ri_tail->next = dnl;
3357 } else {
3358 ri->ri_dns = dnl;
3359 }
3360 ri->ri_tail = dnl;
3361 op->o_callback = ocb;
3362 }
3363 return 0;
3364 }
3365
3366 static int
refresh_purge(Operation * op,SlapReply * rs)3367 refresh_purge( Operation *op, SlapReply *rs )
3368 {
3369 if ( rs->sr_type == REP_SEARCH ) {
3370 refresh_info *ri = op->o_callback->sc_private;
3371 dnlist **dn;
3372 int del = 1;
3373
3374 /* Did the entry exist on the remote? */
3375 for ( dn=&ri->ri_dns; *dn; dn = &(*dn)->next ) {
3376 if ( dn_match( &(*dn)->dn, &rs->sr_entry->e_nname )) {
3377 dnlist *dnext = (*dn)->next;
3378 op->o_tmpfree( *dn, op->o_tmpmemctx );
3379 *dn = dnext;
3380 del = 0;
3381 break;
3382 }
3383 }
3384 /* No, so put it on the list to delete */
3385 if ( del ) {
3386 Attribute *a;
3387 dnlist *dnl = dnl_alloc( op, &rs->sr_entry->e_nname );
3388 dnl->next = ri->ri_dels;
3389 ri->ri_dels = dnl;
3390 a = attr_find( rs->sr_entry->e_attrs, ad_queryId );
3391 /* If ours is the only queryId, delete entry */
3392 dnl->delete = ( a->a_numvals == 1 );
3393 }
3394 }
3395 return 0;
3396 }
3397
3398 static int
refresh_query(Operation * op,CachedQuery * query,slap_overinst * on)3399 refresh_query( Operation *op, CachedQuery *query, slap_overinst *on )
3400 {
3401 SlapReply rs = {REP_RESULT};
3402 slap_callback cb = { 0 };
3403 refresh_info ri = { 0 };
3404 char filter_str[ LDAP_LUTIL_UUIDSTR_BUFSIZE + STRLENOF( "(pcacheQueryID=)" ) ];
3405 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
3406 Filter filter = {LDAP_FILTER_EQUALITY};
3407 AttributeName attrs[ 2 ] = {{{ 0 }}};
3408 dnlist *dn;
3409 int rc;
3410
3411 ldap_pvt_thread_mutex_lock( &query->answerable_cnt_mutex );
3412 query->refcnt = 0;
3413 ldap_pvt_thread_mutex_unlock( &query->answerable_cnt_mutex );
3414
3415 cb.sc_response = refresh_merge;
3416 cb.sc_private = &ri;
3417
3418 /* cache DB */
3419 ri.ri_be = op->o_bd;
3420 ri.ri_q = query;
3421
3422 op->o_tag = LDAP_REQ_SEARCH;
3423 op->o_protocol = LDAP_VERSION3;
3424 op->o_callback = &cb;
3425 op->o_do_not_cache = 1;
3426
3427 op->o_req_dn = query->qbase->base;
3428 op->o_req_ndn = query->qbase->base;
3429 op->ors_scope = query->scope;
3430 op->ors_deref = LDAP_DEREF_NEVER;
3431 op->ors_slimit = SLAP_NO_LIMIT;
3432 op->ors_tlimit = SLAP_NO_LIMIT;
3433 op->ors_limit = NULL;
3434 op->ors_filter = query->filter;
3435 filter2bv_x( op, query->filter, &op->ors_filterstr );
3436 op->ors_attrs = query->qtemp->t_attrs.attrs;
3437 op->ors_attrsonly = 0;
3438
3439 op->o_bd = on->on_info->oi_origdb;
3440 rc = op->o_bd->be_search( op, &rs );
3441 if ( rc ) {
3442 op->o_bd = ri.ri_be;
3443 goto leave;
3444 }
3445
3446 /* Get the DNs of all entries matching this query */
3447 cb.sc_response = refresh_purge;
3448
3449 op->o_bd = ri.ri_be;
3450 op->o_req_dn = op->o_bd->be_suffix[0];
3451 op->o_req_ndn = op->o_bd->be_nsuffix[0];
3452 op->ors_scope = LDAP_SCOPE_SUBTREE;
3453 op->ors_deref = LDAP_DEREF_NEVER;
3454 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
3455 "(%s=%s)", ad_queryId->ad_cname.bv_val, query->q_uuid.bv_val);
3456 filter.f_ava = &ava;
3457 filter.f_av_desc = ad_queryId;
3458 filter.f_av_value = query->q_uuid;
3459 attrs[ 0 ].an_desc = ad_queryId;
3460 attrs[ 0 ].an_name = ad_queryId->ad_cname;
3461 op->ors_attrs = attrs;
3462 op->ors_attrsonly = 0;
3463 rs_reinit( &rs, REP_RESULT );
3464 rc = op->o_bd->be_search( op, &rs );
3465 if ( rc ) goto leave;
3466
3467 while (( dn = ri.ri_dels )) {
3468 op->o_req_dn = dn->dn;
3469 op->o_req_ndn = dn->dn;
3470 rs_reinit( &rs, REP_RESULT );
3471 if ( dn->delete ) {
3472 op->o_tag = LDAP_REQ_DELETE;
3473 op->o_bd->be_delete( op, &rs );
3474 } else {
3475 Modifications mod;
3476 struct berval vals[2];
3477
3478 vals[0] = query->q_uuid;
3479 BER_BVZERO( &vals[1] );
3480 mod.sml_op = LDAP_MOD_DELETE;
3481 mod.sml_flags = 0;
3482 mod.sml_desc = ad_queryId;
3483 mod.sml_type = ad_queryId->ad_cname;
3484 mod.sml_values = vals;
3485 mod.sml_nvalues = NULL;
3486 mod.sml_numvals = 1;
3487 mod.sml_next = NULL;
3488
3489 op->o_tag = LDAP_REQ_MODIFY;
3490 op->orm_modlist = &mod;
3491 op->o_bd->be_modify( op, &rs );
3492 }
3493 ri.ri_dels = dn->next;
3494 op->o_tmpfree( dn, op->o_tmpmemctx );
3495 }
3496
3497 leave:
3498 /* reset our local heap, we're done with it */
3499 slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, op->o_threadctx, 1 );
3500 return rc;
3501 }
3502
3503 static void*
consistency_check(void * ctx,void * arg)3504 consistency_check(
3505 void *ctx,
3506 void *arg )
3507 {
3508 struct re_s *rtask = arg;
3509 slap_overinst *on = rtask->arg;
3510 cache_manager *cm = on->on_bi.bi_private;
3511 query_manager *qm = cm->qm;
3512 Connection conn = {0};
3513 OperationBuffer opbuf;
3514 Operation *op;
3515
3516 CachedQuery *query, *qprev;
3517 CachedQuery *expires = NULL;
3518 int return_val, pause = PCACHE_CC_PAUSED;
3519 QueryTemplate *templ;
3520
3521 /* Don't expire anything when we're offline */
3522 if ( cm->cc_paused & PCACHE_CC_OFFLINE ) {
3523 pause = PCACHE_CC_OFFLINE;
3524 goto leave;
3525 }
3526
3527 connection_fake_init( &conn, &opbuf, ctx );
3528 op = &opbuf.ob_op;
3529
3530 op->o_bd = &cm->db;
3531 op->o_dn = cm->db.be_rootdn;
3532 op->o_ndn = cm->db.be_rootndn;
3533
3534 cm->cc_arg = arg;
3535
3536 for (templ = qm->templates; templ; templ=templ->qmnext) {
3537 time_t ttl;
3538 if ( !templ->query_last ) continue;
3539 pause = 0;
3540 op->o_time = slap_get_time();
3541 if ( !templ->ttr ) {
3542 ttl = templ->ttl;
3543 if ( templ->negttl && templ->negttl < ttl )
3544 ttl = templ->negttl;
3545 if ( templ->limitttl && templ->limitttl < ttl )
3546 ttl = templ->limitttl;
3547 /* The oldest timestamp that needs expiration checking */
3548 ttl += op->o_time;
3549 }
3550
3551 Debug( pcache_debug, "Lock CR index = %p\n",
3552 (void *) templ );
3553 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
3554 for ( query=templ->query_last; query; query=qprev ) {
3555 qprev = query->prev;
3556 if ( query->refresh_time && query->refresh_time < op->o_time ) {
3557 /* A refresh will extend the expiry if the query has been
3558 * referenced, but not if it's unreferenced. If the
3559 * expiration has been hit, then skip the refresh since
3560 * we're just going to discard the result anyway.
3561 */
3562 if ( query->refcnt )
3563 query->expiry_time = op->o_time + templ->ttl;
3564 if ( query->expiry_time > op->o_time ) {
3565 /* perform actual refresh below */
3566 continue;
3567 }
3568 }
3569
3570 if (query->expiry_time < op->o_time) {
3571 int rem = 0;
3572 if ( query != templ->query_last )
3573 continue;
3574 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
3575 if (query->in_lru) {
3576 remove_query(qm, query);
3577 rem = 1;
3578 }
3579 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
3580 if (!rem)
3581 continue;
3582 remove_from_template(query, templ);
3583 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
3584 (void *) templ, templ->no_of_queries );
3585 query->prev = expires;
3586 expires = query;
3587 query->qtemp = NULL;
3588 } else if ( !templ->ttr && query->expiry_time > ttl ) {
3589 /* We don't need to check for refreshes, and this
3590 * query's expiry is too new, and all subsequent queries
3591 * will be newer yet. So stop looking.
3592 *
3593 * If we have refreshes, then we always have to walk the
3594 * entire query list.
3595 */
3596 break;
3597 }
3598 }
3599 Debug( pcache_debug, "Unlock CR index = %p\n",
3600 (void *) templ );
3601 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
3602 for ( query=expires; query; query=qprev ) {
3603 int rem;
3604 qprev = query->prev;
3605 if ( BER_BVISNULL( &query->q_uuid ))
3606 return_val = 0;
3607 else
3608 return_val = remove_query_data(op, &query->q_uuid);
3609 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
3610 return_val );
3611 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
3612 cm->cur_entries -= return_val;
3613 cm->num_cached_queries--;
3614 Debug( pcache_debug, "STORED QUERIES = %lu\n",
3615 cm->num_cached_queries );
3616 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
3617 Debug( pcache_debug,
3618 "STALE QUERY REMOVED, CACHE ="
3619 "%d entries\n",
3620 cm->cur_entries );
3621 ldap_pvt_thread_rdwr_wlock( &query->rwlock );
3622 if ( query->bind_refcnt-- ) {
3623 rem = 0;
3624 } else {
3625 rem = 1;
3626 }
3627 ldap_pvt_thread_rdwr_wunlock( &query->rwlock );
3628 if ( rem ) free_query(query);
3629 }
3630
3631 /* handle refreshes that we skipped earlier */
3632 if ( templ->ttr ) {
3633 ldap_pvt_thread_rdwr_rlock(&templ->t_rwlock);
3634 for ( query=templ->query_last; query; query=qprev ) {
3635 qprev = query->prev;
3636 if ( query->refresh_time && query->refresh_time < op->o_time ) {
3637 /* A refresh will extend the expiry if the query has been
3638 * referenced, but not if it's unreferenced. If the
3639 * expiration has been hit, then skip the refresh since
3640 * we're just going to discard the result anyway.
3641 */
3642 if ( query->expiry_time > op->o_time ) {
3643 refresh_query( op, query, on );
3644 query->refresh_time = op->o_time + templ->ttr;
3645 }
3646 }
3647 }
3648 ldap_pvt_thread_rdwr_runlock(&templ->t_rwlock);
3649 }
3650 }
3651
3652 leave:
3653 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3654 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
3655 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
3656 }
3657 /* If there were no queries, defer processing for a while */
3658 if ( cm->cc_paused != pause )
3659 cm->cc_paused = pause;
3660 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
3661
3662 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3663 return NULL;
3664 }
3665
3666
3667 #define MAX_ATTR_SETS 500
3668
3669 enum {
3670 PC_MAIN = 1,
3671 PC_ATTR,
3672 PC_TEMP,
3673 PC_RESP,
3674 PC_QUERIES,
3675 PC_OFFLINE,
3676 PC_BIND,
3677 PC_PRIVATE_DB
3678 };
3679
3680 static ConfigDriver pc_cf_gen;
3681 static ConfigLDAPadd pc_ldadd;
3682 static ConfigCfAdd pc_cfadd;
3683
3684 static ConfigTable pccfg[] = {
3685 { "pcache", "backend> <max_entries> <numattrsets> <entry limit> "
3686 "<cycle_time",
3687 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3688 "( OLcfgOvAt:2.1 NAME ( 'olcPcache' 'olcProxyCache' ) "
3689 "DESC 'Proxy Cache basic parameters' "
3690 "EQUALITY caseIgnoreMatch "
3691 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3692 { "pcacheAttrset", "index> <attributes...",
3693 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3694 "( OLcfgOvAt:2.2 NAME ( 'olcPcacheAttrset' 'olcProxyAttrset' ) "
3695 "DESC 'A set of attributes to cache' "
3696 "EQUALITY caseIgnoreMatch "
3697 "SYNTAX OMsDirectoryString )", NULL, NULL },
3698 { "pcacheTemplate", "filter> <attrset-index> <TTL> <negTTL> "
3699 "<limitTTL> <TTR",
3700 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3701 "( OLcfgOvAt:2.3 NAME ( 'olcPcacheTemplate' 'olcProxyCacheTemplate' ) "
3702 "DESC 'Filter template, attrset, cache TTL, "
3703 "optional negative TTL, optional sizelimit TTL, "
3704 "optional TTR' "
3705 "EQUALITY caseIgnoreMatch "
3706 "SYNTAX OMsDirectoryString )", NULL, NULL },
3707 { "pcachePosition", "head|tail(default)",
3708 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3709 "( OLcfgOvAt:2.4 NAME 'olcPcachePosition' "
3710 "DESC 'Response callback position in overlay stack' "
3711 "EQUALITY caseIgnoreMatch "
3712 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3713 { "pcacheMaxQueries", "queries",
3714 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3715 "( OLcfgOvAt:2.5 NAME ( 'olcPcacheMaxQueries' 'olcProxyCacheQueries' ) "
3716 "DESC 'Maximum number of queries to cache' "
3717 "EQUALITY integerMatch "
3718 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
3719 { "pcachePersist", "TRUE|FALSE",
3720 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3721 "( OLcfgOvAt:2.6 NAME ( 'olcPcachePersist' 'olcProxySaveQueries' ) "
3722 "DESC 'Save cached queries for hot restart' "
3723 "EQUALITY booleanMatch "
3724 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3725 { "pcacheValidate", "TRUE|FALSE",
3726 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3727 "( OLcfgOvAt:2.7 NAME ( 'olcPcacheValidate' 'olcProxyCheckCacheability' ) "
3728 "DESC 'Check whether the results of a query are cacheable, e.g. for schema issues' "
3729 "EQUALITY booleanMatch "
3730 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3731 { "pcacheOffline", "TRUE|FALSE",
3732 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|PC_OFFLINE, pc_cf_gen,
3733 "( OLcfgOvAt:2.8 NAME 'olcPcacheOffline' "
3734 "DESC 'Set cache to offline mode and disable expiration' "
3735 "EQUALITY booleanMatch "
3736 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3737 { "pcacheBind", "filter> <attrset-index> <TTR> <scope> <base",
3738 6, 6, 0, ARG_MAGIC|PC_BIND, pc_cf_gen,
3739 "( OLcfgOvAt:2.9 NAME 'olcPcacheBind' "
3740 "DESC 'Parameters for caching Binds' "
3741 "EQUALITY caseIgnoreMatch "
3742 "SYNTAX OMsDirectoryString )", NULL, NULL },
3743 { "pcache-", "private database args",
3744 1, 0, STRLENOF("pcache-"), ARG_MAGIC|PC_PRIVATE_DB, pc_cf_gen,
3745 NULL, NULL, NULL },
3746
3747 /* Legacy keywords */
3748 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
3749 "<cycle_time",
3750 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
3751 NULL, NULL, NULL },
3752 { "proxyattrset", "index> <attributes...",
3753 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
3754 NULL, NULL, NULL },
3755 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
3756 4, 7, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
3757 NULL, NULL, NULL },
3758 { "response-callback", "head|tail(default)",
3759 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
3760 NULL, NULL, NULL },
3761 { "proxyCacheQueries", "queries",
3762 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
3763 NULL, NULL, NULL },
3764 { "proxySaveQueries", "TRUE|FALSE",
3765 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
3766 NULL, NULL, NULL },
3767 { "proxyCheckCacheability", "TRUE|FALSE",
3768 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, check_cacheability),
3769 NULL, NULL, NULL },
3770
3771 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3772 };
3773
3774 static ConfigOCs pcocs[] = {
3775 { "( OLcfgOvOc:2.1 "
3776 "NAME 'olcPcacheConfig' "
3777 "DESC 'ProxyCache configuration' "
3778 "SUP olcOverlayConfig "
3779 "MUST ( olcPcache $ olcPcacheAttrset $ olcPcacheTemplate ) "
3780 "MAY ( olcPcachePosition $ olcPcacheMaxQueries $ olcPcachePersist $ "
3781 "olcPcacheValidate $ olcPcacheOffline $ olcPcacheBind ) )",
3782 Cft_Overlay, pccfg, NULL, pc_cfadd },
3783 { "( OLcfgOvOc:2.2 "
3784 "NAME 'olcPcacheDatabase' "
3785 "DESC 'Cache database configuration' "
3786 /* co_table is initialized in pcache_initialize */
3787 "AUXILIARY )", Cft_Misc, NULL, pc_ldadd },
3788 { NULL, 0, NULL }
3789 };
3790
3791 static int pcache_db_open2( slap_overinst *on, ConfigReply *cr );
3792
3793 static int
pc_ldadd_cleanup(ConfigArgs * c)3794 pc_ldadd_cleanup( ConfigArgs *c )
3795 {
3796 slap_overinst *on = c->ca_private;
3797 return pcache_db_open2( on, &c->reply );
3798 }
3799
3800 static int
pc_ldadd(CfEntryInfo * p,Entry * e,ConfigArgs * ca)3801 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3802 {
3803 slap_overinst *on;
3804 cache_manager *cm;
3805
3806 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
3807 p->ce_bi->bi_cf_ocs != pcocs )
3808 return LDAP_CONSTRAINT_VIOLATION;
3809
3810 on = (slap_overinst *)p->ce_bi;
3811 cm = on->on_bi.bi_private;
3812 ca->be = &cm->db;
3813 /* Defer open if this is an LDAPadd */
3814 if ( CONFIG_ONLINE_ADD( ca ))
3815 config_push_cleanup( ca, pc_ldadd_cleanup );
3816 else
3817 cm->defer_db_open = 0;
3818 ca->ca_private = on;
3819 return LDAP_SUCCESS;
3820 }
3821
3822 static int
pc_cfadd(Operation * op,SlapReply * rs,Entry * p,ConfigArgs * ca)3823 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
3824 {
3825 CfEntryInfo *pe = p->e_private;
3826 slap_overinst *on = (slap_overinst *)pe->ce_bi;
3827 cache_manager *cm = on->on_bi.bi_private;
3828 struct berval bv;
3829
3830 /* FIXME: should not hardcode "olcDatabase" here */
3831 bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
3832 "olcDatabase=" SLAP_X_ORDERED_FMT "%s",
3833 0, cm->db.bd_info->bi_type );
3834 if ( bv.bv_len >= sizeof( ca->cr_msg ) ) {
3835 return -1;
3836 }
3837 bv.bv_val = ca->cr_msg;
3838 ca->be = &cm->db;
3839 cm->defer_db_open = 0;
3840
3841 /* We can only create this entry if the database is table-driven
3842 */
3843 if ( cm->db.bd_info->bi_cf_ocs )
3844 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
3845 &pcocs[1] );
3846
3847 return 0;
3848 }
3849
3850 static int
pc_cf_gen(ConfigArgs * c)3851 pc_cf_gen( ConfigArgs *c )
3852 {
3853 slap_overinst *on = (slap_overinst *)c->bi;
3854 cache_manager* cm = on->on_bi.bi_private;
3855 query_manager* qm = cm->qm;
3856 QueryTemplate* temp;
3857 AttributeName* attr_name;
3858 AttributeName* attrarray;
3859 const char* text=NULL;
3860 int i, num, rc = 0;
3861 char *ptr;
3862 unsigned long t;
3863
3864 if ( c->op == SLAP_CONFIG_EMIT ) {
3865 struct berval bv;
3866 switch( c->type ) {
3867 case PC_MAIN:
3868 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
3869 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
3870 cm->num_entries_limit, cm->cc_period );
3871 bv.bv_val = c->cr_msg;
3872 value_add_one( &c->rvalue_vals, &bv );
3873 break;
3874 case PC_ATTR:
3875 for (i=0; i<cm->numattrsets; i++) {
3876 if ( !qm->attr_sets[i].count ) continue;
3877
3878 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
3879
3880 /* count the attr length */
3881 for ( attr_name = qm->attr_sets[i].attrs;
3882 attr_name->an_name.bv_val; attr_name++ )
3883 {
3884 bv.bv_len += attr_name->an_name.bv_len + 1;
3885 if ( attr_name->an_desc &&
3886 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3887 bv.bv_len += STRLENOF("undef:");
3888 }
3889 }
3890
3891 bv.bv_val = ch_malloc( bv.bv_len+1 );
3892 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
3893 for ( attr_name = qm->attr_sets[i].attrs;
3894 attr_name->an_name.bv_val; attr_name++ ) {
3895 *ptr++ = ' ';
3896 if ( attr_name->an_desc &&
3897 ( attr_name->an_desc->ad_flags & SLAP_DESC_TEMPORARY ) ) {
3898 ptr = lutil_strcopy( ptr, "undef:" );
3899 }
3900 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
3901 }
3902 ber_bvarray_add( &c->rvalue_vals, &bv );
3903 }
3904 if ( !c->rvalue_vals )
3905 rc = 1;
3906 break;
3907 case PC_TEMP:
3908 for (temp=qm->templates; temp; temp=temp->qmnext) {
3909 /* HEADS-UP: always print all;
3910 * if optional == 0, ignore */
3911 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3912 " %d %ld %ld %ld %ld",
3913 temp->attr_set_index,
3914 temp->ttl,
3915 temp->negttl,
3916 temp->limitttl,
3917 temp->ttr );
3918 bv.bv_len += temp->querystr.bv_len + 2;
3919 bv.bv_val = ch_malloc( bv.bv_len+1 );
3920 ptr = bv.bv_val;
3921 *ptr++ = '"';
3922 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
3923 *ptr++ = '"';
3924 strcpy( ptr, c->cr_msg );
3925 ber_bvarray_add( &c->rvalue_vals, &bv );
3926 }
3927 if ( !c->rvalue_vals )
3928 rc = 1;
3929 break;
3930 case PC_BIND:
3931 for (temp=qm->templates; temp; temp=temp->qmnext) {
3932 if ( !temp->bindttr ) continue;
3933 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3934 " %d %ld %s ",
3935 temp->attr_set_index,
3936 temp->bindttr,
3937 ldap_pvt_scope2str( temp->bindscope ));
3938 bv.bv_len += temp->bindbase.bv_len + temp->bindftemp.bv_len + 4;
3939 bv.bv_val = ch_malloc( bv.bv_len + 1 );
3940 ptr = bv.bv_val;
3941 *ptr++ = '"';
3942 ptr = lutil_strcopy( ptr, temp->bindftemp.bv_val );
3943 *ptr++ = '"';
3944 ptr = lutil_strcopy( ptr, c->cr_msg );
3945 *ptr++ = '"';
3946 ptr = lutil_strcopy( ptr, temp->bindbase.bv_val );
3947 *ptr++ = '"';
3948 *ptr = '\0';
3949 ber_bvarray_add( &c->rvalue_vals, &bv );
3950 }
3951 if ( !c->rvalue_vals )
3952 rc = 1;
3953 break;
3954 case PC_RESP:
3955 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
3956 BER_BVSTR( &bv, "head" );
3957 } else {
3958 BER_BVSTR( &bv, "tail" );
3959 }
3960 value_add_one( &c->rvalue_vals, &bv );
3961 break;
3962 case PC_QUERIES:
3963 c->value_int = cm->max_queries;
3964 break;
3965 case PC_OFFLINE:
3966 c->value_int = (cm->cc_paused & PCACHE_CC_OFFLINE) != 0;
3967 break;
3968 }
3969 return rc;
3970 } else if ( c->op == LDAP_MOD_DELETE ) {
3971 rc = 1;
3972 switch( c->type ) {
3973 case PC_ATTR: /* FIXME */
3974 case PC_TEMP:
3975 case PC_BIND:
3976 break;
3977 case PC_OFFLINE:
3978 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
3979 /* If there were cached queries when we went offline,
3980 * restart the checker now.
3981 */
3982 if ( cm->num_cached_queries ) {
3983 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3984 cm->cc_paused = 0;
3985 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
3986 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3987 }
3988 rc = 0;
3989 break;
3990 }
3991 return rc;
3992 }
3993
3994 switch( c->type ) {
3995 case PC_MAIN:
3996 if ( cm->numattrsets > 0 ) {
3997 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive already provided" );
3998 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
3999 return( 1 );
4000 }
4001
4002 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
4003 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
4004 c->argv[3] );
4005 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4006 return( 1 );
4007 }
4008 if ( cm->numattrsets <= 0 ) {
4009 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
4010 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4011 return( 1 );
4012 }
4013 if ( cm->numattrsets > MAX_ATTR_SETS ) {
4014 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
4015 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4016 return( 1 );
4017 }
4018
4019 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
4020 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
4021 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4022 return( 1 );
4023 }
4024
4025 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
4026 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
4027 c->argv[2] );
4028 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4029 return( 1 );
4030 }
4031 if ( cm->max_entries <= 0 ) {
4032 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
4033 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg );
4034 return( 1 );
4035 }
4036
4037 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
4038 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
4039 c->argv[4] );
4040 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4041 return( 1 );
4042 }
4043 if ( cm->num_entries_limit <= 0 ) {
4044 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
4045 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4046 return( 1 );
4047 }
4048 if ( cm->num_entries_limit > cm->max_entries ) {
4049 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
4050 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4051 return( 1 );
4052 }
4053
4054 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4055 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
4056 c->argv[5] );
4057 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4058 return( 1 );
4059 }
4060
4061 cm->cc_period = (time_t)t;
4062 Debug( pcache_debug,
4063 "Total # of attribute sets to be cached = %d.\n",
4064 cm->numattrsets );
4065 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
4066 sizeof( struct attr_set ) );
4067 break;
4068 case PC_ATTR:
4069 if ( cm->numattrsets == 0 ) {
4070 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4071 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4072 return( 1 );
4073 }
4074 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
4075 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
4076 c->argv[1] );
4077 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4078 return( 1 );
4079 }
4080
4081 if ( num < 0 || num >= cm->numattrsets ) {
4082 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
4083 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4084 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4085 return 1;
4086 }
4087 qm->attr_sets[num].flags |= PC_CONFIGURED;
4088 if ( c->argc == 2 ) {
4089 /* assume "1.1" */
4090 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4091 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
4092 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4093 return 1;
4094
4095 } else if ( c->argc == 3 ) {
4096 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4097 qm->attr_sets[num].count = 1;
4098 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4099 sizeof( AttributeName ) );
4100 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4101 break;
4102
4103 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4104 qm->attr_sets[num].count = 1;
4105 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
4106 sizeof( AttributeName ) );
4107 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4108 break;
4109
4110 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
4111 break;
4112 }
4113 /* else: fallthru */
4114
4115 } else if ( c->argc == 4 ) {
4116 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
4117 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
4118 {
4119 qm->attr_sets[num].count = 2;
4120 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
4121 sizeof( AttributeName ) );
4122 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
4123 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4124 break;
4125 }
4126 /* else: fallthru */
4127 }
4128
4129 if ( c->argc > 2 ) {
4130 int all_user = 0, all_op = 0;
4131
4132 qm->attr_sets[num].count = c->argc - 2;
4133 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
4134 sizeof( AttributeName ) );
4135 attr_name = qm->attr_sets[num].attrs;
4136 for ( i = 2; i < c->argc; i++ ) {
4137 attr_name->an_desc = NULL;
4138 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
4139 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4140 "invalid attr #%d \"%s\" in attrlist",
4141 i - 2, c->argv[i] );
4142 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4143 ch_free( qm->attr_sets[num].attrs );
4144 qm->attr_sets[num].attrs = NULL;
4145 qm->attr_sets[num].count = 0;
4146 return 1;
4147 }
4148 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
4149 all_user = 1;
4150 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
4151 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
4152 all_op = 1;
4153 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
4154 } else {
4155 if ( strncasecmp( c->argv[i], "undef:", STRLENOF("undef:") ) == 0 ) {
4156 struct berval bv;
4157 ber_str2bv( c->argv[i] + STRLENOF("undef:"), 0, 0, &bv );
4158 attr_name->an_desc = slap_bv2tmp_ad( &bv, NULL );
4159
4160 } else if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
4161 strcpy( c->cr_msg, text );
4162 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4163 ch_free( qm->attr_sets[num].attrs );
4164 qm->attr_sets[num].attrs = NULL;
4165 qm->attr_sets[num].count = 0;
4166 return 1;
4167 }
4168 attr_name->an_name = attr_name->an_desc->ad_cname;
4169 }
4170 attr_name->an_oc = NULL;
4171 attr_name->an_flags = 0;
4172 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
4173 qm->attr_sets[num].flags |= PC_GOT_OC;
4174 attr_name++;
4175 BER_BVZERO( &attr_name->an_name );
4176 }
4177
4178 /* warn if list contains both "*" and "+" */
4179 if ( i > 4 && all_user && all_op ) {
4180 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4181 "warning: attribute list contains \"*\" and \"+\"" );
4182 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4183 }
4184 }
4185 break;
4186 case PC_TEMP:
4187 if ( cm->numattrsets == 0 ) {
4188 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcache\" directive not provided yet" );
4189 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4190 return( 1 );
4191 }
4192 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4193 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
4194 c->argv[2] );
4195 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4196 return( 1 );
4197 }
4198
4199 if ( i < 0 || i >= cm->numattrsets ||
4200 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4201 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
4202 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4203 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4204 return 1;
4205 }
4206 {
4207 AttributeName *attrs;
4208 int cnt;
4209 cnt = template_attrs( c->argv[1], &qm->attr_sets[i], &attrs, &text );
4210 if ( cnt < 0 ) {
4211 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4212 text );
4213 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4214 return 1;
4215 }
4216 temp = ch_calloc( 1, sizeof( QueryTemplate ));
4217 temp->qmnext = qm->templates;
4218 qm->templates = temp;
4219 temp->t_attrs.attrs = attrs;
4220 temp->t_attrs.count = cnt;
4221 }
4222 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
4223 temp->query = temp->query_last = NULL;
4224 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4225 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4226 "unable to parse template ttl=\"%s\"",
4227 c->argv[3] );
4228 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4229 pc_temp_fail:
4230 ch_free( temp->t_attrs.attrs );
4231 ch_free( temp );
4232 return( 1 );
4233 }
4234 temp->ttl = (time_t)t;
4235 temp->negttl = (time_t)0;
4236 temp->limitttl = (time_t)0;
4237 temp->ttr = (time_t)0;
4238 switch ( c->argc ) {
4239 case 7:
4240 if ( lutil_parse_time( c->argv[6], &t ) != 0 ) {
4241 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4242 "unable to parse template ttr=\"%s\"",
4243 c->argv[6] );
4244 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4245 goto pc_temp_fail;
4246 }
4247 temp->ttr = (time_t)t;
4248 /* fallthru */
4249
4250 case 6:
4251 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
4252 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4253 "unable to parse template sizelimit ttl=\"%s\"",
4254 c->argv[5] );
4255 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4256 goto pc_temp_fail;
4257 }
4258 temp->limitttl = (time_t)t;
4259 /* fallthru */
4260
4261 case 5:
4262 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
4263 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4264 "unable to parse template negative ttl=\"%s\"",
4265 c->argv[4] );
4266 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4267 goto pc_temp_fail;
4268 }
4269 temp->negttl = (time_t)t;
4270 break;
4271 }
4272
4273 temp->no_of_queries = 0;
4274
4275 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
4276 Debug( pcache_debug, "Template:\n" );
4277 Debug( pcache_debug, " query template: %s\n",
4278 temp->querystr.bv_val );
4279 temp->attr_set_index = i;
4280 qm->attr_sets[i].flags |= PC_REFERENCED;
4281 temp->qtnext = qm->attr_sets[i].templates;
4282 qm->attr_sets[i].templates = temp;
4283 Debug( pcache_debug, " attributes: \n" );
4284 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
4285 for ( i=0; attrarray[i].an_name.bv_val; i++ )
4286 Debug( pcache_debug, "\t%s\n",
4287 attrarray[i].an_name.bv_val );
4288 }
4289 break;
4290 case PC_BIND:
4291 if ( !qm->templates ) {
4292 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"pcacheTemplate\" directive not provided yet" );
4293 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4294 return( 1 );
4295 }
4296 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
4297 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse Bind index #=\"%s\"",
4298 c->argv[2] );
4299 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4300 return( 1 );
4301 }
4302
4303 if ( i < 0 || i >= cm->numattrsets ||
4304 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
4305 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind index %d invalid (%s%d)",
4306 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
4307 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4308 return 1;
4309 }
4310 { struct berval bv, tempbv;
4311 AttributeDescription **descs;
4312 int ndescs;
4313 ber_str2bv( c->argv[1], 0, 0, &bv );
4314 ndescs = ftemp_attrs( &bv, &tempbv, &descs, &text );
4315 if ( ndescs < 0 ) {
4316 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template: %s",
4317 text );
4318 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4319 return 1;
4320 }
4321 for ( temp = qm->templates; temp; temp=temp->qmnext ) {
4322 if ( temp->attr_set_index == i && bvmatch( &tempbv,
4323 &temp->querystr ))
4324 break;
4325 }
4326 ch_free( tempbv.bv_val );
4327 if ( !temp ) {
4328 ch_free( descs );
4329 snprintf( c->cr_msg, sizeof( c->cr_msg ), "Bind template %s %d invalid",
4330 c->argv[1], i );
4331 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4332 return 1;
4333 }
4334 ber_dupbv( &temp->bindftemp, &bv );
4335 temp->bindfattrs = descs;
4336 temp->bindnattrs = ndescs;
4337 }
4338 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
4339 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4340 "unable to parse bind ttr=\"%s\"",
4341 c->argv[3] );
4342 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4343 pc_bind_fail:
4344 ch_free( temp->bindfattrs );
4345 temp->bindfattrs = NULL;
4346 ch_free( temp->bindftemp.bv_val );
4347 BER_BVZERO( &temp->bindftemp );
4348 return( 1 );
4349 }
4350 num = ldap_pvt_str2scope( c->argv[4] );
4351 if ( num < 0 ) {
4352 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4353 "unable to parse bind scope=\"%s\"",
4354 c->argv[4] );
4355 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4356 goto pc_bind_fail;
4357 }
4358 {
4359 struct berval dn, ndn;
4360 ber_str2bv( c->argv[5], 0, 0, &dn );
4361 rc = dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL );
4362 if ( rc ) {
4363 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4364 "invalid bind baseDN=\"%s\"",
4365 c->argv[5] );
4366 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4367 goto pc_bind_fail;
4368 }
4369 if ( temp->bindbase.bv_val )
4370 ch_free( temp->bindbase.bv_val );
4371 temp->bindbase = ndn;
4372 }
4373 {
4374 /* convert the template into dummy filter */
4375 struct berval bv;
4376 char *eq = temp->bindftemp.bv_val, *e2;
4377 Filter *f;
4378 i = 0;
4379 while ((eq = strchr(eq, '=' ))) {
4380 eq++;
4381 if ( eq[0] == ')' )
4382 i++;
4383 }
4384 bv.bv_len = temp->bindftemp.bv_len + i;
4385 bv.bv_val = ch_malloc( bv.bv_len + 1 );
4386 for ( e2 = bv.bv_val, eq = temp->bindftemp.bv_val;
4387 *eq; eq++ ) {
4388 if ( *eq == '=' ) {
4389 *e2++ = '=';
4390 if ( eq[1] == ')' )
4391 *e2++ = '*';
4392 } else {
4393 *e2++ = *eq;
4394 }
4395 }
4396 *e2 = '\0';
4397 f = str2filter( bv.bv_val );
4398 if ( !f ) {
4399 ch_free( bv.bv_val );
4400 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4401 "unable to parse bindfilter=\"%s\"", bv.bv_val );
4402 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4403 ch_free( temp->bindbase.bv_val );
4404 BER_BVZERO( &temp->bindbase );
4405 goto pc_bind_fail;
4406 }
4407 if ( temp->bindfilter )
4408 filter_free( temp->bindfilter );
4409 if ( temp->bindfilterstr.bv_val )
4410 ch_free( temp->bindfilterstr.bv_val );
4411 temp->bindfilterstr = bv;
4412 temp->bindfilter = f;
4413 }
4414 temp->bindttr = (time_t)t;
4415 temp->bindscope = num;
4416 cm->cache_binds = 1;
4417 break;
4418
4419 case PC_RESP:
4420 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
4421 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
4422
4423 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
4424 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4425
4426 } else {
4427 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
4428 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4429 return 1;
4430 }
4431 break;
4432 case PC_QUERIES:
4433 if ( c->value_int <= 0 ) {
4434 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
4435 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4436 return( 1 );
4437 }
4438 cm->max_queries = c->value_int;
4439 break;
4440 case PC_OFFLINE:
4441 if ( c->value_int )
4442 cm->cc_paused |= PCACHE_CC_OFFLINE;
4443 else
4444 cm->cc_paused &= ~PCACHE_CC_OFFLINE;
4445 break;
4446 case PC_PRIVATE_DB:
4447 if ( cm->db.be_private == NULL ) {
4448 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4449 "private database must be defined before setting database specific options" );
4450 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4451 return( 1 );
4452 }
4453
4454 if ( cm->db.bd_info->bi_cf_ocs ) {
4455 ConfigTable *ct;
4456 ConfigArgs c2 = *c;
4457 char *argv0 = c->argv[ 0 ];
4458
4459 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4460
4461 ct = config_find_keyword( cm->db.bd_info->bi_cf_ocs->co_table, c );
4462 if ( ct == NULL ) {
4463 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4464 "private database does not recognize specific option '%s'",
4465 c->argv[ 0 ] );
4466 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4467 rc = 1;
4468
4469 } else {
4470 c->table = cm->db.bd_info->bi_cf_ocs->co_type;
4471 c->be = &cm->db;
4472 c->bi = c->be->bd_info;
4473
4474 rc = config_add_vals( ct, c );
4475
4476 c->bi = c2.bi;
4477 c->be = c2.be;
4478 c->table = c2.table;
4479 }
4480
4481 c->argv[ 0 ] = argv0;
4482
4483 } else if ( cm->db.be_config != NULL ) {
4484 char *argv0 = c->argv[ 0 ];
4485
4486 c->argv[ 0 ] = &argv0[ STRLENOF( "pcache-" ) ];
4487 rc = cm->db.be_config( &cm->db, c->fname, c->lineno, c->argc, c->argv );
4488 c->argv[ 0 ] = argv0;
4489
4490 } else {
4491 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4492 "no means to set private database specific options" );
4493 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg );
4494 return 1;
4495 }
4496 break;
4497 default:
4498 rc = SLAP_CONF_UNKNOWN;
4499 break;
4500 }
4501
4502 return rc;
4503 }
4504
4505 static int
pcache_db_config(BackendDB * be,const char * fname,int lineno,int argc,char ** argv)4506 pcache_db_config(
4507 BackendDB *be,
4508 const char *fname,
4509 int lineno,
4510 int argc,
4511 char **argv
4512 )
4513 {
4514 slap_overinst *on = (slap_overinst *)be->bd_info;
4515 cache_manager* cm = on->on_bi.bi_private;
4516
4517 /* Something for the cache database? */
4518 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
4519 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
4520 argc, argv );
4521 return SLAP_CONF_UNKNOWN;
4522 }
4523
4524 static int
pcache_db_init(BackendDB * be,ConfigReply * cr)4525 pcache_db_init(
4526 BackendDB *be,
4527 ConfigReply *cr)
4528 {
4529 slap_overinst *on = (slap_overinst *)be->bd_info;
4530 cache_manager *cm;
4531 query_manager *qm;
4532
4533 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
4534 on->on_bi.bi_private = cm;
4535
4536 qm = (query_manager*)ch_malloc(sizeof(query_manager));
4537
4538 cm->db = *be;
4539 cm->db.bd_info = NULL;
4540 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
4541 cm->db.be_private = NULL;
4542 cm->db.bd_self = &cm->db;
4543 cm->db.be_pending_csn_list = NULL;
4544 cm->qm = qm;
4545 cm->numattrsets = 0;
4546 cm->num_entries_limit = 5;
4547 cm->num_cached_queries = 0;
4548 cm->max_entries = 0;
4549 cm->cur_entries = 0;
4550 cm->max_queries = 10000;
4551 cm->save_queries = 0;
4552 cm->check_cacheability = 0;
4553 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
4554 cm->defer_db_open = 1;
4555 cm->cache_binds = 0;
4556 cm->cc_period = 1000;
4557 cm->cc_paused = 0;
4558 cm->cc_arg = NULL;
4559 #ifdef PCACHE_MONITOR
4560 cm->monitor_cb = NULL;
4561 #endif /* PCACHE_MONITOR */
4562
4563 qm->attr_sets = NULL;
4564 qm->templates = NULL;
4565 qm->lru_top = NULL;
4566 qm->lru_bottom = NULL;
4567
4568 qm->qcfunc = query_containment;
4569 qm->crfunc = cache_replacement;
4570 qm->addfunc = add_query;
4571 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
4572
4573 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
4574
4575 #ifndef PCACHE_MONITOR
4576 return 0;
4577 #else /* PCACHE_MONITOR */
4578 return pcache_monitor_db_init( be );
4579 #endif /* PCACHE_MONITOR */
4580 }
4581
4582 static int
pcache_cachedquery_open_cb(Operation * op,SlapReply * rs)4583 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
4584 {
4585 assert( op->o_tag == LDAP_REQ_SEARCH );
4586
4587 if ( rs->sr_type == REP_SEARCH ) {
4588 Attribute *a;
4589
4590 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
4591 if ( a != NULL ) {
4592 BerVarray *valsp;
4593
4594 assert( a->a_nvals != NULL );
4595
4596 valsp = op->o_callback->sc_private;
4597 assert( *valsp == NULL );
4598
4599 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
4600 }
4601 }
4602
4603 return 0;
4604 }
4605
4606 static int
pcache_cachedquery_count_cb(Operation * op,SlapReply * rs)4607 pcache_cachedquery_count_cb( Operation *op, SlapReply *rs )
4608 {
4609 assert( op->o_tag == LDAP_REQ_SEARCH );
4610
4611 if ( rs->sr_type == REP_SEARCH ) {
4612 int *countp = (int *)op->o_callback->sc_private;
4613
4614 (*countp)++;
4615 }
4616
4617 return 0;
4618 }
4619
4620 static int
pcache_db_open2(slap_overinst * on,ConfigReply * cr)4621 pcache_db_open2(
4622 slap_overinst *on,
4623 ConfigReply *cr )
4624 {
4625 cache_manager *cm = on->on_bi.bi_private;
4626 query_manager* qm = cm->qm;
4627 int rc;
4628
4629 rc = backend_startup_one( &cm->db, cr );
4630 if ( rc == 0 ) {
4631 cm->defer_db_open = 0;
4632 }
4633
4634 /* There is no runqueue in TOOL mode */
4635 if (( slapMode & SLAP_SERVER_MODE ) && rc == 0 ) {
4636 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4637 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
4638 consistency_check, on,
4639 "pcache_consistency", cm->db.be_suffix[0].bv_val );
4640 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4641
4642 /* Cached database must have the rootdn */
4643 if ( BER_BVISNULL( &cm->db.be_rootndn )
4644 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
4645 {
4646 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
4647 "underlying database of type \"%s\"\n"
4648 " serving naming context \"%s\"\n"
4649 " has no \"rootdn\", required by \"pcache\".\n",
4650 on->on_info->oi_orig->bi_type,
4651 cm->db.be_suffix[0].bv_val );
4652 return 1;
4653 }
4654
4655 if ( cm->save_queries ) {
4656 void *thrctx = ldap_pvt_thread_pool_context();
4657 Connection conn = { 0 };
4658 OperationBuffer opbuf;
4659 Operation *op;
4660 slap_callback cb = { 0 };
4661 SlapReply rs = { REP_RESULT };
4662 BerVarray vals = NULL;
4663 Filter f = { 0 }, f2 = { 0 };
4664 AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
4665 AttributeName attrs[ 2 ] = {{{ 0 }}};
4666
4667 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4668 op = &opbuf.ob_op;
4669
4670 op->o_bd = &cm->db;
4671
4672 op->o_tag = LDAP_REQ_SEARCH;
4673 op->o_protocol = LDAP_VERSION3;
4674 cb.sc_response = pcache_cachedquery_open_cb;
4675 cb.sc_private = &vals;
4676 op->o_callback = &cb;
4677 op->o_time = slap_get_time();
4678 op->o_do_not_cache = 1;
4679 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4680
4681 op->o_dn = cm->db.be_rootdn;
4682 op->o_ndn = cm->db.be_rootndn;
4683 op->o_req_dn = cm->db.be_suffix[ 0 ];
4684 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
4685
4686 op->ors_scope = LDAP_SCOPE_BASE;
4687 op->ors_deref = LDAP_DEREF_NEVER;
4688 op->ors_slimit = 1;
4689 op->ors_tlimit = SLAP_NO_LIMIT;
4690 op->ors_limit = NULL;
4691 ber_str2bv( "(pcacheQueryURL=*)", 0, 0, &op->ors_filterstr );
4692 f.f_choice = LDAP_FILTER_PRESENT;
4693 f.f_desc = ad_cachedQueryURL;
4694 op->ors_filter = &f;
4695 attrs[ 0 ].an_desc = ad_cachedQueryURL;
4696 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
4697 op->ors_attrs = attrs;
4698 op->ors_attrsonly = 0;
4699
4700 rc = op->o_bd->be_search( op, &rs );
4701 if ( rc == LDAP_SUCCESS && vals != NULL ) {
4702 int i;
4703
4704 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
4705 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
4706 cm->num_cached_queries++;
4707 }
4708 }
4709
4710 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4711 }
4712
4713 /* count cached entries */
4714 f.f_choice = LDAP_FILTER_NOT;
4715 f.f_not = &f2;
4716 f2.f_choice = LDAP_FILTER_EQUALITY;
4717 f2.f_ava = &ava;
4718 f2.f_av_desc = slap_schema.si_ad_objectClass;
4719 BER_BVSTR( &f2.f_av_value, "glue" );
4720 ber_str2bv( "(!(objectClass=glue))", 0, 0, &op->ors_filterstr );
4721
4722 op->ors_slimit = SLAP_NO_LIMIT;
4723 op->ors_scope = LDAP_SCOPE_SUBTREE;
4724 op->ors_attrs = slap_anlist_no_attrs;
4725
4726 rs_reinit( &rs, REP_RESULT );
4727 op->o_callback->sc_response = pcache_cachedquery_count_cb;
4728 op->o_callback->sc_private = &rs.sr_nentries;
4729
4730 rc = op->o_bd->be_search( op, &rs );
4731
4732 cm->cur_entries = rs.sr_nentries;
4733
4734 /* ignore errors */
4735 rc = 0;
4736 }
4737 }
4738 return rc;
4739 }
4740
4741 static int
pcache_db_open(BackendDB * be,ConfigReply * cr)4742 pcache_db_open(
4743 BackendDB *be,
4744 ConfigReply *cr )
4745 {
4746 slap_overinst *on = (slap_overinst *)be->bd_info;
4747 cache_manager *cm = on->on_bi.bi_private;
4748 query_manager* qm = cm->qm;
4749 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
4750
4751 /* check attr sets */
4752 for ( i = 0; i < cm->numattrsets; i++) {
4753 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
4754 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
4755 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i );
4756 rf++;
4757
4758 } else {
4759 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i );
4760 }
4761 ncf++;
4762
4763 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
4764 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i );
4765 nrf++;
4766 }
4767 }
4768
4769 if ( ncf || rf || nrf ) {
4770 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf );
4771 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf );
4772 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf );
4773
4774 if ( rf > 0 ) {
4775 return 1;
4776 }
4777 }
4778
4779 /* need to inherit something from the original database... */
4780 cm->db.be_def_limit = be->be_def_limit;
4781 cm->db.be_limits = be->be_limits;
4782 cm->db.be_acl = be->be_acl;
4783 cm->db.be_dfltaccess = be->be_dfltaccess;
4784
4785 if ( SLAP_DBMONITORING( be ) ) {
4786 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
4787
4788 } else {
4789 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
4790 }
4791
4792 if ( !cm->defer_db_open ) {
4793 rc = pcache_db_open2( on, cr );
4794 }
4795
4796 #ifdef PCACHE_MONITOR
4797 if ( rc == LDAP_SUCCESS ) {
4798 rc = pcache_monitor_db_open( be );
4799 }
4800 #endif /* PCACHE_MONITOR */
4801
4802 return rc;
4803 }
4804
4805 static void
pcache_free_qbase(void * v)4806 pcache_free_qbase( void *v )
4807 {
4808 Qbase *qb = v;
4809 int i;
4810
4811 for (i=0; i<3; i++)
4812 ldap_tavl_free( qb->scopes[i], NULL );
4813 ch_free( qb );
4814 }
4815
4816 static int
pcache_db_close(BackendDB * be,ConfigReply * cr)4817 pcache_db_close(
4818 BackendDB *be,
4819 ConfigReply *cr
4820 )
4821 {
4822 slap_overinst *on = (slap_overinst *)be->bd_info;
4823 cache_manager *cm = on->on_bi.bi_private;
4824 query_manager *qm = cm->qm;
4825 QueryTemplate *tm;
4826 int rc = 0;
4827
4828 /* stop the thread ... */
4829 if ( cm->cc_arg ) {
4830 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4831 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, cm->cc_arg ) ) {
4832 ldap_pvt_runqueue_stoptask( &slapd_rq, cm->cc_arg );
4833 }
4834 ldap_pvt_runqueue_remove( &slapd_rq, cm->cc_arg );
4835 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4836 cm->cc_arg = NULL;
4837 }
4838
4839 if ( cm->save_queries ) {
4840 CachedQuery *qc;
4841 BerVarray vals = NULL;
4842
4843 void *thrctx;
4844 Connection conn = { 0 };
4845 OperationBuffer opbuf;
4846 Operation *op;
4847 slap_callback cb = { 0 };
4848
4849 SlapReply rs = { REP_RESULT };
4850 Modifications mod = {{ 0 }};
4851
4852 thrctx = ldap_pvt_thread_pool_context();
4853
4854 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4855 op = &opbuf.ob_op;
4856
4857 mod.sml_numvals = 0;
4858 if ( qm->templates != NULL ) {
4859 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
4860 for ( qc = tm->query; qc; qc = qc->next ) {
4861 struct berval bv;
4862
4863 if ( query2url( op, qc, &bv, 0 ) == 0 ) {
4864 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
4865 mod.sml_numvals++;
4866 }
4867 }
4868 }
4869 }
4870
4871 op->o_bd = &cm->db;
4872 op->o_dn = cm->db.be_rootdn;
4873 op->o_ndn = cm->db.be_rootndn;
4874
4875 op->o_tag = LDAP_REQ_MODIFY;
4876 op->o_protocol = LDAP_VERSION3;
4877 cb.sc_response = slap_null_cb;
4878 op->o_callback = &cb;
4879 op->o_time = slap_get_time();
4880 op->o_do_not_cache = 1;
4881 op->o_managedsait = SLAP_CONTROL_CRITICAL;
4882
4883 op->o_req_dn = op->o_bd->be_suffix[0];
4884 op->o_req_ndn = op->o_bd->be_nsuffix[0];
4885
4886 mod.sml_op = LDAP_MOD_REPLACE;
4887 mod.sml_flags = 0;
4888 mod.sml_desc = ad_cachedQueryURL;
4889 mod.sml_type = ad_cachedQueryURL->ad_cname;
4890 mod.sml_values = vals;
4891 mod.sml_nvalues = NULL;
4892 mod.sml_next = NULL;
4893 Debug( pcache_debug,
4894 "%sSETTING CACHED QUERY URLS\n",
4895 vals == NULL ? "RE" : "" );
4896
4897 op->orm_modlist = &mod;
4898
4899 op->o_bd->be_modify( op, &rs );
4900
4901 ber_bvarray_free_x( vals, op->o_tmpmemctx );
4902 }
4903
4904 /* cleanup stuff inherited from the original database... */
4905 cm->db.be_limits = NULL;
4906 cm->db.be_acl = NULL;
4907
4908 if ( cm->db.bd_info->bi_db_close ) {
4909 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
4910 }
4911
4912 #ifdef PCACHE_MONITOR
4913 if ( rc == LDAP_SUCCESS ) {
4914 rc = pcache_monitor_db_close( be );
4915 }
4916 #endif /* PCACHE_MONITOR */
4917
4918 return rc;
4919 }
4920
4921 static int
pcache_db_destroy(BackendDB * be,ConfigReply * cr)4922 pcache_db_destroy(
4923 BackendDB *be,
4924 ConfigReply *cr
4925 )
4926 {
4927 slap_overinst *on = (slap_overinst *)be->bd_info;
4928 cache_manager *cm = on->on_bi.bi_private;
4929 query_manager *qm = cm->qm;
4930 QueryTemplate *tm;
4931 int i;
4932
4933 if ( cm->db.be_private != NULL ) {
4934 backend_stopdown_one( &cm->db );
4935 }
4936
4937 while ( (tm = qm->templates) != NULL ) {
4938 CachedQuery *qc, *qn;
4939 qm->templates = tm->qmnext;
4940 for ( qc = tm->query; qc; qc = qn ) {
4941 qn = qc->next;
4942 free_query( qc );
4943 }
4944 ldap_avl_free( tm->qbase, pcache_free_qbase );
4945 free( tm->querystr.bv_val );
4946 free( tm->bindfattrs );
4947 free( tm->bindftemp.bv_val );
4948 free( tm->bindfilterstr.bv_val );
4949 free( tm->bindbase.bv_val );
4950 filter_free( tm->bindfilter );
4951 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
4952 free( tm->t_attrs.attrs );
4953 free( tm );
4954 }
4955
4956 for ( i = 0; i < cm->numattrsets; i++ ) {
4957 int j;
4958
4959 /* Account of LDAP_NO_ATTRS */
4960 if ( !qm->attr_sets[i].count ) continue;
4961
4962 for ( j = 0; !BER_BVISNULL( &qm->attr_sets[i].attrs[j].an_name ); j++ ) {
4963 if ( qm->attr_sets[i].attrs[j].an_desc &&
4964 ( qm->attr_sets[i].attrs[j].an_desc->ad_flags &
4965 SLAP_DESC_TEMPORARY ) ) {
4966 slap_sl_mfuncs.bmf_free( qm->attr_sets[i].attrs[j].an_desc, NULL );
4967 }
4968 }
4969 free( qm->attr_sets[i].attrs );
4970 }
4971 free( qm->attr_sets );
4972 qm->attr_sets = NULL;
4973
4974 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
4975 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
4976 free( qm );
4977 free( cm );
4978
4979 #ifdef PCACHE_MONITOR
4980 pcache_monitor_db_destroy( be );
4981 #endif /* PCACHE_MONITOR */
4982
4983 return 0;
4984 }
4985
4986 #ifdef PCACHE_CONTROL_PRIVDB
4987 /*
4988 Control ::= SEQUENCE {
4989 controlType LDAPOID,
4990 criticality BOOLEAN DEFAULT FALSE,
4991 controlValue OCTET STRING OPTIONAL }
4992
4993 controlType ::= 1.3.6.1.4.1.4203.666.11.9.5.1
4994
4995 * criticality must be TRUE; controlValue must be absent.
4996 */
4997 static int
parse_privdb_ctrl(Operation * op,SlapReply * rs,LDAPControl * ctrl)4998 parse_privdb_ctrl(
4999 Operation *op,
5000 SlapReply *rs,
5001 LDAPControl *ctrl )
5002 {
5003 if ( op->o_ctrlflag[ privDB_cid ] != SLAP_CONTROL_NONE ) {
5004 rs->sr_text = "privateDB control specified multiple times";
5005 return LDAP_PROTOCOL_ERROR;
5006 }
5007
5008 if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
5009 rs->sr_text = "privateDB control value not absent";
5010 return LDAP_PROTOCOL_ERROR;
5011 }
5012
5013 if ( !ctrl->ldctl_iscritical ) {
5014 rs->sr_text = "privateDB control criticality required";
5015 return LDAP_PROTOCOL_ERROR;
5016 }
5017
5018 op->o_ctrlflag[ privDB_cid ] = SLAP_CONTROL_CRITICAL;
5019
5020 return LDAP_SUCCESS;
5021 }
5022
5023 static char *extops[] = {
5024 LDAP_EXOP_MODIFY_PASSWD,
5025 NULL
5026 };
5027 #endif /* PCACHE_CONTROL_PRIVDB */
5028
5029 static struct berval pcache_exop_MODIFY_PASSWD = BER_BVC( LDAP_EXOP_MODIFY_PASSWD );
5030 #ifdef PCACHE_EXOP_QUERY_DELETE
5031 static struct berval pcache_exop_QUERY_DELETE = BER_BVC( PCACHE_EXOP_QUERY_DELETE );
5032
5033 #define LDAP_TAG_EXOP_QUERY_DELETE_BASE ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 0)
5034 #define LDAP_TAG_EXOP_QUERY_DELETE_DN ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 1)
5035 #define LDAP_TAG_EXOP_QUERY_DELETE_UUID ((LBER_CLASS_CONTEXT|LBER_CONSTRUCTED) + 2)
5036
5037 /*
5038 ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
5039 requestName [0] LDAPOID,
5040 requestValue [1] OCTET STRING OPTIONAL }
5041
5042 requestName ::= 1.3.6.1.4.1.4203.666.11.9.6.1
5043
5044 requestValue ::= SEQUENCE { CHOICE {
5045 baseDN [0] LDAPDN
5046 entryDN [1] LDAPDN },
5047 queryID [2] OCTET STRING (SIZE(16))
5048 -- constrained to UUID }
5049
5050 * Either baseDN or entryDN must be present, to allow database selection.
5051 *
5052 * 1. if baseDN and queryID are present, then the query corresponding
5053 * to queryID is deleted;
5054 * 2. if baseDN is present and queryID is absent, then all queries
5055 * are deleted;
5056 * 3. if entryDN is present and queryID is absent, then all queries
5057 * corresponding to the queryID values present in entryDN are deleted;
5058 * 4. if entryDN and queryID are present, then all queries
5059 * corresponding to the queryID values present in entryDN are deleted,
5060 * but only if the value of queryID is contained in the entry;
5061 *
5062 * Currently, only 1, 3 and 4 are implemented. 2 can be obtained by either
5063 * recursively deleting the database (ldapdelete -r) with PRIVDB control,
5064 * or by removing the database files.
5065
5066 ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
5067 COMPONENTS OF LDAPResult,
5068 responseName [10] LDAPOID OPTIONAL,
5069 responseValue [11] OCTET STRING OPTIONAL }
5070
5071 * responseName and responseValue must be absent.
5072 */
5073
5074 /*
5075 * - on success, *tagp is either LDAP_TAG_EXOP_QUERY_DELETE_BASE
5076 * or LDAP_TAG_EXOP_QUERY_DELETE_DN.
5077 * - if ndn != NULL, it is set to the normalized DN in the request
5078 * corresponding to either the baseDN or the entryDN, according
5079 * to *tagp; memory is malloc'ed on the Operation's slab, and must
5080 * be freed by the caller.
5081 * - if uuid != NULL, it is set to point to the normalized UUID;
5082 * memory is malloc'ed on the Operation's slab, and must
5083 * be freed by the caller.
5084 */
5085 static int
pcache_parse_query_delete(struct berval * in,ber_tag_t * tagp,struct berval * ndn,struct berval * uuid,const char ** text,void * ctx)5086 pcache_parse_query_delete(
5087 struct berval *in,
5088 ber_tag_t *tagp,
5089 struct berval *ndn,
5090 struct berval *uuid,
5091 const char **text,
5092 void *ctx )
5093 {
5094 int rc = LDAP_SUCCESS;
5095 ber_tag_t tag;
5096 ber_len_t len = -1;
5097 BerElementBuffer berbuf;
5098 BerElement *ber = (BerElement *)&berbuf;
5099 struct berval reqdata = BER_BVNULL;
5100
5101 *text = NULL;
5102
5103 if ( ndn ) {
5104 BER_BVZERO( ndn );
5105 }
5106
5107 if ( uuid ) {
5108 BER_BVZERO( uuid );
5109 }
5110
5111 if ( in == NULL || in->bv_len == 0 ) {
5112 *text = "empty request data field in queryDelete exop";
5113 return LDAP_PROTOCOL_ERROR;
5114 }
5115
5116 ber_dupbv_x( &reqdata, in, ctx );
5117
5118 /* ber_init2 uses reqdata directly, doesn't allocate new buffers */
5119 ber_init2( ber, &reqdata, 0 );
5120
5121 tag = ber_scanf( ber, "{" /*}*/ );
5122
5123 if ( tag == LBER_ERROR ) {
5124 Debug( LDAP_DEBUG_TRACE,
5125 "pcache_parse_query_delete: decoding error.\n" );
5126 goto decoding_error;
5127 }
5128
5129 tag = ber_peek_tag( ber, &len );
5130 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE
5131 || tag == LDAP_TAG_EXOP_QUERY_DELETE_DN )
5132 {
5133 *tagp = tag;
5134
5135 if ( ndn != NULL ) {
5136 struct berval dn;
5137
5138 tag = ber_scanf( ber, "m", &dn );
5139 if ( tag == LBER_ERROR ) {
5140 Debug( LDAP_DEBUG_TRACE,
5141 "pcache_parse_query_delete: DN parse failed.\n" );
5142 goto decoding_error;
5143 }
5144
5145 rc = dnNormalize( 0, NULL, NULL, &dn, ndn, ctx );
5146 if ( rc != LDAP_SUCCESS ) {
5147 *text = "invalid DN in queryDelete exop request data";
5148 goto done;
5149 }
5150
5151 } else {
5152 tag = ber_scanf( ber, "x" /* "m" */ );
5153 if ( tag == LBER_DEFAULT ) {
5154 goto decoding_error;
5155 }
5156 }
5157
5158 tag = ber_peek_tag( ber, &len );
5159 }
5160
5161 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_UUID ) {
5162 if ( uuid != NULL ) {
5163 struct berval bv;
5164 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
5165
5166 tag = ber_scanf( ber, "m", &bv );
5167 if ( tag == LBER_ERROR ) {
5168 Debug( LDAP_DEBUG_TRACE,
5169 "pcache_parse_query_delete: UUID parse failed.\n" );
5170 goto decoding_error;
5171 }
5172
5173 if ( bv.bv_len != 16 ) {
5174 Debug( LDAP_DEBUG_TRACE,
5175 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5176 (unsigned long)bv.bv_len );
5177 goto decoding_error;
5178 }
5179
5180 rc = lutil_uuidstr_from_normalized(
5181 bv.bv_val, bv.bv_len,
5182 uuidbuf, sizeof( uuidbuf ) );
5183 if ( rc == -1 ) {
5184 goto decoding_error;
5185 }
5186 ber_str2bv( uuidbuf, rc, 1, uuid );
5187 rc = LDAP_SUCCESS;
5188
5189 } else {
5190 tag = ber_skip_tag( ber, &len );
5191 if ( tag == LBER_DEFAULT ) {
5192 goto decoding_error;
5193 }
5194
5195 if ( len != 16 ) {
5196 Debug( LDAP_DEBUG_TRACE,
5197 "pcache_parse_query_delete: invalid UUID length %lu.\n",
5198 (unsigned long)len );
5199 goto decoding_error;
5200 }
5201 }
5202
5203 tag = ber_peek_tag( ber, &len );
5204 }
5205
5206 if ( tag != LBER_DEFAULT || len != 0 ) {
5207 decoding_error:;
5208 Debug( LDAP_DEBUG_TRACE,
5209 "pcache_parse_query_delete: decoding error\n" );
5210 rc = LDAP_PROTOCOL_ERROR;
5211 *text = "queryDelete data decoding error";
5212
5213 done:;
5214 if ( ndn && !BER_BVISNULL( ndn ) ) {
5215 slap_sl_free( ndn->bv_val, ctx );
5216 BER_BVZERO( ndn );
5217 }
5218
5219 if ( uuid && !BER_BVISNULL( uuid ) ) {
5220 slap_sl_free( uuid->bv_val, ctx );
5221 BER_BVZERO( uuid );
5222 }
5223 }
5224
5225 if ( !BER_BVISNULL( &reqdata ) ) {
5226 ber_memfree_x( reqdata.bv_val, ctx );
5227 }
5228
5229 return rc;
5230 }
5231
5232 static int
pcache_exop_query_delete(Operation * op,SlapReply * rs)5233 pcache_exop_query_delete(
5234 Operation *op,
5235 SlapReply *rs )
5236 {
5237 BackendDB *bd = op->o_bd;
5238
5239 struct berval uuid = BER_BVNULL,
5240 *uuidp = NULL;
5241 char buf[ SLAP_TEXT_BUFLEN ];
5242 unsigned len;
5243 ber_tag_t tag = LBER_DEFAULT;
5244
5245 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5246 uuidp = &uuid;
5247 }
5248
5249 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5250 &tag, &op->o_req_ndn, uuidp,
5251 &rs->sr_text, op->o_tmpmemctx );
5252 if ( rs->sr_err != LDAP_SUCCESS ) {
5253 return rs->sr_err;
5254 }
5255
5256 if ( LogTest( LDAP_DEBUG_STATS ) ) {
5257 assert( !BER_BVISNULL( &op->o_req_ndn ) );
5258 len = snprintf( buf, sizeof( buf ), " dn=\"%s\"", op->o_req_ndn.bv_val );
5259
5260 if ( !BER_BVISNULL( &uuid ) && len < sizeof( buf ) ) {
5261 snprintf( &buf[ len ], sizeof( buf ) - len, " pcacheQueryId=\"%s\"", uuid.bv_val );
5262 }
5263
5264 Debug( LDAP_DEBUG_STATS, "%s QUERY DELETE%s\n",
5265 op->o_log_prefix, buf );
5266 }
5267 op->o_req_dn = op->o_req_ndn;
5268
5269 op->o_bd = select_backend( &op->o_req_ndn, 0 );
5270 if ( op->o_bd == NULL ) {
5271 send_ldap_error( op, rs, LDAP_NO_SUCH_OBJECT,
5272 "no global superior knowledge" );
5273 }
5274 rs->sr_err = backend_check_restrictions( op, rs,
5275 (struct berval *)&pcache_exop_QUERY_DELETE );
5276 if ( rs->sr_err != LDAP_SUCCESS ) {
5277 goto done;
5278 }
5279
5280 if ( op->o_bd->be_extended == NULL ) {
5281 send_ldap_error( op, rs, LDAP_UNAVAILABLE_CRITICAL_EXTENSION,
5282 "backend does not support extended operations" );
5283 goto done;
5284 }
5285
5286 op->o_bd->be_extended( op, rs );
5287
5288 done:;
5289 if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
5290 op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
5291 BER_BVZERO( &op->o_req_ndn );
5292 BER_BVZERO( &op->o_req_dn );
5293 }
5294
5295 if ( !BER_BVISNULL( &uuid ) ) {
5296 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5297 }
5298
5299 op->o_bd = bd;
5300
5301 return rs->sr_err;
5302 }
5303 #endif /* PCACHE_EXOP_QUERY_DELETE */
5304
5305 static int
pcache_op_extended(Operation * op,SlapReply * rs)5306 pcache_op_extended( Operation *op, SlapReply *rs )
5307 {
5308 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5309 cache_manager *cm = on->on_bi.bi_private;
5310
5311 #ifdef PCACHE_CONTROL_PRIVDB
5312 if ( op->o_ctrlflag[ privDB_cid ] == SLAP_CONTROL_CRITICAL ) {
5313 return pcache_op_privdb( op, rs );
5314 }
5315 #endif /* PCACHE_CONTROL_PRIVDB */
5316
5317 #ifdef PCACHE_EXOP_QUERY_DELETE
5318 if ( bvmatch( &op->ore_reqoid, &pcache_exop_QUERY_DELETE ) ) {
5319 struct berval uuid = BER_BVNULL;
5320 ber_tag_t tag = LBER_DEFAULT;
5321
5322 rs->sr_err = pcache_parse_query_delete( op->ore_reqdata,
5323 &tag, NULL, &uuid, &rs->sr_text, op->o_tmpmemctx );
5324 assert( rs->sr_err == LDAP_SUCCESS );
5325
5326 if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_DN ) {
5327 /* remove all queries related to the selected entry */
5328 rs->sr_err = pcache_remove_entry_queries_from_cache( op,
5329 cm, &op->o_req_ndn, &uuid );
5330
5331 } else if ( tag == LDAP_TAG_EXOP_QUERY_DELETE_BASE ) {
5332 if ( !BER_BVISNULL( &uuid ) ) {
5333 /* remove the selected query */
5334 rs->sr_err = pcache_remove_query_from_cache( op,
5335 cm, &uuid );
5336
5337 } else {
5338 /* TODO: remove all queries */
5339 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
5340 rs->sr_text = "deletion of all queries not implemented";
5341 }
5342 }
5343
5344 op->o_tmpfree( uuid.bv_val, op->o_tmpmemctx );
5345 return rs->sr_err;
5346 }
5347 #endif /* PCACHE_EXOP_QUERY_DELETE */
5348
5349 /* We only care if we're configured for Bind caching */
5350 if ( bvmatch( &op->ore_reqoid, &pcache_exop_MODIFY_PASSWD ) &&
5351 cm->cache_binds ) {
5352 /* See if the local entry exists and has a password.
5353 * It's too much work to find the matching query, so
5354 * we just see if there's a hashed password to update.
5355 */
5356 Operation op2 = *op;
5357 Entry *e = NULL;
5358 int rc;
5359 int doit = 0;
5360
5361 op2.o_bd = &cm->db;
5362 op2.o_dn = op->o_bd->be_rootdn;
5363 op2.o_ndn = op->o_bd->be_rootndn;
5364 rc = be_entry_get_rw( &op2, &op->o_req_ndn, NULL,
5365 slap_schema.si_ad_userPassword, 0, &e );
5366 if ( rc == LDAP_SUCCESS && e ) {
5367 /* See if a recognized password is hashed here */
5368 Attribute *a = attr_find( e->e_attrs,
5369 slap_schema.si_ad_userPassword );
5370 if ( a && a->a_vals[0].bv_val[0] == '{' &&
5371 lutil_passwd_scheme( a->a_vals[0].bv_val )) {
5372 doit = 1;
5373 }
5374 be_entry_release_r( &op2, e );
5375 }
5376
5377 if ( doit ) {
5378 rc = overlay_op_walk( op, rs, op_extended, on->on_info,
5379 on->on_next );
5380 if ( rc == LDAP_SUCCESS ) {
5381 req_pwdexop_s *qpw = &op->oq_pwdexop;
5382
5383 /* We don't care if it succeeds or not */
5384 pc_setpw( &op2, &qpw->rs_new, cm );
5385 }
5386 return rc;
5387 }
5388 }
5389 return SLAP_CB_CONTINUE;
5390 }
5391
5392 static int
pcache_entry_release(Operation * op,Entry * e,int rw)5393 pcache_entry_release( Operation *op, Entry *e, int rw )
5394 {
5395 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
5396 cache_manager *cm = on->on_bi.bi_private;
5397 BackendDB *db = op->o_bd;
5398 int rc;
5399
5400 op->o_bd = &cm->db;
5401 rc = be_entry_release_rw( op, e, rw );
5402 op->o_bd = db;
5403 return rc;
5404 }
5405
5406 #ifdef PCACHE_MONITOR
5407
5408 static int
pcache_monitor_update(Operation * op,SlapReply * rs,Entry * e,void * priv)5409 pcache_monitor_update(
5410 Operation *op,
5411 SlapReply *rs,
5412 Entry *e,
5413 void *priv )
5414 {
5415 cache_manager *cm = (cache_manager *) priv;
5416 query_manager *qm = cm->qm;
5417
5418 CachedQuery *qc;
5419 BerVarray vals = NULL;
5420
5421 attr_delete( &e->e_attrs, ad_cachedQueryURL );
5422 if ( ( SLAP_OPATTRS( rs->sr_attr_flags ) || ad_inlist( ad_cachedQueryURL, rs->sr_attrs ) )
5423 && qm->templates != NULL )
5424 {
5425 QueryTemplate *tm;
5426
5427 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
5428 for ( qc = tm->query; qc; qc = qc->next ) {
5429 struct berval bv;
5430
5431 if ( query2url( op, qc, &bv, 1 ) == 0 ) {
5432 ber_bvarray_add_x( &vals, &bv, op->o_tmpmemctx );
5433 }
5434 }
5435 }
5436
5437
5438 if ( vals != NULL ) {
5439 attr_merge_normalize( e, ad_cachedQueryURL, vals, NULL );
5440 ber_bvarray_free_x( vals, op->o_tmpmemctx );
5441 }
5442 }
5443
5444 {
5445 Attribute *a;
5446 char buf[ SLAP_TEXT_BUFLEN ];
5447 struct berval bv;
5448
5449 /* number of cached queries */
5450 a = attr_find( e->e_attrs, ad_numQueries );
5451 assert( a != NULL );
5452
5453 bv.bv_val = buf;
5454 bv.bv_len = snprintf( buf, sizeof( buf ), "%lu", cm->num_cached_queries );
5455
5456 if ( a->a_nvals != a->a_vals ) {
5457 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5458 }
5459 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5460
5461 /* number of cached entries */
5462 a = attr_find( e->e_attrs, ad_numEntries );
5463 assert( a != NULL );
5464
5465 bv.bv_val = buf;
5466 bv.bv_len = snprintf( buf, sizeof( buf ), "%d", cm->cur_entries );
5467
5468 if ( a->a_nvals != a->a_vals ) {
5469 ber_bvreplace( &a->a_nvals[ 0 ], &bv );
5470 }
5471 ber_bvreplace( &a->a_vals[ 0 ], &bv );
5472 }
5473
5474 return SLAP_CB_CONTINUE;
5475 }
5476
5477 static int
pcache_monitor_free(Entry * e,void ** priv)5478 pcache_monitor_free(
5479 Entry *e,
5480 void **priv )
5481 {
5482 struct berval values[ 2 ];
5483 Modification mod = { 0 };
5484
5485 const char *text;
5486 char textbuf[ SLAP_TEXT_BUFLEN ];
5487
5488 int rc;
5489
5490 /* NOTE: if slap_shutdown != 0, priv might have already been freed */
5491 *priv = NULL;
5492
5493 /* Remove objectClass */
5494 mod.sm_op = LDAP_MOD_DELETE;
5495 mod.sm_desc = slap_schema.si_ad_objectClass;
5496 mod.sm_values = values;
5497 mod.sm_numvals = 1;
5498 values[ 0 ] = oc_olmPCache->soc_cname;
5499 BER_BVZERO( &values[ 1 ] );
5500
5501 rc = modify_delete_values( e, &mod, 1, &text,
5502 textbuf, sizeof( textbuf ) );
5503 /* don't care too much about return code... */
5504
5505 /* remove attrs */
5506 mod.sm_values = NULL;
5507 mod.sm_desc = ad_cachedQueryURL;
5508 mod.sm_numvals = 0;
5509 rc = modify_delete_values( e, &mod, 1, &text,
5510 textbuf, sizeof( textbuf ) );
5511 /* don't care too much about return code... */
5512
5513 /* remove attrs */
5514 mod.sm_values = NULL;
5515 mod.sm_desc = ad_numQueries;
5516 mod.sm_numvals = 0;
5517 rc = modify_delete_values( e, &mod, 1, &text,
5518 textbuf, sizeof( textbuf ) );
5519 /* don't care too much about return code... */
5520
5521 /* remove attrs */
5522 mod.sm_values = NULL;
5523 mod.sm_desc = ad_numEntries;
5524 mod.sm_numvals = 0;
5525 rc = modify_delete_values( e, &mod, 1, &text,
5526 textbuf, sizeof( textbuf ) );
5527 /* don't care too much about return code... */
5528
5529 return SLAP_CB_CONTINUE;
5530 }
5531
5532 /*
5533 * call from within pcache_initialize()
5534 */
5535 static int
pcache_monitor_initialize(void)5536 pcache_monitor_initialize( void )
5537 {
5538 static int pcache_monitor_initialized = 0;
5539
5540 if ( backend_info( "monitor" ) == NULL ) {
5541 return -1;
5542 }
5543
5544 if ( pcache_monitor_initialized++ ) {
5545 return 0;
5546 }
5547
5548 return 0;
5549 }
5550
5551 static int
pcache_monitor_db_init(BackendDB * be)5552 pcache_monitor_db_init( BackendDB *be )
5553 {
5554 if ( pcache_monitor_initialize() == LDAP_SUCCESS ) {
5555 SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_MONITORING;
5556 }
5557
5558 return 0;
5559 }
5560
5561 static int
pcache_monitor_db_open(BackendDB * be)5562 pcache_monitor_db_open( BackendDB *be )
5563 {
5564 slap_overinst *on = (slap_overinst *)be->bd_info;
5565 cache_manager *cm = on->on_bi.bi_private;
5566 Attribute *a, *next;
5567 monitor_callback_t *cb = NULL;
5568 int rc = 0;
5569 BackendInfo *mi;
5570 monitor_extra_t *mbe;
5571
5572 if ( !SLAP_DBMONITORING( be ) ) {
5573 return 0;
5574 }
5575
5576 mi = backend_info( "monitor" );
5577 if ( !mi || !mi->bi_extra ) {
5578 SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
5579 return 0;
5580 }
5581 mbe = mi->bi_extra;
5582
5583 /* don't bother if monitor is not configured */
5584 if ( !mbe->is_configured() ) {
5585 static int warning = 0;
5586
5587 if ( warning++ == 0 ) {
5588 Debug( LDAP_DEBUG_CONFIG, "pcache_monitor_db_open: "
5589 "monitoring disabled; "
5590 "configure monitor database to enable\n" );
5591 }
5592
5593 return 0;
5594 }
5595
5596 /* alloc as many as required (plus 1 for objectClass) */
5597 a = attrs_alloc( 1 + 2 );
5598 if ( a == NULL ) {
5599 rc = 1;
5600 goto cleanup;
5601 }
5602
5603 a->a_desc = slap_schema.si_ad_objectClass;
5604 attr_valadd( a, &oc_olmPCache->soc_cname, NULL, 1 );
5605 next = a->a_next;
5606
5607 {
5608 struct berval bv = BER_BVC( "0" );
5609
5610 next->a_desc = ad_numQueries;
5611 attr_valadd( next, &bv, NULL, 1 );
5612 next = next->a_next;
5613
5614 next->a_desc = ad_numEntries;
5615 attr_valadd( next, &bv, NULL, 1 );
5616 next = next->a_next;
5617 }
5618
5619 cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
5620 cb->mc_update = pcache_monitor_update;
5621 cb->mc_free = pcache_monitor_free;
5622 cb->mc_private = (void *)cm;
5623
5624 /* make sure the database is registered; then add monitor attributes */
5625 BER_BVZERO( &cm->monitor_ndn );
5626 rc = mbe->register_overlay( be, on, &cm->monitor_ndn );
5627 if ( rc == 0 ) {
5628 rc = mbe->register_entry_attrs( &cm->monitor_ndn, a, cb,
5629 NULL, -1, NULL);
5630 }
5631
5632 cleanup:;
5633 if ( rc != 0 ) {
5634 if ( cb != NULL ) {
5635 ch_free( cb );
5636 cb = NULL;
5637 }
5638
5639 if ( a != NULL ) {
5640 attrs_free( a );
5641 a = NULL;
5642 }
5643 }
5644
5645 /* store for cleanup */
5646 cm->monitor_cb = (void *)cb;
5647
5648 /* we don't need to keep track of the attributes, because
5649 * mdb_monitor_free() takes care of everything */
5650 if ( a != NULL ) {
5651 attrs_free( a );
5652 }
5653
5654 return rc;
5655 }
5656
5657 static int
pcache_monitor_db_close(BackendDB * be)5658 pcache_monitor_db_close( BackendDB *be )
5659 {
5660 slap_overinst *on = (slap_overinst *)be->bd_info;
5661 cache_manager *cm = on->on_bi.bi_private;
5662
5663 if ( cm->monitor_cb != NULL ) {
5664 BackendInfo *mi = backend_info( "monitor" );
5665 monitor_extra_t *mbe;
5666
5667 if ( mi && mi->bi_extra ) {
5668 mbe = mi->bi_extra;
5669 mbe->unregister_entry_callback( &cm->monitor_ndn,
5670 (monitor_callback_t *)cm->monitor_cb,
5671 NULL, 0, NULL );
5672 }
5673 }
5674
5675 return 0;
5676 }
5677
5678 static int
pcache_monitor_db_destroy(BackendDB * be)5679 pcache_monitor_db_destroy( BackendDB *be )
5680 {
5681 return 0;
5682 }
5683
5684 #endif /* PCACHE_MONITOR */
5685
5686 static slap_overinst pcache;
5687
5688 static char *obsolete_names[] = {
5689 "proxycache",
5690 NULL
5691 };
5692
5693 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
5694 static
5695 #endif /* SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC */
5696 int
pcache_initialize()5697 pcache_initialize()
5698 {
5699 int i, code;
5700 struct berval debugbv = BER_BVC("pcache");
5701 ConfigArgs c;
5702 char *argv[ 4 ];
5703
5704 /* olcDatabaseDummy is defined in slapd, and Windows
5705 will not let us initialize a struct element with a data pointer
5706 from another library, so we have to initialize this element
5707 "by hand". */
5708 pcocs[1].co_table = olcDatabaseDummy;
5709
5710
5711 code = slap_loglevel_get( &debugbv, &pcache_debug );
5712 if ( code ) {
5713 return code;
5714 }
5715
5716 #ifdef PCACHE_CONTROL_PRIVDB
5717 code = register_supported_control( PCACHE_CONTROL_PRIVDB,
5718 SLAP_CTRL_BIND|SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, extops,
5719 parse_privdb_ctrl, &privDB_cid );
5720 if ( code != LDAP_SUCCESS ) {
5721 Debug( LDAP_DEBUG_ANY,
5722 "pcache_initialize: failed to register control %s (%d)\n",
5723 PCACHE_CONTROL_PRIVDB, code );
5724 return code;
5725 }
5726 #endif /* PCACHE_CONTROL_PRIVDB */
5727
5728 #ifdef PCACHE_EXOP_QUERY_DELETE
5729 code = load_extop2( (struct berval *)&pcache_exop_QUERY_DELETE,
5730 SLAP_EXOP_WRITES|SLAP_EXOP_HIDE, pcache_exop_query_delete,
5731 0 );
5732 if ( code != LDAP_SUCCESS ) {
5733 Debug( LDAP_DEBUG_ANY,
5734 "pcache_initialize: unable to register queryDelete exop: %d.\n",
5735 code );
5736 return code;
5737 }
5738 #endif /* PCACHE_EXOP_QUERY_DELETE */
5739
5740 argv[ 0 ] = "back-mdb monitor";
5741 c.argv = argv;
5742 c.argc = 3;
5743 c.fname = argv[0];
5744
5745 for ( i = 0; s_oid[ i ].name; i++ ) {
5746 c.lineno = i;
5747 argv[ 1 ] = s_oid[ i ].name;
5748 argv[ 2 ] = s_oid[ i ].oid;
5749
5750 if ( parse_oidm( &c, 0, NULL ) != 0 ) {
5751 Debug( LDAP_DEBUG_ANY, "pcache_initialize: "
5752 "unable to add objectIdentifier \"%s=%s\"\n",
5753 s_oid[ i ].name, s_oid[ i ].oid );
5754 return 1;
5755 }
5756 }
5757
5758 for ( i = 0; s_ad[i].desc != NULL; i++ ) {
5759 code = register_at( s_ad[i].desc, s_ad[i].adp, 0 );
5760 if ( code ) {
5761 Debug( LDAP_DEBUG_ANY,
5762 "pcache_initialize: register_at #%d failed\n", i );
5763 return code;
5764 }
5765 (*s_ad[i].adp)->ad_type->sat_flags |= SLAP_AT_HIDE;
5766 }
5767
5768 for ( i = 0; s_oc[i].desc != NULL; i++ ) {
5769 code = register_oc( s_oc[i].desc, s_oc[i].ocp, 0 );
5770 if ( code ) {
5771 Debug( LDAP_DEBUG_ANY,
5772 "pcache_initialize: register_oc #%d failed\n", i );
5773 return code;
5774 }
5775 (*s_oc[i].ocp)->soc_flags |= SLAP_OC_HIDE;
5776 }
5777
5778 pcache.on_bi.bi_type = "pcache";
5779 pcache.on_bi.bi_obsolete_names = obsolete_names;
5780 pcache.on_bi.bi_db_init = pcache_db_init;
5781 pcache.on_bi.bi_db_config = pcache_db_config;
5782 pcache.on_bi.bi_db_open = pcache_db_open;
5783 pcache.on_bi.bi_db_close = pcache_db_close;
5784 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
5785
5786 pcache.on_bi.bi_op_search = pcache_op_search;
5787 pcache.on_bi.bi_op_bind = pcache_op_bind;
5788 #ifdef PCACHE_CONTROL_PRIVDB
5789 pcache.on_bi.bi_op_compare = pcache_op_privdb;
5790 pcache.on_bi.bi_op_modrdn = pcache_op_privdb;
5791 pcache.on_bi.bi_op_modify = pcache_op_privdb;
5792 pcache.on_bi.bi_op_add = pcache_op_privdb;
5793 pcache.on_bi.bi_op_delete = pcache_op_privdb;
5794 #endif /* PCACHE_CONTROL_PRIVDB */
5795 pcache.on_bi.bi_extended = pcache_op_extended;
5796
5797 pcache.on_bi.bi_entry_release_rw = pcache_entry_release;
5798 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
5799
5800 pcache.on_bi.bi_cf_ocs = pcocs;
5801
5802 code = config_register_schema( pccfg, pcocs );
5803 if ( code ) return code;
5804
5805 return overlay_register( &pcache );
5806 }
5807
5808 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
init_module(int argc,char * argv[])5809 int init_module(int argc, char *argv[]) {
5810 return pcache_initialize();
5811 }
5812 #endif
5813
5814 #endif /* defined(SLAPD_OVER_PROXYCACHE) */
5815