sssvlv.c 36.8 KB
Newer Older
1
2
3
4
/* sssvlv.c - server side sort / virtual list view */
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
5
 * Copyright 2009-2021 The OpenLDAP Foundation.
6
7
8
9
10
11
12
13
14
15
16
17
18
 * Portions copyright 2009 Symas Corporation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */
/* ACKNOWLEDGEMENTS:
 * This work was initially developed by Howard Chu for inclusion in
19
20
 * OpenLDAP Software. Support for multiple sorts per connection added
 * by Raphael Ouazana.
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 */

#include "portable.h"

#ifdef SLAPD_OVER_SSSVLV

#include <stdio.h>

#include <ac/string.h>
#include <ac/ctype.h>

#include <avl.h>

#include "slap.h"
#include "lutil.h"
Howard Chu's avatar
Howard Chu committed
36
#include "config.h"
37

Howard Chu's avatar
Howard Chu committed
38
39
#include "../../../libraries/liblber/lber-int.h"	/* ber_rewind */

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* RFC2891: Server Side Sorting
 * RFC2696: Paged Results
 */
#ifndef LDAP_MATCHRULE_IDENTIFIER
#define LDAP_MATCHRULE_IDENTIFIER      0x80L
#define LDAP_REVERSEORDER_IDENTIFIER   0x81L
#define LDAP_ATTRTYPES_IDENTIFIER      0x80L
#endif

/* draft-ietf-ldapext-ldapv3-vlv-09.txt: Virtual List Views
 */
#ifndef LDAP_VLVBYINDEX_IDENTIFIER
#define LDAP_VLVBYINDEX_IDENTIFIER	   0xa0L
#define LDAP_VLVBYVALUE_IDENTIFIER     0x81L
#define LDAP_VLVCONTEXT_IDENTIFIER     0x04L

#define LDAP_VLV_SSS_MISSING	0x4C
#define LDAP_VLV_RANGE_ERROR	0x4D
#endif

#define SAFESTR(macro_str, macro_def) ((macro_str) ? (macro_str) : (macro_def))

Howard Chu's avatar
Howard Chu committed
62
#define SSSVLV_DEFAULT_MAX_KEYS	5
63
64
65
66
#define SSSVLV_DEFAULT_MAX_REQUEST_PER_CONN 5

#define NO_PS_COOKIE (PagedResultsCookie) -1
#define NO_VC_CONTEXT (unsigned long) -1
Howard Chu's avatar
Howard Chu committed
67

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
typedef struct vlv_ctrl {
	int vc_before;
	int vc_after;
	int	vc_offset;
	int vc_count;
	struct berval vc_value;
	unsigned long vc_context;
} vlv_ctrl;

typedef struct sort_key
{
	AttributeDescription	*sk_ad;
	MatchingRule			*sk_ordering;
	int						sk_direction;	/* 1=normal, -1=reverse */
} sort_key;

typedef struct sort_ctrl {
	int sc_nkeys;
Howard Chu's avatar
Howard Chu committed
86
	sort_key sc_keys[1];
87
88
89
90
91
92
} sort_ctrl;


typedef struct sort_node
{
	int sn_conn;
93
	int sn_session;
94
95
96
97
98
99
100
101
102
	struct berval sn_dn;
	struct berval *sn_vals;
} sort_node;

typedef struct sssvlv_info
{
	int svi_max;	/* max concurrent sorts */
	int svi_num;	/* current # sorts */
	int svi_max_keys;	/* max sort keys per request */
103
	int svi_max_percon; /* max concurrent sorts per con */
104
105
106
107
} sssvlv_info;

typedef struct sort_op
{
108
	TAvlnode *so_tree;
109
110
111
112
113
114
115
116
	sort_ctrl *so_ctrl;
	sssvlv_info *so_info;
	int so_paged;
	int so_page_size;
	int so_nentries;
	int so_vlv;
	int so_vlv_rc;
	int so_vlv_target;
117
	int so_session;
118
	unsigned long so_vcontext;
119
	int so_running;
120
121
122
} sort_op;

/* There is only one conn table for all overlay instances */
123
124
/* Each conn can handle one session by context */
static sort_op ***sort_conns;
125
static ldap_pvt_thread_mutex_t sort_conns_mutex;
126
static int ov_count;
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
static const char *debug_header = "sssvlv";

static int sss_cid;
static int vlv_cid;

/* RFC 2981 Section 2.2
 * If a sort key is a multi-valued attribute, and an entry happens to
 * have multiple values for that attribute and no other controls are
 * present that affect the sorting order, then the server SHOULD use the
 * least value (according to the ORDERING rule for that attribute).
 */
