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