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