static struct berval* select_value(
	Attribute		*attr,
	sort_key			*key )
{
	struct berval* ber1, *ber2;
	MatchingRule *mr = key->sk_ordering;
144
145
	unsigned i;
	int cmp;
146
147
148
149
150
151
152
153
154
155
156
157

	ber1 = &(attr->a_nvals[0]);
	ber2 = ber1+1;
	for ( i = 1; i < attr->a_numvals; i++,ber2++ ) {
		mr->smr_match( &cmp, 0, mr->smr_syntax, mr, ber1, ber2 );
		if ( cmp > 0 ) {
			ber1 = ber2;
		}
	}

	Debug(LDAP_DEBUG_TRACE, "%s: value selected for compare: %s\n",
		debug_header,
158
		SAFESTR(ber1->bv_val, "<Empty>") );
159
160
161
162
163
164
165
166

	return ber1;
}

static int node_cmp( const void* val1, const void* val2 )
{
	sort_node *sn1 = (sort_node *)val1;
	sort_node *sn2 = (sort_node *)val2;
167
	sort_ctrl *sc;
168
169
	MatchingRule *mr;
	int i, cmp = 0;
170
171
172
173
	assert( sort_conns[sn1->sn_conn]
		&& sort_conns[sn1->sn_conn][sn1->sn_session]
		&& sort_conns[sn1->sn_conn][sn1->sn_session]->so_ctrl );
	sc = sort_conns[sn1->sn_conn][sn1->sn_session]->so_ctrl;
174
175
176
177
178
179
180
181
182
183
184
185
186

	for ( i=0; cmp == 0 && i<sc->sc_nkeys; i++ ) {
		if ( BER_BVISNULL( &sn1->sn_vals[i] )) {
			if ( BER_BVISNULL( &sn2->sn_vals[i] ))
				cmp = 0;
			else
				cmp = sc->sc_keys[i].sk_direction;
		} else if ( BER_BVISNULL( &sn2->sn_vals[i] )) {
			cmp = sc->sc_keys[i].sk_direction * -1;
		} else {
			mr = sc->sc_keys[i].sk_ordering;
			mr->smr_match( &cmp, 0, mr->smr_syntax, mr,
				&sn1->sn_vals[i], &sn2->sn_vals[i] );
Howard Chu's avatar
Howard Chu committed
187
188
			if ( cmp )
				cmp *= sc->sc_keys[i].sk_direction;
189
190
		}
	}
Howard Chu's avatar
Howard Chu committed
191
192
193
194
195
	return cmp;
}

static int node_insert( const void *val1, const void *val2 )
{
196
	/* Never return equal so that new entries are always inserted */
Howard Chu's avatar
Howard Chu committed
197
	return node_cmp( val1, val2 ) < 0 ? -1 : 1;
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
}

static int pack_vlv_response_control(
	Operation		*op,
	SlapReply		*rs,
	sort_op			*so,
	LDAPControl	**ctrlsp )
{
	LDAPControl			*ctrl;
	BerElementBuffer	berbuf;
	BerElement			*ber		= (BerElement *)&berbuf;
	struct berval		cookie, bv;
	int					rc;

	ber_init2( ber, NULL, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

Howard Chu's avatar
Howard Chu committed
215
	rc = ber_printf( ber, "{iie", so->so_vlv_target, so->so_nentries,
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
		so->so_vlv_rc );

	if ( rc != -1 && so->so_vcontext ) {
		cookie.bv_val = (char *)&so->so_vcontext;
		cookie.bv_len = sizeof(so->so_vcontext);
		rc = ber_printf( ber, "tO", LDAP_VLVCONTEXT_IDENTIFIER, &cookie );
	}

	if ( rc != -1 ) {
		rc = ber_printf( ber, "}" );
	}

	if ( rc != -1 ) {
		rc = ber_flatten2( ber, &bv, 0 );
	}

	if ( rc != -1 ) {
		ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
			bv.bv_len, op->o_tmpmemctx );
		ctrl->ldctl_oid			= LDAP_CONTROL_VLVRESPONSE;
		ctrl->ldctl_iscritical	= 0;
		ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
		ctrl->ldctl_value.bv_len = bv.bv_len;
		AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
		ctrlsp[0] = ctrl;
	} else {
		ctrlsp[0] = NULL;
		rs->sr_err = LDAP_OTHER;
	}

	ber_free_buf( ber );

	return rs->sr_err;
}

