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