]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/sssvlv.c
ITS#6686
[openldap] / servers / slapd / overlays / sssvlv.c
1 /* sssvlv.c - server side sort / virtual list view */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2009-2010 The OpenLDAP Foundation.
6  * Portions copyright 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 Howard Chu for inclusion in
19  * OpenLDAP Software. Support for multiple sorts per connection added
20  * by Raphael Ouazana.
21  */
22
23 #include "portable.h"
24
25 #ifdef SLAPD_OVER_SSSVLV
26
27 #include <stdio.h>
28
29 #include <ac/string.h>
30 #include <ac/ctype.h>
31
32 #include <avl.h>
33
34 #include "slap.h"
35 #include "lutil.h"
36 #include "config.h"
37
38 #include "../../../libraries/liblber/lber-int.h"        /* ber_rewind */
39
40 /* RFC2891: Server Side Sorting
41  * RFC2696: Paged Results
42  */
43 #ifndef LDAP_MATCHRULE_IDENTIFIER
44 #define LDAP_MATCHRULE_IDENTIFIER      0x80L
45 #define LDAP_REVERSEORDER_IDENTIFIER   0x81L
46 #define LDAP_ATTRTYPES_IDENTIFIER      0x80L
47 #endif
48
49 /* draft-ietf-ldapext-ldapv3-vlv-09.txt: Virtual List Views
50  */
51 #ifndef LDAP_VLVBYINDEX_IDENTIFIER
52 #define LDAP_VLVBYINDEX_IDENTIFIER         0xa0L
53 #define LDAP_VLVBYVALUE_IDENTIFIER     0x81L
54 #define LDAP_VLVCONTEXT_IDENTIFIER     0x04L
55
56 #define LDAP_VLV_SSS_MISSING    0x4C
57 #define LDAP_VLV_RANGE_ERROR    0x4D
58 #endif
59
60 #define SAFESTR(macro_str, macro_def) ((macro_str) ? (macro_str) : (macro_def))
61
62 #define SSSVLV_DEFAULT_MAX_KEYS 5
63 #define SSSVLV_DEFAULT_MAX_REQUEST_PER_CONN 5
64
65 #define NO_PS_COOKIE (PagedResultsCookie) -1
66 #define NO_VC_CONTEXT (unsigned long) -1
67
68 typedef struct vlv_ctrl {
69         int vc_before;
70         int vc_after;
71         int     vc_offset;
72         int vc_count;
73         struct berval vc_value;
74         unsigned long vc_context;
75 } vlv_ctrl;
76
77 typedef struct sort_key
78 {
79         AttributeDescription    *sk_ad;
80         MatchingRule                    *sk_ordering;
81         int                                             sk_direction;   /* 1=normal, -1=reverse */
82 } sort_key;
83
84 typedef struct sort_ctrl {
85         int sc_nkeys;
86         sort_key sc_keys[1];
87 } sort_ctrl;
88
89
90 typedef struct sort_node
91 {
92         int sn_conn;
93         int sn_session;
94         struct berval sn_dn;
95         struct berval *sn_vals;
96 } sort_node;
97
98 typedef struct sssvlv_info
99 {
100         int svi_max;    /* max concurrent sorts */
101         int svi_num;    /* current # sorts */
102         int svi_max_keys;       /* max sort keys per request */
103         int svi_max_percon; /* max concurrent sorts per con */
104 } sssvlv_info;
105
106 typedef struct sort_op
107 {
108         Avlnode *so_tree;
109         sort_ctrl *so_ctrl;
110         sssvlv_info *so_info;
111         int so_paged;
112         int so_page_size;
113         int so_nentries;
114         int so_vlv;
115         int so_vlv_rc;
116         int so_vlv_target;
117         int so_session;
118         unsigned long so_vcontext;
119 } sort_op;
120
121 /* There is only one conn table for all overlay instances */
122 /* Each conn can handle one session by context */
123 static sort_op ***sort_conns;
124 static ldap_pvt_thread_mutex_t sort_conns_mutex;
125 static int ov_count;
126 static const char *debug_header = "sssvlv";
127
128 static int sss_cid;
129 static int vlv_cid;
130
131 /* RFC 2981 Section 2.2
132  * If a sort key is a multi-valued attribute, and an entry happens to
133  * have multiple values for that attribute and no other controls are
134  * present that affect the sorting order, then the server SHOULD use the
135  * least value (according to the ORDERING rule for that attribute).
136  */
137 static struct berval* select_value(
138         Attribute               *attr,
139         sort_key                        *key )
140 {
141         struct berval* ber1, *ber2;
142         MatchingRule *mr = key->sk_ordering;
143         unsigned i;
144         int cmp;
145
146         ber1 = &(attr->a_nvals[0]);
147         ber2 = ber1+1;
148         for ( i = 1; i < attr->a_numvals; i++,ber2++ ) {
149                 mr->smr_match( &cmp, 0, mr->smr_syntax, mr, ber1, ber2 );
150                 if ( cmp > 0 ) {
151                         ber1 = ber2;
152                 }
153         }
154
155         Debug(LDAP_DEBUG_TRACE, "%s: value selected for compare: %s\n",
156                 debug_header,
157                 SAFESTR(ber1->bv_val, "<Empty>"),
158                 0);
159
160         return ber1;
161 }
162
163 static int node_cmp( const void* val1, const void* val2 )
164 {
165         sort_node *sn1 = (sort_node *)val1;
166         sort_node *sn2 = (sort_node *)val2;
167         assert( sort_conns[sn1->sn_conn] && sort_conns[sn1->sn_conn][sn1->sn_session]
168                 && sort_conns[sn1->sn_conn][sn1->sn_session]->so_ctrl );
169         sort_ctrl *sc = sort_conns[sn1->sn_conn][sn1->sn_session]->so_ctrl;
170         MatchingRule *mr;
171         int i, cmp = 0;
172
173         for ( i=0; cmp == 0 && i<sc->sc_nkeys; i++ ) {
174                 if ( BER_BVISNULL( &sn1->sn_vals[i] )) {
175                         if ( BER_BVISNULL( &sn2->sn_vals[i] ))
176                                 cmp = 0;
177                         else
178                                 cmp = sc->sc_keys[i].sk_direction;
179                 } else if ( BER_BVISNULL( &sn2->sn_vals[i] )) {
180                         cmp = sc->sc_keys[i].sk_direction * -1;
181                 } else {
182                         mr = sc->sc_keys[i].sk_ordering;
183                         mr->smr_match( &cmp, 0, mr->smr_syntax, mr,
184                                 &sn1->sn_vals[i], &sn2->sn_vals[i] );
185                         if ( cmp )
186                                 cmp *= sc->sc_keys[i].sk_direction;
187                 }
188         }
189         return cmp;
190 }
191
192 static int node_insert( const void *val1, const void *val2 )
193 {
194         /* Never return equal so that new entries are always inserted */
195         return node_cmp( val1, val2 ) < 0 ? -1 : 1;
196 }
197
198 static int pack_vlv_response_control(
199         Operation               *op,
200         SlapReply               *rs,
201         sort_op                 *so,
202         LDAPControl     **ctrlsp )
203 {
204         LDAPControl                     *ctrl;
205         BerElementBuffer        berbuf;
206         BerElement                      *ber            = (BerElement *)&berbuf;
207         struct berval           cookie, bv;
208         int                                     rc;
209
210         ber_init2( ber, NULL, LBER_USE_DER );
211         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
212
213         rc = ber_printf( ber, "{iie", so->so_vlv_target, so->so_nentries,
214                 so->so_vlv_rc );
215
216         if ( rc != -1 && so->so_vcontext ) {
217                 cookie.bv_val = (char *)&so->so_vcontext;
218                 cookie.bv_len = sizeof(so->so_vcontext);
219                 rc = ber_printf( ber, "tO", LDAP_VLVCONTEXT_IDENTIFIER, &cookie );
220         }
221
222         if ( rc != -1 ) {
223                 rc = ber_printf( ber, "}" );
224         }
225
226         if ( rc != -1 ) {
227                 rc = ber_flatten2( ber, &bv, 0 );
228         }
229
230         if ( rc != -1 ) {
231                 ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
232                         bv.bv_len, op->o_tmpmemctx );
233                 ctrl->ldctl_oid                 = LDAP_CONTROL_VLVRESPONSE;
234                 ctrl->ldctl_iscritical  = 0;
235                 ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
236                 ctrl->ldctl_value.bv_len = bv.bv_len;
237                 AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
238                 ctrlsp[0] = ctrl;
239         } else {
240                 ctrlsp[0] = NULL;
241                 rs->sr_err = LDAP_OTHER;
242         }
243
244         ber_free_buf( ber );
245
246         return rs->sr_err;
247 }
248
249 static int pack_pagedresult_response_control(
250         Operation               *op,
251         SlapReply               *rs,
252         sort_op                 *so,
253         LDAPControl     **ctrlsp )
254 {
255         LDAPControl                     *ctrl;
256         BerElementBuffer        berbuf;
257         BerElement                      *ber            = (BerElement *)&berbuf;
258         PagedResultsCookie      resp_cookie;
259         struct berval           cookie, bv;
260         int                                     rc;
261
262         ber_init2( ber, NULL, LBER_USE_DER );
263         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
264
265         if ( so->so_nentries > 0 ) {
266                 resp_cookie             = ( PagedResultsCookie )so->so_tree;
267                 cookie.bv_len   = sizeof( PagedResultsCookie );
268                 cookie.bv_val   = (char *)&resp_cookie;
269         } else {
270                 resp_cookie             = ( PagedResultsCookie )0;
271                 BER_BVZERO( &cookie );
272         }
273
274         op->o_conn->c_pagedresults_state.ps_cookie = resp_cookie;
275         op->o_conn->c_pagedresults_state.ps_count
276                 = ((PagedResultsState *)op->o_pagedresults_state)->ps_count
277                   + rs->sr_nentries;
278
279         rc = ber_printf( ber, "{iO}", so->so_nentries, &cookie );
280         if ( rc != -1 ) {
281                 rc = ber_flatten2( ber, &bv, 0 );
282         }
283
284         if ( rc != -1 ) {
285                 ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
286                         bv.bv_len, op->o_tmpmemctx );
287                 ctrl->ldctl_oid                 = LDAP_CONTROL_PAGEDRESULTS;
288                 ctrl->ldctl_iscritical  = 0;
289                 ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
290                 ctrl->ldctl_value.bv_len = bv.bv_len;
291                 AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
292                 ctrlsp[0] = ctrl;
293         } else {
294                 ctrlsp[0] = NULL;
295                 rs->sr_err = LDAP_OTHER;
296         }
297
298         ber_free_buf( ber );
299
300         return rs->sr_err;
301 }
302
303 static int pack_sss_response_control(
304         Operation               *op,
305         SlapReply               *rs,
306         LDAPControl     **ctrlsp )
307 {
308         LDAPControl                     *ctrl;
309         BerElementBuffer        berbuf;
310         BerElement                      *ber            = (BerElement *)&berbuf;
311         struct berval           bv;
312         int                                     rc;
313
314         ber_init2( ber, NULL, LBER_USE_DER );
315         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
316
317         /* Pack error code */
318         rc = ber_printf(ber, "{e}", rs->sr_err);
319
320         if ( rc != -1)
321                 rc = ber_flatten2( ber, &bv, 0 );
322
323         if ( rc != -1 ) {
324                 ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
325                         bv.bv_len, op->o_tmpmemctx );
326                 ctrl->ldctl_oid                 = LDAP_CONTROL_SORTRESPONSE;
327                 ctrl->ldctl_iscritical  = 0;
328                 ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
329                 ctrl->ldctl_value.bv_len = bv.bv_len;
330                 AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
331                 ctrlsp[0] = ctrl;
332         } else {
333                 ctrlsp[0] = NULL;
334                 rs->sr_err = LDAP_OTHER;
335         }
336
337         ber_free_buf( ber );
338
339         return rs->sr_err;
340 }
341
342 /* Return the session id or -1 if unknown */
343 static int find_session_by_context(
344         int svi_max_percon,
345         int conn_id,
346         unsigned long vc_context,
347         PagedResultsCookie ps_cookie )
348 {
349         int sess_id;
350         for(sess_id = 0; sess_id < svi_max_percon; sess_id++) {
351                 if( sort_conns[conn_id] && sort_conns[conn_id][sess_id] &&
352                     ( sort_conns[conn_id][sess_id]->so_vcontext == vc_context || 
353                       (PagedResultsCookie) sort_conns[conn_id][sess_id]->so_tree == ps_cookie ) )
354                         return sess_id;
355         }
356         return -1;
357 }
358
359 static int find_next_session(
360         int svi_max_percon,
361         int conn_id )
362 {
363         int sess_id;
364         assert(sort_conns[conn_id] != NULL);
365         for(sess_id = 0; sess_id < svi_max_percon; sess_id++) {
366                 if(!sort_conns[conn_id][sess_id]) {
367                         return sess_id;
368                 }
369         }
370         if (sess_id >= svi_max_percon) {
371                 return -1;
372         } else {
373                 return sess_id;
374         }
375 }
376         
377 static void free_sort_op( Connection *conn, sort_op *so )
378 {
379         int sess_id;
380         PagedResultsCookie ps_cookie = (PagedResultsCookie) so->so_tree;
381         if ( so->so_tree ) {
382                 tavl_free( so->so_tree, ch_free );
383                 so->so_tree = NULL;
384         }
385
386         ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
387         sess_id = find_session_by_context( so->so_info->svi_max_percon, conn->c_conn_idx, so->so_vcontext, ps_cookie );
388         sort_conns[conn->c_conn_idx][sess_id] = NULL;
389         so->so_info->svi_num--;
390         ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
391
392         ch_free( so );
393 }
394
395 static void free_sort_ops( Connection *conn, sort_op **sos, int svi_max_percon )
396 {
397         int sess_id;
398         sort_op *so;
399
400         for( sess_id = 0; sess_id < svi_max_percon ; sess_id++ ) {
401                 so = sort_conns[conn->c_conn_idx][sess_id];
402                 if ( so ) {
403                         free_sort_op( conn, so );
404                         sort_conns[conn->c_conn_idx][sess_id] = NULL;
405                 }
406         }
407 }
408         
409 static void send_list(
410         Operation               *op,
411         SlapReply               *rs,
412         sort_op                 *so)
413 {
414         Avlnode *cur_node, *tmp_node;
415         vlv_ctrl *vc = op->o_controls[vlv_cid];
416         int i, j, dir, rc;
417         BackendDB *be;
418         Entry *e;
419         LDAPControl *ctrls[2];
420
421         /* FIXME: it may be better to just flatten the tree into
422          * an array before doing all of this...
423          */
424
425         /* Are we just counting an offset? */
426         if ( BER_BVISNULL( &vc->vc_value )) {
427                 if ( vc->vc_offset == vc->vc_count ) {
428                         /* wants the last entry in the list */
429                         cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
430                         so->so_vlv_target = so->so_nentries;
431                 } else if ( vc->vc_offset == 1 ) {
432                         /* wants the first entry in the list */
433                         cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
434                         so->so_vlv_target = 1;
435                 } else {
436                         int target;
437                         /* Just iterate to the right spot */
438                         if ( vc->vc_count && vc->vc_count != so->so_nentries ) {
439                                 if ( vc->vc_offset > vc->vc_count )
440                                         goto range_err;
441                                 target = so->so_nentries * vc->vc_offset / vc->vc_count;
442                         } else {
443                                 if ( vc->vc_offset > so->so_nentries ) {
444 range_err:
445                                         so->so_vlv_rc = LDAP_VLV_RANGE_ERROR;
446                                         pack_vlv_response_control( op, rs, so, ctrls );
447                                         ctrls[1] = NULL;
448                                         slap_add_ctrls( op, rs, ctrls );
449                                         rs->sr_err = LDAP_VLV_ERROR;
450                                         return;
451                                 }
452                                 target = vc->vc_offset;
453                         }
454                         so->so_vlv_target = target;
455                         /* Start at left and go right, or start at right and go left? */
456                         if ( target < so->so_nentries / 2 ) {
457                                 cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
458                                 dir = TAVL_DIR_RIGHT;
459                         } else {
460                                 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
461                                 dir = TAVL_DIR_LEFT;
462                                 target = so->so_nentries - target + 1;
463                         }
464                         for ( i=1; i<target; i++ )
465                                 cur_node = tavl_next( cur_node, dir );
466                 }
467         } else {
468         /* we're looking for a specific value */
469                 sort_ctrl *sc = so->so_ctrl;
470                 MatchingRule *mr = sc->sc_keys[0].sk_ordering;
471                 sort_node *sn;
472                 struct berval bv;
473
474                 if ( mr->smr_normalize ) {
475                         rc = mr->smr_normalize( SLAP_MR_VALUE_OF_SYNTAX,
476                                 mr->smr_syntax, mr, &vc->vc_value, &bv, op->o_tmpmemctx );
477                         if ( rc ) {
478                                 so->so_vlv_rc = LDAP_INAPPROPRIATE_MATCHING;
479                                 pack_vlv_response_control( op, rs, so, ctrls );
480                                 ctrls[1] = NULL;
481                                 slap_add_ctrls( op, rs, ctrls );
482                                 rs->sr_err = LDAP_VLV_ERROR;
483                                 return;
484                         }
485                 } else {
486                         bv = vc->vc_value;
487                 }
488
489                 sn = op->o_tmpalloc( sizeof(sort_node) +
490                         sc->sc_nkeys * sizeof(struct berval), op->o_tmpmemctx );
491                 sn->sn_vals = (struct berval *)(sn+1);
492                 sn->sn_conn = op->o_conn->c_conn_idx;
493                 sn->sn_session = find_session_by_context( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, vc->vc_context, NO_PS_COOKIE );
494                 sn->sn_vals[0] = bv;
495                 for (i=1; i<sc->sc_nkeys; i++) {
496                         BER_BVZERO( &sn->sn_vals[i] );
497                 }
498                 cur_node = tavl_find3( so->so_tree, sn, node_cmp, &j );
499                 /* didn't find >= match */
500                 if ( j > 0 )
501                         cur_node = NULL;
502                 op->o_tmpfree( sn, op->o_tmpmemctx );
503
504                 if ( !cur_node ) {
505                         so->so_vlv_target = so->so_nentries + 1;
506                 } else {
507                         sort_node *sn = so->so_tree->avl_data;
508                         /* start from the left or the right side? */
509                         mr->smr_match( &i, 0, mr->smr_syntax, mr, &bv, &sn->sn_vals[0] );
510                         if ( i > 0 ) {
511                                 tmp_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
512                                 dir = TAVL_DIR_LEFT;
513                         } else {
514                                 tmp_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
515                                 dir = TAVL_DIR_RIGHT;
516                         }
517                         for (i=0; tmp_node != cur_node;
518                                 tmp_node = tavl_next( tmp_node, dir ), i++);
519                         so->so_vlv_target = i;
520                 }
521                 if ( bv.bv_val != vc->vc_value.bv_val )
522                         op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
523         }
524         if ( !cur_node ) {
525                 i = 1;
526                 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
527         } else {
528                 i = 0;
529         }
530         for ( ; i<vc->vc_before; i++ ) {
531                 tmp_node = tavl_next( cur_node, TAVL_DIR_LEFT );
532                 if ( !tmp_node ) break;
533                 cur_node = tmp_node;
534         }
535         j = i + vc->vc_after + 1;
536         be = op->o_bd;
537         for ( i=0; i<j; i++ ) {
538                 sort_node *sn = cur_node->avl_data;
539
540                 if ( slapd_shutdown ) break;
541
542                 op->o_bd = select_backend( &sn->sn_dn, 0 );
543                 e = NULL;
544                 rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );
545
546                 if ( e && rc == LDAP_SUCCESS ) {
547                         rs->sr_entry = e;
548                         rs->sr_flags = REP_ENTRY_MUSTRELEASE;
549                         rs->sr_err = send_search_entry( op, rs );
550                         if ( rs->sr_err == LDAP_UNAVAILABLE )
551                                 break;
552                 }
553                 cur_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
554                 if ( !cur_node ) break;
555         }
556         so->so_vlv_rc = LDAP_SUCCESS;
557
558         op->o_bd = be;
559 }
560
561 static void send_page( Operation *op, SlapReply *rs, sort_op *so )
562 {
563         Avlnode         *cur_node               = so->so_tree;
564         Avlnode         *next_node              = NULL;
565         BackendDB *be = op->o_bd;
566         Entry *e;
567         int rc;
568
569         while ( cur_node && rs->sr_nentries < so->so_page_size ) {
570                 sort_node *sn = cur_node->avl_data;
571
572                 if ( slapd_shutdown ) break;
573
574                 next_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
575
576                 op->o_bd = select_backend( &sn->sn_dn, 0 );
577                 e = NULL;
578                 rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );
579
580                 ch_free( cur_node->avl_data );
581                 ber_memfree( cur_node );
582
583                 cur_node = next_node;
584                 so->so_nentries--;
585
586                 if ( e && rc == LDAP_SUCCESS ) {
587                         rs->sr_entry = e;
588                         rs->sr_flags = REP_ENTRY_MUSTRELEASE;
589                         rs->sr_err = send_search_entry( op, rs );
590                         if ( rs->sr_err == LDAP_UNAVAILABLE )
591                                 break;
592                 }
593         }
594
595         /* Set the first entry to send for the next page */
596         so->so_tree = next_node;
597
598         op->o_bd = be;
599 }
600
601 static void send_entry(
602         Operation               *op,
603         SlapReply               *rs,
604         sort_op                 *so)
605 {
606         Debug(LDAP_DEBUG_TRACE,
607                 "%s: response control: status=%d, text=%s\n",
608                 debug_header, rs->sr_err, SAFESTR(rs->sr_text, "<None>"));
609
610         if ( !so->so_tree )
611                 return;
612
613         /* RFC 2891: If critical then send the entries iff they were
614          * succesfully sorted.  If non-critical send all entries
615          * whether they were sorted or not.
616          */
617         if ( (op->o_ctrlflag[sss_cid] != SLAP_CONTROL_CRITICAL) ||
618                  (rs->sr_err == LDAP_SUCCESS) )
619         {
620                 if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
621                         send_list( op, rs, so );
622                 } else {
623                         /* Get the first node to send */
624                         Avlnode *start_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
625                         so->so_tree = start_node;
626
627                         if ( so->so_paged <= SLAP_CONTROL_IGNORED ) {
628                                 /* Not paged result search.  Send all entries.
629                                  * Set the page size to the number of entries
630                                  * so that send_page() will send all entries.
631                                  */
632                                 so->so_page_size = so->so_nentries;
633                         }
634
635                         send_page( op, rs, so );
636                 }
637         }
638 }
639
640 static void send_result(
641         Operation               *op,
642         SlapReply               *rs,
643         sort_op                 *so)
644 {
645         LDAPControl *ctrls[3];
646         int rc, i = 0;
647
648         rc = pack_sss_response_control( op, rs, ctrls );
649         if ( rc == LDAP_SUCCESS ) {
650                 i++;
651                 rc = -1;
652                 if ( so->so_paged > SLAP_CONTROL_IGNORED ) {
653                         rc = pack_pagedresult_response_control( op, rs, so, ctrls+1 );
654                 } else if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
655                         rc = pack_vlv_response_control( op, rs, so, ctrls+1 );
656                 }
657                 if ( rc == LDAP_SUCCESS )
658                         i++;
659         }
660         ctrls[i] = NULL;
661
662         if ( ctrls[0] != NULL )
663                 slap_add_ctrls( op, rs, ctrls );
664         send_ldap_result( op, rs );
665
666         if ( so->so_tree == NULL ) {
667                 /* Search finished, so clean up */
668                 free_sort_op( op->o_conn, so );
669         }
670 }
671
672 static int sssvlv_op_response(
673         Operation       *op,
674         SlapReply       *rs )
675 {
676         sort_ctrl *sc = op->o_controls[sss_cid];
677         sort_op *so = op->o_callback->sc_private;
678
679         if ( rs->sr_type == REP_SEARCH ) {
680                 int i;
681                 size_t len;
682                 sort_node *sn, *sn2;
683                 struct berval *bv;
684                 char *ptr;
685
686                 len = sizeof(sort_node) + sc->sc_nkeys * sizeof(struct berval) +
687                         rs->sr_entry->e_nname.bv_len + 1;
688                 sn = op->o_tmpalloc( len, op->o_tmpmemctx );
689                 sn->sn_vals = (struct berval *)(sn+1);
690
691                 /* Build tmp list of key values */
692                 for ( i=0; i<sc->sc_nkeys; i++ ) {
693                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
694                                 sc->sc_keys[i].sk_ad );
695                         if ( a ) {
696                                 if ( a->a_numvals > 1 ) {
697                                         bv = select_value( a, &sc->sc_keys[i] );
698                                 } else {
699                                         bv = a->a_nvals;
700                                 }
701                                 sn->sn_vals[i] = *bv;
702                                 len += bv->bv_len + 1;
703                         } else {
704                                 BER_BVZERO( &sn->sn_vals[i] );
705                         }
706                 }
707
708                 /* Now dup into regular memory */
709                 sn2 = ch_malloc( len );
710                 sn2->sn_vals = (struct berval *)(sn2+1);
711                 AC_MEMCPY( sn2->sn_vals, sn->sn_vals,
712                                 sc->sc_nkeys * sizeof(struct berval));
713
714                 ptr = (char *)(sn2->sn_vals + sc->sc_nkeys);
715                 sn2->sn_dn.bv_val = ptr;
716                 sn2->sn_dn.bv_len = rs->sr_entry->e_nname.bv_len;
717                 AC_MEMCPY( ptr, rs->sr_entry->e_nname.bv_val,
718                         rs->sr_entry->e_nname.bv_len );
719                 ptr += rs->sr_entry->e_nname.bv_len;
720                 *ptr++ = '\0';
721                 for ( i=0; i<sc->sc_nkeys; i++ ) {
722                         if ( !BER_BVISNULL( &sn2->sn_vals[i] )) {
723                                 AC_MEMCPY(ptr, sn2->sn_vals[i].bv_val, sn2->sn_vals[i].bv_len);
724                                 sn2->sn_vals[i].bv_val = ptr;
725                                 ptr += sn2->sn_vals[i].bv_len;
726                                 *ptr++ = '\0';
727                         }
728                 }
729                 op->o_tmpfree( sn, op->o_tmpmemctx );
730                 sn = sn2;
731                 sn->sn_conn = op->o_conn->c_conn_idx;
732                 sn->sn_session = find_session_by_context( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, so->so_vcontext, (PagedResultsCookie) so->so_tree );
733
734                 /* Insert into the AVL tree */
735                 tavl_insert(&(so->so_tree), sn, node_insert, avl_dup_error);
736
737                 so->so_nentries++;
738
739                 /* Collected the keys so that they can be sorted.  Thus, stop
740                  * the entry from propagating.
741                  */
742                 rs->sr_err = LDAP_SUCCESS;
743         }
744         else if ( rs->sr_type == REP_RESULT ) {
745                 /* Remove serversort response callback.
746                  * We don't want the entries that we are about to send to be
747                  * processed by serversort response again.
748                  */
749                 if ( op->o_callback->sc_response == sssvlv_op_response ) {
750                         op->o_callback = op->o_callback->sc_next;
751                 }
752
753                 send_entry( op, rs, so );
754                 send_result( op, rs, so );
755         }
756
757         return rs->sr_err;
758 }
759
760 static int sssvlv_op_search(
761         Operation               *op,
762         SlapReply               *rs)
763 {
764         slap_overinst                   *on                     = (slap_overinst *)op->o_bd->bd_info;
765         sssvlv_info                             *si                     = on->on_bi.bi_private;
766         int                                             rc                      = SLAP_CB_CONTINUE;
767         int     ok;
768         sort_op *so = NULL, so2;
769         sort_ctrl *sc;
770         PagedResultsState *ps;
771         vlv_ctrl *vc;
772         int sess_id;
773
774         if ( op->o_ctrlflag[sss_cid] <= SLAP_CONTROL_IGNORED ) {
775                 if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
776                         LDAPControl *ctrls[2];
777                         so2.so_vcontext = 0;
778                         so2.so_vlv_target = 0;
779                         so2.so_nentries = 0;
780                         so2.so_vlv_rc = LDAP_VLV_SSS_MISSING;
781                         so2.so_vlv = op->o_ctrlflag[vlv_cid];
782                         rc = pack_vlv_response_control( op, rs, &so2, ctrls );
783                         if ( rc == LDAP_SUCCESS ) {
784                                 ctrls[1] = NULL;
785                                 slap_add_ctrls( op, rs, ctrls );
786                         }
787                         rs->sr_err = LDAP_VLV_ERROR;
788                         rs->sr_text = "Sort control is required with VLV";
789                         goto leave;
790                 }
791                 /* Not server side sort so just continue */
792                 return SLAP_CB_CONTINUE;
793         }
794
795         Debug(LDAP_DEBUG_TRACE,
796                 "==> sssvlv_search: <%s> %s, control flag: %d\n",
797                 op->o_req_dn.bv_val, op->ors_filterstr.bv_val,
798                 op->o_ctrlflag[sss_cid]);
799
800         sc = op->o_controls[sss_cid];
801         if ( sc->sc_nkeys > si->svi_max_keys ) {
802                 rs->sr_text = "Too many sort keys";
803                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
804                 goto leave;
805         }
806
807         ps = ( op->o_pagedresults > SLAP_CONTROL_IGNORED ) ?
808                 (PagedResultsState*)(op->o_pagedresults_state) : NULL;
809         vc = op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ?
810                 op->o_controls[vlv_cid] : NULL;
811
812         if ( ps && vc ) {
813                 rs->sr_text = "VLV incompatible with PagedResults";
814                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
815                 goto leave;
816         }
817
818         ok = 1;
819         ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
820         /* Is there already a sort running on this conn? */
821         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 );
822         if ( sess_id >= 0 ) {
823                 so = sort_conns[op->o_conn->c_conn_idx][sess_id];
824                 /* Is it a continuation of a VLV search? */
825                 if ( !vc || so->so_vlv <= SLAP_CONTROL_IGNORED ||
826                         vc->vc_context != so->so_vcontext ) {
827                         /* Is it a continuation of a paged search? */
828                         if ( !ps || so->so_paged <= SLAP_CONTROL_IGNORED ||
829                                 op->o_conn->c_pagedresults_state.ps_cookie != ps->ps_cookie ) {
830                                 ok = 0;
831                         } else if ( !ps->ps_size ) {
832                         /* Abandoning current request */
833                                 ok = 0;
834                                 so->so_nentries = 0;
835                                 rs->sr_err = LDAP_SUCCESS;
836                         }
837                 }
838                 if (( vc && so->so_paged > SLAP_CONTROL_IGNORED ) ||
839                         ( ps && so->so_vlv > SLAP_CONTROL_IGNORED )) {
840                         /* changed from paged to vlv or vice versa, abandon */
841                         ok = 0;
842                         so->so_nentries = 0;
843                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
844                 }
845         /* Are there too many running overall? */
846         } else if ( si->svi_num >= si->svi_max ) {
847                 ok = 0;
848         } else if ( ( sess_id = find_next_session(si->svi_max_percon, op->o_conn->c_conn_idx ) ) < 0 ) {
849                 ok = 0;
850         } else {
851                 /* OK, this connection now has a sort running */
852                 si->svi_num++;
853                 sort_conns[op->o_conn->c_conn_idx][sess_id] = &so2;
854                 sort_conns[op->o_conn->c_conn_idx][sess_id]->so_session = sess_id;
855         }
856         ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
857         if ( ok ) {
858                 /* are we continuing a VLV search? */
859                 if ( so && vc && vc->vc_context ) {
860                         so->so_ctrl = sc;
861                         send_list( op, rs, so );
862                         send_result( op, rs, so );
863                         rc = LDAP_SUCCESS;
864                 /* are we continuing a paged search? */
865                 } else if ( so && ps && ps->ps_cookie ) {
866                         so->so_ctrl = sc;
867                         send_page( op, rs, so );
868                         send_result( op, rs, so );
869                         rc = LDAP_SUCCESS;
870                 } else {
871                         slap_callback *cb = op->o_tmpalloc( sizeof(slap_callback),
872                                 op->o_tmpmemctx );
873                         /* Install serversort response callback to handle a new search */
874                         if ( ps || vc ) {
875                                 so = ch_calloc( 1, sizeof(sort_op));
876                         } else {
877                                 so = op->o_tmpcalloc( 1, sizeof(sort_op), op->o_tmpmemctx );
878                         }
879                         sort_conns[op->o_conn->c_conn_idx][sess_id] = so;
880
881                         cb->sc_cleanup          = NULL;
882                         cb->sc_response         = sssvlv_op_response;
883                         cb->sc_next                     = op->o_callback;
884                         cb->sc_private          = so;
885
886                         so->so_tree = NULL;
887                         so->so_ctrl = sc;
888                         so->so_info = si;
889                         if ( ps ) {
890                                 so->so_paged = op->o_pagedresults;
891                                 so->so_page_size = ps->ps_size;
892                                 op->o_pagedresults = SLAP_CONTROL_IGNORED;
893                         } else {
894                                 so->so_paged = 0;
895                                 so->so_page_size = 0;
896                                 if ( vc ) {
897                                         so->so_vlv = op->o_ctrlflag[vlv_cid];
898                                         so->so_vlv_target = 0;
899                                         so->so_vlv_rc = 0;
900                                 } else {
901                                         so->so_vlv = SLAP_CONTROL_NONE;
902                                 }
903                         }
904                         so->so_session = sess_id;
905                         so->so_vlv = op->o_ctrlflag[vlv_cid];
906                         so->so_vcontext = (unsigned long)so;
907                         so->so_nentries = 0;
908
909                         op->o_callback          = cb;
910                 }
911         } else {
912                 if ( so && !so->so_nentries ) {
913                         free_sort_op( op->o_conn, so );
914                 } else {
915                         rs->sr_text = "Other sort requests already in progress";
916                         rs->sr_err = LDAP_BUSY;
917                 }
918 leave:
919                 rc = rs->sr_err;
920                 send_ldap_result( op, rs );
921         }
922
923         return rc;
924 }
925
926 static int get_ordering_rule(
927         AttributeDescription    *ad,
928         struct berval                   *matchrule,
929         SlapReply                               *rs,
930         MatchingRule                    **ordering )
931 {
932         MatchingRule* mr;
933
934         if ( matchrule && matchrule->bv_val ) {
935                 mr = mr_find( matchrule->bv_val );
936                 if ( mr == NULL ) {
937                         rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
938                         rs->sr_text = "serverSort control: No ordering rule";
939                         Debug(LDAP_DEBUG_TRACE, "%s: no ordering rule function for %s\n",
940                                 debug_header, matchrule->bv_val, 0);
941                 }
942         }
943         else {
944                 mr = ad->ad_type->sat_ordering;
945                 if ( mr == NULL ) {
946                         rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
947                         rs->sr_text = "serverSort control: No ordering rule";
948                         Debug(LDAP_DEBUG_TRACE,
949                                 "%s: no ordering rule specified and no default ordering rule for attribute %s\n",
950                                 debug_header, ad->ad_cname.bv_val, 0);
951                 }
952         }
953
954         *ordering = mr;
955         return rs->sr_err;
956 }
957
958 static int count_key(BerElement *ber)
959 {
960         char *end;
961         ber_len_t len;
962         ber_tag_t tag;
963         int count = 0;
964
965         /* Server Side Sort Control is a SEQUENCE of SEQUENCE */
966         for ( tag = ber_first_element( ber, &len, &end );
967                   tag == LBER_SEQUENCE;
968                   tag = ber_next_element( ber, &len, end ))
969         {
970                 tag = ber_skip_tag( ber, &len );
971                 ber_skip_data( ber, len );
972                 ++count;
973         }
974         ber_rewind( ber );
975
976         return count;
977 }
978
979 static int build_key(
980         BerElement              *ber,
981         SlapReply               *rs,
982         sort_key                        *key )
983 {
984         struct berval attr;
985         struct berval matchrule = BER_BVNULL;
986         ber_int_t reverse = 0;
987         ber_tag_t tag;
988         ber_len_t len;
989         MatchingRule *ordering = NULL;
990         AttributeDescription *ad = NULL;
991         const char *text;
992
993         if (( tag = ber_scanf( ber, "{" )) == LBER_ERROR ) {
994                 rs->sr_text = "serverSort control: decoding error";
995                 rs->sr_err = LDAP_PROTOCOL_ERROR;
996                 return rs->sr_err;
997         }
998
999         if (( tag = ber_scanf( ber, "m", &attr )) == LBER_ERROR ) {
1000                 rs->sr_text = "serverSort control: attribute decoding error";
1001                 rs->sr_err = LDAP_PROTOCOL_ERROR;
1002                 return rs->sr_err;
1003         }
1004
1005         tag = ber_peek_tag( ber, &len );
1006         if ( tag == LDAP_MATCHRULE_IDENTIFIER ) {
1007                 if (( tag = ber_scanf( ber, "m", &matchrule )) == LBER_ERROR ) {
1008                         rs->sr_text = "serverSort control: matchrule decoding error";
1009                         rs->sr_err = LDAP_PROTOCOL_ERROR;
1010                         return rs->sr_err;
1011                 }
1012                 tag = ber_peek_tag( ber, &len );
1013         }
1014
1015         if ( tag == LDAP_REVERSEORDER_IDENTIFIER ) {
1016                 if (( tag = ber_scanf( ber, "b", &reverse )) == LBER_ERROR ) {
1017                         rs->sr_text = "serverSort control: reverse decoding error";
1018                         rs->sr_err = LDAP_PROTOCOL_ERROR;
1019                         return rs->sr_err;
1020                 }
1021         }
1022
1023         if (( tag = ber_scanf( ber, "}" )) == LBER_ERROR ) {
1024                 rs->sr_text = "serverSort control: decoding error";
1025                 rs->sr_err = LDAP_PROTOCOL_ERROR;
1026                 return rs->sr_err;
1027         }
1028
1029         if ( slap_bv2ad( &attr, &ad, &text ) != LDAP_SUCCESS ) {
1030                 rs->sr_text =
1031                         "serverSort control: Unrecognized attribute type in sort key";
1032                 Debug(LDAP_DEBUG_TRACE,
1033                         "%s: Unrecognized attribute type in sort key: %s\n",
1034                         debug_header, SAFESTR(attr.bv_val, "<None>"), 0);
1035                 rs->sr_err = LDAP_NO_SUCH_ATTRIBUTE;
1036                 return rs->sr_err;
1037         }
1038
1039         /* get_ordering_rule will set sr_err and sr_text */
1040         get_ordering_rule( ad, &matchrule, rs, &ordering );
1041         if ( rs->sr_err != LDAP_SUCCESS ) {
1042                 return rs->sr_err;
1043         }
1044
1045         key->sk_ad = ad;
1046         key->sk_ordering = ordering;
1047         key->sk_direction = reverse ? -1 : 1;
1048
1049         return rs->sr_err;
1050 }
1051
1052 static int sss_parseCtrl(
1053         Operation               *op,
1054         SlapReply               *rs,
1055         LDAPControl             *ctrl )
1056 {
1057         BerElementBuffer        berbuf;
1058         BerElement                      *ber;
1059         ber_tag_t               tag;
1060         ber_len_t               len;
1061         int                                     i;
1062         sort_ctrl       *sc;
1063
1064         rs->sr_err = LDAP_PROTOCOL_ERROR;
1065
1066         if ( op->o_ctrlflag[sss_cid] > SLAP_CONTROL_IGNORED ) {
1067                 rs->sr_text = "sorted results control specified multiple times";
1068         } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1069                 rs->sr_text = "sorted results control value is absent";
1070         } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1071                 rs->sr_text = "sorted results control value is empty";
1072         } else {
1073                 rs->sr_err = LDAP_SUCCESS;
1074         }
1075         if ( rs->sr_err != LDAP_SUCCESS )
1076                 return rs->sr_err;
1077
1078         op->o_ctrlflag[sss_cid] = ctrl->ldctl_iscritical ?
1079                 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1080
1081         ber = (BerElement *)&berbuf;
1082         ber_init2( ber, &ctrl->ldctl_value, 0 );
1083         i = count_key( ber );
1084
1085         sc = op->o_tmpalloc( sizeof(sort_ctrl) +
1086                 (i-1) * sizeof(sort_key), op->o_tmpmemctx );
1087         sc->sc_nkeys = i;
1088         op->o_controls[sss_cid] = sc;
1089
1090         /* peel off initial sequence */
1091         ber_scanf( ber, "{" );
1092
1093         i = 0;
1094         do {
1095                 if ( build_key( ber, rs, &sc->sc_keys[i] ) != LDAP_SUCCESS )
1096                         break;
1097                 i++;
1098                 tag = ber_peek_tag( ber, &len );
1099         } while ( tag != LBER_DEFAULT );
1100
1101         return rs->sr_err;
1102 }
1103
1104 static int vlv_parseCtrl(
1105         Operation               *op,
1106         SlapReply               *rs,
1107         LDAPControl             *ctrl )
1108 {
1109         BerElementBuffer        berbuf;
1110         BerElement                      *ber;
1111         ber_tag_t               tag;
1112         ber_len_t               len;
1113         vlv_ctrl        *vc, vc2;
1114
1115         rs->sr_err = LDAP_PROTOCOL_ERROR;
1116         rs->sr_text = NULL;
1117
1118         if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
1119                 rs->sr_text = "vlv control specified multiple times";
1120         } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1121                 rs->sr_text = "vlv control value is absent";
1122         } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1123                 rs->sr_text = "vlv control value is empty";
1124         }
1125         if ( rs->sr_text != NULL )
1126                 return rs->sr_err;
1127
1128         op->o_ctrlflag[vlv_cid] = ctrl->ldctl_iscritical ?
1129                 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1130
1131         ber = (BerElement *)&berbuf;
1132         ber_init2( ber, &ctrl->ldctl_value, 0 );
1133
1134         rs->sr_err = LDAP_PROTOCOL_ERROR;
1135
1136         tag = ber_scanf( ber, "{ii", &vc2.vc_before, &vc2.vc_after );
1137         if ( tag == LBER_ERROR ) {
1138                 return rs->sr_err;
1139         }
1140
1141         tag = ber_peek_tag( ber, &len );
1142         if ( tag == LDAP_VLVBYINDEX_IDENTIFIER ) {
1143                 tag = ber_scanf( ber, "{ii}", &vc2.vc_offset, &vc2.vc_count );
1144                 if ( tag == LBER_ERROR )
1145                         return rs->sr_err;
1146                 BER_BVZERO( &vc2.vc_value );
1147         } else if ( tag == LDAP_VLVBYVALUE_IDENTIFIER ) {
1148                 tag = ber_scanf( ber, "m", &vc2.vc_value );
1149                 if ( tag == LBER_ERROR || BER_BVISNULL( &vc2.vc_value ))
1150                         return rs->sr_err;
1151         } else {
1152                 return rs->sr_err;
1153         }
1154         tag = ber_peek_tag( ber, &len );
1155         if ( tag == LDAP_VLVCONTEXT_IDENTIFIER ) {
1156                 struct berval bv;
1157                 tag = ber_scanf( ber, "m", &bv );
1158                 if ( tag == LBER_ERROR || bv.bv_len != sizeof(vc2.vc_context))
1159                         return rs->sr_err;
1160                 AC_MEMCPY( &vc2.vc_context, bv.bv_val, bv.bv_len );
1161         } else {
1162                 vc2.vc_context = 0;
1163         }
1164
1165         vc = op->o_tmpalloc( sizeof(vlv_ctrl), op->o_tmpmemctx );
1166         *vc = vc2;
1167         op->o_controls[vlv_cid] = vc;
1168         rs->sr_err = LDAP_SUCCESS;
1169
1170         return rs->sr_err;
1171 }
1172
1173 static int sssvlv_connection_destroy( BackendDB *be, Connection *conn )
1174 {
1175         slap_overinst   *on             = (slap_overinst *)be->bd_info;
1176         sssvlv_info *si = on->on_bi.bi_private;
1177
1178         if ( sort_conns[conn->c_conn_idx] ) {
1179                 free_sort_ops( conn, sort_conns[conn->c_conn_idx], si->svi_max_percon );
1180         }
1181
1182         return LDAP_SUCCESS;
1183 }
1184
1185 static int sssvlv_db_open(
1186         BackendDB               *be,
1187         ConfigReply             *cr )
1188 {
1189         slap_overinst   *on = (slap_overinst *)be->bd_info;
1190         sssvlv_info *si = on->on_bi.bi_private;
1191         int rc;
1192         int conn_index;
1193
1194         /* If not set, default to 1/2 of available threads */
1195         if ( !si->svi_max )
1196                 si->svi_max = connection_pool_max / 2;
1197
1198         if ( dtblsize && !sort_conns ) {
1199                 ldap_pvt_thread_mutex_init( &sort_conns_mutex );
1200                 /* accommodate for c_conn_idx == -1 */
1201                 sort_conns = ch_calloc( dtblsize + 1, sizeof(sort_op **) );
1202                 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1203                         sort_conns[conn_index] = ch_calloc( si->svi_max_percon, sizeof(sort_op *) );
1204                 }
1205                 sort_conns++;
1206         }
1207
1208         rc = overlay_register_control( be, LDAP_CONTROL_SORTREQUEST );
1209         if ( rc == LDAP_SUCCESS )
1210                 rc = overlay_register_control( be, LDAP_CONTROL_VLVREQUEST );
1211         return rc;
1212 }
1213
1214 static ConfigTable sssvlv_cfg[] = {
1215         { "sssvlv-max", "num",
1216                 2, 2, 0, ARG_INT|ARG_OFFSET,
1217                         (void *)offsetof(sssvlv_info, svi_max),
1218                 "( OLcfgOvAt:21.1 NAME 'olcSssVlvMax' "
1219                         "DESC 'Maximum number of concurrent Sort requests' "
1220                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1221         { "sssvlv-maxkeys", "num",
1222                 2, 2, 0, ARG_INT|ARG_OFFSET,
1223                         (void *)offsetof(sssvlv_info, svi_max_keys),
1224                 "( OLcfgOvAt:21.2 NAME 'olcSssVlvMaxKeys' "
1225                         "DESC 'Maximum number of Keys in a Sort request' "
1226                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1227         { "sssvlv-maxpercon", "num",
1228                 2, 2, 0, ARG_INT|ARG_OFFSET,
1229                         (void *)offsetof(sssvlv_info, svi_max_percon),
1230                 "( OLcfgOvAt:21.3 NAME 'olcSssVlvMaxPerConn' "
1231                         "DESC 'Maximum number of concurrent paged search requests per connection' "
1232                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1233         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1234 };
1235
1236 static ConfigOCs sssvlv_ocs[] = {
1237         { "( OLcfgOvOc:21.1 "
1238                 "NAME 'olcSssVlvConfig' "
1239                 "DESC 'SSS VLV configuration' "
1240                 "SUP olcOverlayConfig "
1241                 "MAY ( olcSssVlvMax $ olcSssVlvMaxKeys ) )",
1242                 Cft_Overlay, sssvlv_cfg, NULL, NULL },
1243         { NULL, 0, NULL }
1244 };
1245
1246 static int sssvlv_db_init(
1247         BackendDB               *be,
1248         ConfigReply             *cr)
1249 {
1250         slap_overinst   *on = (slap_overinst *)be->bd_info;
1251         sssvlv_info *si;
1252
1253         if ( ov_count == 0 ) {
1254                 int rc;
1255
1256                 rc = register_supported_control2( LDAP_CONTROL_SORTREQUEST,
1257                         SLAP_CTRL_SEARCH,
1258                         NULL,
1259                         sss_parseCtrl,
1260                         1 /* replace */,
1261                         &sss_cid );
1262                 if ( rc != LDAP_SUCCESS ) {
1263                         Debug( LDAP_DEBUG_ANY, "Failed to register Sort Request control '%s' (%d)\n",
1264                                 LDAP_CONTROL_SORTREQUEST, rc, 0 );
1265                         return rc;
1266                 }
1267
1268                 rc = register_supported_control2( LDAP_CONTROL_VLVREQUEST,
1269                         SLAP_CTRL_SEARCH,
1270                         NULL,
1271                         vlv_parseCtrl,
1272                         1 /* replace */,
1273                         &vlv_cid );
1274                 if ( rc != LDAP_SUCCESS ) {
1275                         Debug( LDAP_DEBUG_ANY, "Failed to register VLV Request control '%s' (%d)\n",
1276                                 LDAP_CONTROL_VLVREQUEST, rc, 0 );
1277 #ifdef SLAP_CONFIG_DELETE
1278                         overlay_unregister_control( be, LDAP_CONTROL_SORTREQUEST );
1279 #endif /* SLAP_CONFIG_DELETE */
1280                         unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1281                         return rc;
1282                 }
1283         }
1284         
1285         si = (sssvlv_info *)ch_malloc(sizeof(sssvlv_info));
1286         on->on_bi.bi_private = si;
1287
1288         si->svi_max = 0;
1289         si->svi_num = 0;
1290         si->svi_max_keys = SSSVLV_DEFAULT_MAX_KEYS;
1291         si->svi_max_percon = SSSVLV_DEFAULT_MAX_REQUEST_PER_CONN;
1292
1293         ov_count++;
1294
1295         return LDAP_SUCCESS;
1296 }
1297
1298 static int sssvlv_db_destroy(
1299         BackendDB               *be,
1300         ConfigReply             *cr )
1301 {
1302         slap_overinst   *on = (slap_overinst *)be->bd_info;
1303         sssvlv_info *si = (sssvlv_info *)on->on_bi.bi_private;
1304         int conn_index;
1305         
1306         ov_count--;
1307         if ( !ov_count && sort_conns) {
1308                 sort_conns--;
1309                 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1310                         ch_free(sort_conns[conn_index]);
1311                 }
1312                 ch_free(sort_conns);
1313                 ldap_pvt_thread_mutex_destroy( &sort_conns_mutex );
1314         }
1315
1316         if ( ov_count == 0 ) {
1317                 unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1318         }
1319         
1320         if ( si ) {
1321                 ch_free( si );
1322                 on->on_bi.bi_private = NULL;
1323         }
1324         return LDAP_SUCCESS;
1325 }
1326
1327 static slap_overinst sssvlv;
1328
1329 int sssvlv_initialize()
1330 {
1331         int rc;
1332
1333         sssvlv.on_bi.bi_type                            = "sssvlv";
1334         sssvlv.on_bi.bi_db_init                         = sssvlv_db_init;
1335         sssvlv.on_bi.bi_db_destroy                      = sssvlv_db_destroy;
1336         sssvlv.on_bi.bi_db_open                         = sssvlv_db_open;
1337         sssvlv.on_bi.bi_connection_destroy      = sssvlv_connection_destroy;
1338         sssvlv.on_bi.bi_op_search                       = sssvlv_op_search;
1339
1340         sssvlv.on_bi.bi_cf_ocs = sssvlv_ocs;
1341
1342         rc = config_register_schema( sssvlv_cfg, sssvlv_ocs );
1343         if ( rc )
1344                 return rc;
1345
1346         rc = overlay_register( &sssvlv );
1347         if ( rc != LDAP_SUCCESS ) {
1348                 Debug( LDAP_DEBUG_ANY, "Failed to register server side sort overlay\n", 0, 0, 0 );
1349         }
1350
1351         return rc;
1352 }
1353
1354 #if SLAPD_OVER_SSSVLV == SLAPD_MOD_DYNAMIC
1355 int init_module( int argc, char *argv[])
1356 {
1357         return sssvlv_initialize();
1358 }
1359 #endif
1360
1361 #endif /* SLAPD_OVER_SSSVLV */