static int pack_pagedresult_response_control(
	Operation		*op,
	SlapReply		*rs,
	sort_op			*so,
	LDAPControl	**ctrlsp )
{
	LDAPControl			*ctrl;
	BerElementBuffer	berbuf;
	BerElement			*ber		= (BerElement *)&berbuf;
	PagedResultsCookie	resp_cookie;
	struct berval		cookie, bv;
	int					rc;

	ber_init2( ber, NULL, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	if ( so->so_nentries > 0 ) {
		resp_cookie		= ( PagedResultsCookie )so->so_tree;
		cookie.bv_len	= sizeof( PagedResultsCookie );
		cookie.bv_val	= (char *)&resp_cookie;
	} else {
		resp_cookie		= ( PagedResultsCookie )0;
		BER_BVZERO( &cookie );
	}

	op->o_conn->c_pagedresults_state.ps_cookie = resp_cookie;
	op->o_conn->c_pagedresults_state.ps_count
		= ((PagedResultsState *)op->o_pagedresults_state)->ps_count
		  + rs->sr_nentries;

	rc = ber_printf( ber, "{iO}", so->so_nentries, &cookie );
	if ( rc != -1 ) {
		rc = ber_flatten2( ber, &bv, 0 );
	}

	if ( rc != -1 ) {
		ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
			bv.bv_len, op->o_tmpmemctx );
		ctrl->ldctl_oid			= LDAP_CONTROL_PAGEDRESULTS;
		ctrl->ldctl_iscritical	= 0;
		ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
		ctrl->ldctl_value.bv_len = bv.bv_len;
		AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
		ctrlsp[0] = ctrl;
	} else {
		ctrlsp[0] = NULL;
		rs->sr_err = LDAP_OTHER;
	}

	ber_free_buf( ber );

	return rs->sr_err;
}

static int pack_sss_response_control(
	Operation		*op,
	SlapReply		*rs,
	LDAPControl	**ctrlsp )
{
	LDAPControl			*ctrl;
	BerElementBuffer	berbuf;
	BerElement			*ber		= (BerElement *)&berbuf;
	struct berval		bv;
	int					rc;

	ber_init2( ber, NULL, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	/* Pack error code */
	rc = ber_printf(ber, "{e}", rs->sr_err);

	if ( rc != -1)
		rc = ber_flatten2( ber, &bv, 0 );

	if ( rc != -1 ) {
		ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
			bv.bv_len, op->o_tmpmemctx );
		ctrl->ldctl_oid			= LDAP_CONTROL_SORTRESPONSE;
		ctrl->ldctl_iscritical	= 0;
		ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
		ctrl->ldctl_value.bv_len = bv.bv_len;
		AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
		ctrlsp[0] = ctrl;
	} else {
		ctrlsp[0] = NULL;
		rs->sr_err = LDAP_OTHER;
	}

	ber_free_buf( ber );

	return rs->sr_err;
}

344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/* Return the session id or -1 if unknown */
static int find_session_by_so(
	int svi_max_percon,
	int conn_id,
	sort_op *so )
{
	int sess_id;
	if (so == NULL) {
		return -1;
	}
	for (sess_id = 0; sess_id < svi_max_percon; sess_id++) {
		if ( sort_conns[conn_id] && sort_conns[conn_id][sess_id] == so )
			return sess_id;
	}
	return -1;
}

361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/* Return the session id or -1 if unknown */
static int find_session_by_context(
	int svi_max_percon,
	int conn_id,
	unsigned long vc_context,
	PagedResultsCookie ps_cookie )
{
	int sess_id;
	for(sess_id = 0; sess_id < svi_max_percon; sess_id++) {
		if( sort_conns[conn_id] && sort_conns[conn_id][sess_id] &&
		    ( sort_conns[conn_id][sess_id]->so_vcontext == vc_context || 
                      (PagedResultsCookie) sort_conns[conn_id][sess_id]->so_tree == ps_cookie ) )
			return sess_id;
	}
	return -1;
}

static int find_next_session(
	int svi_max_percon,
	int conn_id )
{
	int sess_id;
	assert(sort_conns[conn_id] != NULL);
	for(sess_id = 0; sess_id < svi_max_percon; sess_id++) {
		if(!sort_conns[conn_id][sess_id]) {
			return sess_id;
		}
	}
	if (sess_id >= svi_max_percon) {
		return -1;
	} else {
		return sess_id;
	}
}
	
396
397
static void free_sort_op( Connection *conn, sort_op *so )
{
398
	int sess_id;
399
		
400
	ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
401
	sess_id = find_session_by_so( so->so_info->svi_max_percon, conn->c_conn_idx, so );
402
403
404
405
	if ( sess_id > -1 ) {
	    sort_conns[conn->c_conn_idx][sess_id] = NULL;
	    so->so_info->svi_num--;
	}
406
	ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
	
	if ( sess_id > -1 ){
	    if ( so->so_tree ) {
		    if ( so->so_paged > SLAP_CONTROL_IGNORED ) {
			    TAvlnode *cur_node, *next_node;
			    cur_node = so->so_tree;
			    while ( cur_node ) {
				    next_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
				    ch_free( cur_node->avl_data );
				    ber_memfree( cur_node );

				    cur_node = next_node;
			    }
		    } else {
			    tavl_free( so->so_tree, ch_free );
		    }
		    so->so_tree = NULL;
	    }

	    ch_free( so );
	}
428
429
}

