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