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