430
431
432
433
434
435
436
437
438
439
440
441
442
443
static void free_sort_ops( Connection *conn, sort_op **sos, int svi_max_percon )
{
	int sess_id;
	sort_op *so;

	for( sess_id = 0; sess_id < svi_max_percon ; sess_id++ ) {
		so = sort_conns[conn->c_conn_idx][sess_id];
		if ( so ) {
			free_sort_op( conn, so );
			sort_conns[conn->c_conn_idx][sess_id] = NULL;
		}
	}
}
	
Howard Chu's avatar
Howard Chu committed
444
static void send_list(
Howard Chu's avatar
Howard Chu committed
445
446
447
448
	Operation		*op,
	SlapReply		*rs,
	sort_op			*so)
{
449
	TAvlnode *cur_node, *tmp_node;
Howard Chu's avatar
Howard Chu committed
450
451
452
453
454
455
	vlv_ctrl *vc = op->o_controls[vlv_cid];
	int i, j, dir, rc;
	BackendDB *be;
	Entry *e;
	LDAPControl *ctrls[2];

456
457
	rs->sr_attrs = op->ors_attrs;

Howard Chu's avatar
Howard Chu committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
	/* FIXME: it may be better to just flatten the tree into
	 * an array before doing all of this...
	 */

	/* Are we just counting an offset? */
	if ( BER_BVISNULL( &vc->vc_value )) {
		if ( vc->vc_offset == vc->vc_count ) {
			/* wants the last entry in the list */
			cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
			so->so_vlv_target = so->so_nentries;
		} else if ( vc->vc_offset == 1 ) {
			/* wants the first entry in the list */
			cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
			so->so_vlv_target = 1;
		} else {
			int target;
			/* Just iterate to the right spot */
			if ( vc->vc_count && vc->vc_count != so->so_nentries ) {
				if ( vc->vc_offset > vc->vc_count )
					goto range_err;
				target = so->so_nentries * vc->vc_offset / vc->vc_count;
			} else {
				if ( vc->vc_offset > so->so_nentries ) {
range_err:
					so->so_vlv_rc = LDAP_VLV_RANGE_ERROR;
					pack_vlv_response_control( op, rs, so, ctrls );
					ctrls[1] = NULL;
					slap_add_ctrls( op, rs, ctrls );
					rs->sr_err = LDAP_VLV_ERROR;
					return;
				}
				target = vc->vc_offset;
			}
			so->so_vlv_target = target;
			/* Start at left and go right, or start at right and go left? */
			if ( target < so->so_nentries / 2 ) {
				cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
				dir = TAVL_DIR_RIGHT;
			} else {
				cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
				dir = TAVL_DIR_LEFT;
Howard Chu's avatar
Howard Chu committed
499
				target = so->so_nentries - target + 1;
Howard Chu's avatar
Howard Chu committed
500
			}
Howard Chu's avatar
Howard Chu committed
501
			for ( i=1; i<target; i++ )
Howard Chu's avatar
Howard Chu committed
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
				cur_node = tavl_next( cur_node, dir );
		}
	} else {
	/* we're looking for a specific value */
		sort_ctrl *sc = so->so_ctrl;
		MatchingRule *mr = sc->sc_keys[0].sk_ordering;
		sort_node *sn;
		struct berval bv;

		if ( mr->smr_normalize ) {
			rc = mr->smr_normalize( SLAP_MR_VALUE_OF_SYNTAX,
				mr->smr_syntax, mr, &vc->vc_value, &bv, op->o_tmpmemctx );
			if ( rc ) {
				so->so_vlv_rc = LDAP_INAPPROPRIATE_MATCHING;
				pack_vlv_response_control( op, rs, so, ctrls );
				ctrls[1] = NULL;
				slap_add_ctrls( op, rs, ctrls );
				rs->sr_err = LDAP_VLV_ERROR;
				return;
			}
		} else {
			bv = vc->vc_value;
		}

		sn = op->o_tmpalloc( sizeof(sort_node) +
			sc->sc_nkeys * sizeof(struct berval), op->o_tmpmemctx );
		sn->sn_vals = (struct berval *)(sn+1);
		sn->sn_conn = op->o_conn->c_conn_idx;
530
		sn->sn_session = find_session_by_so( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, so );
Howard Chu's avatar
Howard Chu committed
531
532
533
534
		sn->sn_vals[0] = bv;
		for (i=1; i<sc->sc_nkeys; i++) {
			BER_BVZERO( &sn->sn_vals[i] );
		}
Howard Chu's avatar
Howard Chu committed
535
536
		cur_node = tavl_find3( so->so_tree, sn, node_cmp, &j );
		/* didn't find >= match */
537
538
539
540
		if ( j > 0 ) {
			if ( cur_node )
				cur_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
		}
Howard Chu's avatar
Howard Chu committed
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
		op->o_tmpfree( sn, op->o_tmpmemctx );

		if ( !cur_node ) {
			so->so_vlv_target = so->so_nentries + 1;
		} else {
			sort_node *sn = so->so_tree->avl_data;
			/* start from the left or the right side? */
			mr->smr_match( &i, 0, mr->smr_syntax, mr, &bv, &sn->sn_vals[0] );
			if ( i > 0 ) {
				tmp_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
				dir = TAVL_DIR_LEFT;
			} else {
				tmp_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
				dir = TAVL_DIR_RIGHT;
			}
			for (i=0; tmp_node != cur_node;
				tmp_node = tavl_next( tmp_node, dir ), i++);
558
			so->so_vlv_target = (dir == TAVL_DIR_RIGHT) ? i+1 : so->so_nentries - i;
Howard Chu's avatar
Howard Chu committed
559
560
561
562
		}
		if ( bv.bv_val != vc->vc_value.bv_val )
			op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
	}
Howard Chu's avatar
Howard Chu committed
563
564
565
566
567
568
569
	if ( !cur_node ) {
		i = 1;
		cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
	} else {
		i = 0;
	}
	for ( ; i<vc->vc_before; i++ ) {
Howard Chu's avatar
Howard Chu committed
570
571
572
573
574
575
576
577
		tmp_node = tavl_next( cur_node, TAVL_DIR_LEFT );
		if ( !tmp_node ) break;
		cur_node = tmp_node;
	}
	j = i + vc->vc_after + 1;
	be = op->o_bd;
	for ( i=0; i<j; i++ ) {
		sort_node *sn = cur_node->avl_data;
578
579
580

		if ( slapd_shutdown ) break;

Howard Chu's avatar
Howard Chu committed
581
582
583
584
585
586
587
588
589
590
591
592
		op->o_bd = select_backend( &sn->sn_dn, 0 );
		e = NULL;
		rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );

		if ( e && rc == LDAP_SUCCESS ) {
			rs->sr_entry = e;
			rs->sr_flags = REP_ENTRY_MUSTRELEASE;
			rs->sr_err = send_search_entry( op, rs );
			if ( rs->sr_err == LDAP_UNAVAILABLE )
				break;
		}
		cur_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
Howard Chu's avatar
Howard Chu committed
593
		if ( !cur_node ) break;
Howard Chu's avatar
Howard Chu committed
594
	}
