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