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