Howard Chu's avatar
Howard Chu committed
595
	so->so_vlv_rc = LDAP_SUCCESS;
Howard Chu's avatar
Howard Chu committed
596
597
598
599

	op->o_bd = be;
}

600
601
static void send_page( Operation *op, SlapReply *rs, sort_op *so )
{
602
603
	TAvlnode *cur_node = so->so_tree;
	TAvlnode *next_node = NULL;
604
605
606
607
	BackendDB *be = op->o_bd;
	Entry *e;
	int rc;

608
609
	rs->sr_attrs = op->ors_attrs;

610
611
612
	while ( cur_node && rs->sr_nentries < so->so_page_size ) {
		sort_node *sn = cur_node->avl_data;

613
614
		if ( slapd_shutdown ) break;

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
		next_node = tavl_next( cur_node, TAVL_DIR_RIGHT );

		op->o_bd = select_backend( &sn->sn_dn, 0 );
		e = NULL;
		rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );

		ch_free( cur_node->avl_data );
		ber_memfree( cur_node );

		cur_node = next_node;
		so->so_nentries--;

		if ( e && rc == LDAP_SUCCESS ) {
			rs->sr_entry = e;
			rs->sr_flags = REP_ENTRY_MUSTRELEASE;
			rs->sr_err = send_search_entry( op, rs );
			if ( rs->sr_err == LDAP_UNAVAILABLE )
				break;
		}
	}

	/* Set the first entry to send for the next page */
	so->so_tree = next_node;
638
639
	if ( next_node )
		next_node->avl_left = NULL;
640
641
642
643

	op->o_bd = be;
}

Howard Chu's avatar
Howard Chu committed
644
static void send_entry(
645
646
647
648
649
650
651
652
	Operation		*op,
	SlapReply		*rs,
	sort_op			*so)
{
	Debug(LDAP_DEBUG_TRACE,
		"%s: response control: status=%d, text=%s\n",
		debug_header, rs->sr_err, SAFESTR(rs->sr_text, "<None>"));

Howard Chu's avatar
Howard Chu committed
653
654
655
	if ( !so->so_tree )
		return;

656
	/* RFC 2891: If critical then send the entries iff they were
Josh Soref's avatar
Josh Soref committed
657
	 * successfully sorted.  If non-critical send all entries
658
659
660
661
662
	 * whether they were sorted or not.
	 */
	if ( (op->o_ctrlflag[sss_cid] != SLAP_CONTROL_CRITICAL) ||
		 (rs->sr_err == LDAP_SUCCESS) )
	{
Howard Chu's avatar
Howard Chu committed
663
664
665
666
		if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
			send_list( op, rs, so );
		} else {
			/* Get the first node to send */
667
			TAvlnode *start_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
Howard Chu's avatar
Howard Chu committed
668
669
670
671
672
673
674
675
676
			so->so_tree = start_node;

			if ( so->so_paged <= SLAP_CONTROL_IGNORED ) {
				/* Not paged result search.  Send all entries.
				 * Set the page size to the number of entries
				 * so that send_page() will send all entries.
				 */
				so->so_page_size = so->so_nentries;
			}
677

Howard Chu's avatar
Howard Chu committed
678
679
			send_page( op, rs, so );
		}
680
681
682
683
684
685
686
687
688
	}
}

