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