static void send_result(
	Operation		*op,
	SlapReply		*rs,
	sort_op			*so)
{
	LDAPControl *ctrls[3];
Howard Chu's avatar
Howard Chu committed
689
	int rc, i = 0;
690
691

	rc = pack_sss_response_control( op, rs, ctrls );
Howard Chu's avatar
Howard Chu committed
692
	if ( rc == LDAP_SUCCESS ) {
Howard Chu's avatar
Howard Chu committed
693
694
		i++;
		rc = -1;
Howard Chu's avatar
Howard Chu committed
695
696
697
698
699
		if ( so->so_paged > SLAP_CONTROL_IGNORED ) {
			rc = pack_pagedresult_response_control( op, rs, so, ctrls+1 );
		} else if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
			rc = pack_vlv_response_control( op, rs, so, ctrls+1 );
		}
Howard Chu's avatar
Howard Chu committed
700
701
		if ( rc == LDAP_SUCCESS )
			i++;
702
	}
Howard Chu's avatar
Howard Chu committed
703
	ctrls[i] = NULL;
704
705
706
707
708
709
710
711

	if ( ctrls[0] != NULL )
		slap_add_ctrls( op, rs, ctrls );
	send_ldap_result( op, rs );

	if ( so->so_tree == NULL ) {
		/* Search finished, so clean up */
		free_sort_op( op->o_conn, so );
712
713
	} else {
	    so->so_running = 0;
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
	}
}

static int sssvlv_op_response(
	Operation	*op,
	SlapReply	*rs )
{
	sort_ctrl *sc = op->o_controls[sss_cid];
	sort_op *so = op->o_callback->sc_private;

	if ( rs->sr_type == REP_SEARCH ) {
		int i;
		size_t len;
		sort_node *sn, *sn2;
		struct berval *bv;
		char *ptr;

		len = sizeof(sort_node) + sc->sc_nkeys * sizeof(struct berval) +
			rs->sr_entry->e_nname.bv_len + 1;
		sn = op->o_tmpalloc( len, op->o_tmpmemctx );
		sn->sn_vals = (struct berval *)(sn+1);

		/* Build tmp list of key values */
		for ( i=0; i<sc->sc_nkeys; i++ ) {
			Attribute *a = attr_find( rs->sr_entry->e_attrs,
				sc->sc_keys[i].sk_ad );
			if ( a ) {
				if ( a->a_numvals > 1 ) {
					bv = select_value( a, &sc->sc_keys[i] );
				} else {
					bv = a->a_nvals;
				}
				sn->sn_vals[i] = *bv;
				len += bv->bv_len + 1;
			} else {
				BER_BVZERO( &sn->sn_vals[i] );
			}
		}

		/* Now dup into regular memory */
		sn2 = ch_malloc( len );
		sn2->sn_vals = (struct berval *)(sn2+1);
		AC_MEMCPY( sn2->sn_vals, sn->sn_vals,
				sc->sc_nkeys * sizeof(struct berval));

Howard Chu's avatar
Howard Chu committed
759
760
761
		ptr = (char *)(sn2->sn_vals + sc->sc_nkeys);
		sn2->sn_dn.bv_val = ptr;
		sn2->sn_dn.bv_len = rs->sr_entry->e_nname.bv_len;
762
763
764
765
766
		AC_MEMCPY( ptr, rs->sr_entry->e_nname.bv_val,
			rs->sr_entry->e_nname.bv_len );
		ptr += rs->sr_entry->e_nname.bv_len;
		*ptr++ = '\0';
		for ( i=0; i<sc->sc_nkeys; i++ ) {
Howard Chu's avatar
Howard Chu committed
767
768
769
770
			if ( !BER_BVISNULL( &sn2->sn_vals[i] )) {
				AC_MEMCPY(ptr, sn2->sn_vals[i].bv_val, sn2->sn_vals[i].bv_len);
				sn2->sn_vals[i].bv_val = ptr;
				ptr += sn2->sn_vals[i].bv_len;
771
772
773
				*ptr++ = '\0';
			}
		}
Howard Chu's avatar
Howard Chu committed
774
775
		op->o_tmpfree( sn, op->o_tmpmemctx );
		sn = sn2;
776
		sn->sn_conn = op->o_conn->c_conn_idx;
777
		sn->sn_session = find_session_by_so( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, so );
778
779

		/* Insert into the AVL tree */
Howard Chu's avatar
Howard Chu committed
780
		tavl_insert(&(so->so_tree), sn, node_insert, avl_dup_error);
781
782
783
784
785
786

		so->so_nentries++;

		/* Collected the keys so that they can be sorted.  Thus, stop
		 * the entry from propagating.
		 */
Howard Chu's avatar
Howard Chu committed
787
		rs->sr_err = LDAP_SUCCESS;
788
789
790
791
792
793
794
795
796
797
	}
	else if ( rs->sr_type == REP_RESULT ) {
		/* Remove serversort response callback.
		 * We don't want the entries that we are about to send to be
		 * processed by serversort response again.
		 */
		if ( op->o_callback->sc_response == sssvlv_op_response ) {
			op->o_callback = op->o_callback->sc_next;
		}

Howard Chu's avatar
Howard Chu committed
798
		send_entry( op, rs, so );
799
800
801
		send_result( op, rs, so );
	}

Howard Chu's avatar
Howard Chu committed
802
	return rs->sr_err;
803
804
805
806
807
808
809
810
811
812
}

static int sssvlv_op_search(
	Operation		*op,
	SlapReply		*rs)
{
	slap_overinst			*on			= (slap_overinst *)op->o_bd->bd_info;
	sssvlv_info				*si			= on->on_bi.bi_private;
	int						rc			= SLAP_CB_CONTINUE;
	int	ok;
813
	sort_op *so = NULL, so2;
814
	sort_ctrl *sc;
815
816
	PagedResultsState *ps;
	vlv_ctrl *vc;
817
	int sess_id;
818
819
820
821
822
823
824
825

	if ( op->o_ctrlflag[sss_cid] <= SLAP_CONTROL_IGNORED ) {
		if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
			LDAPControl *ctrls[2];
			so2.so_vcontext = 0;
			so2.so_vlv_target = 0;
			so2.so_nentries = 0;
			so2.so_vlv_rc = LDAP_VLV_SSS_MISSING;
826
			so2.so_vlv = op->o_ctrlflag[vlv_cid];
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
			rc = pack_vlv_response_control( op, rs, &so2, ctrls );
			if ( rc == LDAP_SUCCESS ) {
				ctrls[1] = NULL;
				slap_add_ctrls( op, rs, ctrls );
			}
			rs->sr_err = LDAP_VLV_ERROR;
			rs->sr_text = "Sort control is required with VLV";
			goto leave;
		}
		/* Not server side sort so just continue */
		return SLAP_CB_CONTINUE;
	}

	Debug(LDAP_DEBUG_TRACE,
		"==> sssvlv_search: <%s> %s, control flag: %d\n",
		op->o_req_dn.bv_val, op->ors_filterstr.bv_val,
		op->o_ctrlflag[sss_cid]);

845
	sc = op->o_controls[sss_cid];
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
	if ( sc->sc_nkeys > si->svi_max_keys ) {
		rs->sr_text = "Too many sort keys";
		rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
		goto leave;
	}

	ps = ( op->o_pagedresults > SLAP_CONTROL_IGNORED ) ?
		(PagedResultsState*)(op->o_pagedresults_state) : NULL;
	vc = op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ?
		op->o_controls[vlv_cid] : NULL;

	if ( ps && vc ) {
		rs->sr_text = "VLV incompatible with PagedResults";
		rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
		goto leave;
	}

	ok = 1;
	ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
	/* Is there already a sort running on this conn? */
866
867
868
	sess_id = find_session_by_context( si->svi_max_percon, op->o_conn->c_conn_idx, vc ? vc->vc_context : NO_VC_CONTEXT, ps ? ps->ps_cookie : NO_PS_COOKIE );
	if ( sess_id >= 0 ) {
		so = sort_conns[op->o_conn->c_conn_idx][sess_id];
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
		
		if( so->so_running > 0 ){
		    /* another thread is handling, response busy to client */
		    so = NULL;
		    ok = 0;
		} else {
		
		    /* Is it a continuation of a VLV search? */
		    if ( !vc || so->so_vlv <= SLAP_CONTROL_IGNORED ||
			    vc->vc_context != so->so_vcontext ) {
			    /* Is it a continuation of a paged search? */
			    if ( !ps || so->so_paged <= SLAP_CONTROL_IGNORED ||
				    op->o_conn->c_pagedresults_state.ps_cookie != ps->ps_cookie ) {
				    ok = 0;
			    } else if ( !ps->ps_size ) {
			    /* Abandoning current request */
				    ok = 0;
				    so->so_nentries = 0;
				    rs->sr_err = LDAP_SUCCESS;
			    }
		    }
		    if (( vc && so->so_paged > SLAP_CONTROL_IGNORED ) ||
			    ( ps && so->so_vlv > SLAP_CONTROL_IGNORED )) {
			    /* changed from paged to vlv or vice versa, abandon */
			    ok = 0;
			    so->so_nentries = 0;
			    rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
		    }

		    if ( ok ) {
			/* occupy before mutex unlock */
			so->so_running = 1;
		    }
		
Howard Chu's avatar
Howard Chu committed
903
		}
904
905
906
	/* Are there too many running overall? */
	} else if ( si->svi_num >= si->svi_max ) {
		ok = 0;
907
908
	} else if ( ( sess_id = find_next_session(si->svi_max_percon, op->o_conn->c_conn_idx ) ) < 0 ) {
		ok = 0;
909
910
911
	} else {
		/* OK, this connection now has a sort running */
		si->svi_num++;
912
913
		sort_conns[op->o_conn->c_conn_idx][sess_id] = &so2;
		sort_conns[op->o_conn->c_conn_idx][sess_id]->so_session = sess_id;
914
915
916
	}
	ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
	if ( ok ) {
917
918
919
		/* If we're a global overlay, this check got bypassed */
		if ( !op->ors_limit && limits_check( op, rs ))
			return rs->sr_err;
Howard Chu's avatar
Howard Chu committed
920
		/* are we continuing a VLV search? */
921
		if ( so && vc && vc->vc_context ) {
Howard Chu's avatar
Howard Chu committed
922
923
924
925
			so->so_ctrl = sc;
			send_list( op, rs, so );
			send_result( op, rs, so );
			rc = LDAP_SUCCESS;
926
		/* are we continuing a paged search? */
927
		} else if ( so && ps && ps->ps_cookie ) {
928
929
930
931
			so->so_ctrl = sc;
			send_page( op, rs, so );
			send_result( op, rs, so );
			rc = LDAP_SUCCESS;
Howard Chu's avatar
Howard Chu committed
932
		} else {
933
934
935
			slap_callback *cb = op->o_tmpalloc( sizeof(slap_callback),
				op->o_tmpmemctx );
			/* Install serversort response callback to handle a new search */
Howard Chu's avatar
Howard Chu committed
936
			if ( ps || vc ) {
937
				so = ch_calloc( 1, sizeof(sort_op));
938
			} else {
939
				so = op->o_tmpcalloc( 1, sizeof(sort_op), op->o_tmpmemctx );
940
			}
941
			sort_conns[op->o_conn->c_conn_idx][sess_id] = so;
942
943
944
945
946

			cb->sc_cleanup		= NULL;
			cb->sc_response		= sssvlv_op_response;
			cb->sc_next			= op->o_callback;
			cb->sc_private		= so;
947
			cb->sc_writewait	= NULL;
948
949
950
951
952
953
954
955
956
957
958

			so->so_tree = NULL;
			so->so_ctrl = sc;
			so->so_info = si;
			if ( ps ) {
				so->so_paged = op->o_pagedresults;
				so->so_page_size = ps->ps_size;
				op->o_pagedresults = SLAP_CONTROL_IGNORED;
			} else {
				so->so_paged = 0;
				so->so_page_size = 0;
Howard Chu's avatar
Howard Chu committed
959
				if ( vc ) {
Howard Chu's avatar
Howard Chu committed
960
					so->so_vlv = op->o_ctrlflag[vlv_cid];
Howard Chu's avatar
Howard Chu committed
961
962
					so->so_vlv_target = 0;
					so->so_vlv_rc = 0;
Howard Chu's avatar
Howard Chu committed
963
964
				} else {
					so->so_vlv = SLAP_CONTROL_NONE;
Howard Chu's avatar
Howard Chu committed
965
				}
966
			}
967
968
			so->so_session = sess_id;
			so->so_vlv = op->o_ctrlflag[vlv_cid];
Howard Chu's avatar
Howard Chu committed
969
			so->so_vcontext = (unsigned long)so;
970
			so->so_nentries = 0;
971
			so->so_running = 1;
972
973
974
975

			op->o_callback		= cb;
		}
	} else {
Howard Chu's avatar
Howard Chu committed
976
		if ( so && !so->so_nentries ) {
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
			free_sort_op( op->o_conn, so );
		} else {
			rs->sr_text = "Other sort requests already in progress";
			rs->sr_err = LDAP_BUSY;
		}
leave:
		rc = rs->sr_err;
		send_ldap_result( op, rs );
	}

	return rc;
}

static int get_ordering_rule(
	AttributeDescription	*ad,
	struct berval			*matchrule,
	SlapReply				*rs,
	MatchingRule			**ordering )
{
	MatchingRule* mr;

	if ( matchrule && matchrule->bv_val ) {
		mr = mr_find( matchrule->bv_val );
		if ( mr == NULL ) {
For faster browsing, not all history is shown. View entire blame