1 /* sssvlv.c - server side sort / virtual list view */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2009-2011 The OpenLDAP Foundation.
6 * Portions copyright 2009 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
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>.
18 * This work was initially developed by Howard Chu for inclusion in
19 * OpenLDAP Software. Support for multiple sorts per connection added
25 #ifdef SLAPD_OVER_SSSVLV
29 #include <ac/string.h>
38 #include "../../../libraries/liblber/lber-int.h" /* ber_rewind */
40 /* RFC2891: Server Side Sorting
41 * RFC2696: Paged Results
43 #ifndef LDAP_MATCHRULE_IDENTIFIER
44 #define LDAP_MATCHRULE_IDENTIFIER 0x80L
45 #define LDAP_REVERSEORDER_IDENTIFIER 0x81L
46 #define LDAP_ATTRTYPES_IDENTIFIER 0x80L
49 /* draft-ietf-ldapext-ldapv3-vlv-09.txt: Virtual List Views
51 #ifndef LDAP_VLVBYINDEX_IDENTIFIER
52 #define LDAP_VLVBYINDEX_IDENTIFIER 0xa0L
53 #define LDAP_VLVBYVALUE_IDENTIFIER 0x81L
54 #define LDAP_VLVCONTEXT_IDENTIFIER 0x04L
56 #define LDAP_VLV_SSS_MISSING 0x4C
57 #define LDAP_VLV_RANGE_ERROR 0x4D
60 #define SAFESTR(macro_str, macro_def) ((macro_str) ? (macro_str) : (macro_def))
62 #define SSSVLV_DEFAULT_MAX_KEYS 5
63 #define SSSVLV_DEFAULT_MAX_REQUEST_PER_CONN 5
65 #define NO_PS_COOKIE (PagedResultsCookie) -1
66 #define NO_VC_CONTEXT (unsigned long) -1
68 typedef struct vlv_ctrl {
73 struct berval vc_value;
74 unsigned long vc_context;
77 typedef struct sort_key
79 AttributeDescription *sk_ad;
80 MatchingRule *sk_ordering;
81 int sk_direction; /* 1=normal, -1=reverse */
84 typedef struct sort_ctrl {
90 typedef struct sort_node
95 struct berval *sn_vals;
98 typedef struct sssvlv_info
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 */
106 typedef struct sort_op
110 sssvlv_info *so_info;
118 unsigned long so_vcontext;
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;
126 static const char *debug_header = "sssvlv";
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).
137 static struct berval* select_value(
141 struct berval* ber1, *ber2;
142 MatchingRule *mr = key->sk_ordering;
146 ber1 = &(attr->a_nvals[0]);
148 for ( i = 1; i < attr->a_numvals; i++,ber2++ ) {
149 mr->smr_match( &cmp, 0, mr->smr_syntax, mr, ber1, ber2 );
155 Debug(LDAP_DEBUG_TRACE, "%s: value selected for compare: %s\n",
157 SAFESTR(ber1->bv_val, "<Empty>"),
163 static int node_cmp( const void* val1, const void* val2 )
165 sort_node *sn1 = (sort_node *)val1;
166 sort_node *sn2 = (sort_node *)val2;
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;
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] ))
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;
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] );
188 cmp *= sc->sc_keys[i].sk_direction;
194 static int node_insert( const void *val1, const void *val2 )
196 /* Never return equal so that new entries are always inserted */
197 return node_cmp( val1, val2 ) < 0 ? -1 : 1;
200 static int pack_vlv_response_control(
204 LDAPControl **ctrlsp )
207 BerElementBuffer berbuf;
208 BerElement *ber = (BerElement *)&berbuf;
209 struct berval cookie, bv;
212 ber_init2( ber, NULL, LBER_USE_DER );
213 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
215 rc = ber_printf( ber, "{iie", so->so_vlv_target, so->so_nentries,
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 );
225 rc = ber_printf( ber, "}" );
229 rc = ber_flatten2( ber, &bv, 0 );
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 );
243 rs->sr_err = LDAP_OTHER;
251 static int pack_pagedresult_response_control(
255 LDAPControl **ctrlsp )
258 BerElementBuffer berbuf;
259 BerElement *ber = (BerElement *)&berbuf;
260 PagedResultsCookie resp_cookie;
261 struct berval cookie, bv;
264 ber_init2( ber, NULL, LBER_USE_DER );
265 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
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;
272 resp_cookie = ( PagedResultsCookie )0;
273 BER_BVZERO( &cookie );
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
281 rc = ber_printf( ber, "{iO}", so->so_nentries, &cookie );
283 rc = ber_flatten2( ber, &bv, 0 );
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 );
297 rs->sr_err = LDAP_OTHER;
305 static int pack_sss_response_control(
308 LDAPControl **ctrlsp )
311 BerElementBuffer berbuf;
312 BerElement *ber = (BerElement *)&berbuf;
316 ber_init2( ber, NULL, LBER_USE_DER );
317 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
319 /* Pack error code */
320 rc = ber_printf(ber, "{e}", rs->sr_err);
323 rc = ber_flatten2( ber, &bv, 0 );
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 );
336 rs->sr_err = LDAP_OTHER;
344 /* Return the session id or -1 if unknown */
345 static int find_session_by_so(
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 )
361 /* Return the session id or -1 if unknown */
362 static int find_session_by_context(
365 unsigned long vc_context,
366 PagedResultsCookie ps_cookie )
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 ) )
378 static int find_next_session(
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]) {
389 if (sess_id >= svi_max_percon) {
396 static void free_sort_op( Connection *conn, sort_op *so )
400 tavl_free( so->so_tree, ch_free );
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 );
413 static void free_sort_ops( Connection *conn, sort_op **sos, int svi_max_percon )
418 for( sess_id = 0; sess_id < svi_max_percon ; sess_id++ ) {
419 so = sort_conns[conn->c_conn_idx][sess_id];
421 free_sort_op( conn, so );
422 sort_conns[conn->c_conn_idx][sess_id] = NULL;
427 static void send_list(
432 Avlnode *cur_node, *tmp_node;
433 vlv_ctrl *vc = op->o_controls[vlv_cid];
437 LDAPControl *ctrls[2];
439 /* FIXME: it may be better to just flatten the tree into
440 * an array before doing all of this...
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;
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 )
459 target = so->so_nentries * vc->vc_offset / vc->vc_count;
461 if ( vc->vc_offset > so->so_nentries ) {
463 so->so_vlv_rc = LDAP_VLV_RANGE_ERROR;
464 pack_vlv_response_control( op, rs, so, ctrls );
466 slap_add_ctrls( op, rs, ctrls );
467 rs->sr_err = LDAP_VLV_ERROR;
470 target = vc->vc_offset;
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;
478 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
480 target = so->so_nentries - target + 1;
482 for ( i=1; i<target; i++ )
483 cur_node = tavl_next( cur_node, dir );
486 /* we're looking for a specific value */
487 sort_ctrl *sc = so->so_ctrl;
488 MatchingRule *mr = sc->sc_keys[0].sk_ordering;
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 );
496 so->so_vlv_rc = LDAP_INAPPROPRIATE_MATCHING;
497 pack_vlv_response_control( op, rs, so, ctrls );
499 slap_add_ctrls( op, rs, ctrls );
500 rs->sr_err = LDAP_VLV_ERROR;
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 );
513 for (i=1; i<sc->sc_nkeys; i++) {
514 BER_BVZERO( &sn->sn_vals[i] );
516 cur_node = tavl_find3( so->so_tree, sn, node_cmp, &j );
517 /* didn't find >= match */
520 op->o_tmpfree( sn, op->o_tmpmemctx );
523 so->so_vlv_target = so->so_nentries + 1;
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] );
529 tmp_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
532 tmp_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
533 dir = TAVL_DIR_RIGHT;
535 for (i=0; tmp_node != cur_node;
536 tmp_node = tavl_next( tmp_node, dir ), i++);
537 so->so_vlv_target = i;
539 if ( bv.bv_val != vc->vc_value.bv_val )
540 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
544 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
548 for ( ; i<vc->vc_before; i++ ) {
549 tmp_node = tavl_next( cur_node, TAVL_DIR_LEFT );
550 if ( !tmp_node ) break;
553 j = i + vc->vc_after + 1;
555 for ( i=0; i<j; i++ ) {
556 sort_node *sn = cur_node->avl_data;
558 if ( slapd_shutdown ) break;
560 op->o_bd = select_backend( &sn->sn_dn, 0 );
562 rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );
564 if ( e && rc == LDAP_SUCCESS ) {
566 rs->sr_flags = REP_ENTRY_MUSTRELEASE;
567 rs->sr_err = send_search_entry( op, rs );
568 if ( rs->sr_err == LDAP_UNAVAILABLE )
571 cur_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
572 if ( !cur_node ) break;
574 so->so_vlv_rc = LDAP_SUCCESS;
579 static void send_page( Operation *op, SlapReply *rs, sort_op *so )
581 Avlnode *cur_node = so->so_tree;
582 Avlnode *next_node = NULL;
583 BackendDB *be = op->o_bd;
587 while ( cur_node && rs->sr_nentries < so->so_page_size ) {
588 sort_node *sn = cur_node->avl_data;
590 if ( slapd_shutdown ) break;
592 next_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
594 op->o_bd = select_backend( &sn->sn_dn, 0 );
596 rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );
598 ch_free( cur_node->avl_data );
599 ber_memfree( cur_node );
601 cur_node = next_node;
604 if ( e && rc == LDAP_SUCCESS ) {
606 rs->sr_flags = REP_ENTRY_MUSTRELEASE;
607 rs->sr_err = send_search_entry( op, rs );
608 if ( rs->sr_err == LDAP_UNAVAILABLE )
613 /* Set the first entry to send for the next page */
614 so->so_tree = next_node;
619 static void send_entry(
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>"));
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.
635 if ( (op->o_ctrlflag[sss_cid] != SLAP_CONTROL_CRITICAL) ||
636 (rs->sr_err == LDAP_SUCCESS) )
638 if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
639 send_list( op, rs, so );
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;
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.
650 so->so_page_size = so->so_nentries;
653 send_page( op, rs, so );
658 static void send_result(
663 LDAPControl *ctrls[3];
666 rc = pack_sss_response_control( op, rs, ctrls );
667 if ( rc == LDAP_SUCCESS ) {
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 );
675 if ( rc == LDAP_SUCCESS )
680 if ( ctrls[0] != NULL )
681 slap_add_ctrls( op, rs, ctrls );
682 send_ldap_result( op, rs );
684 if ( so->so_tree == NULL ) {
685 /* Search finished, so clean up */
686 free_sort_op( op->o_conn, so );
690 static int sssvlv_op_response(
694 sort_ctrl *sc = op->o_controls[sss_cid];
695 sort_op *so = op->o_callback->sc_private;
697 if ( rs->sr_type == REP_SEARCH ) {
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);
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 );
714 if ( a->a_numvals > 1 ) {
715 bv = select_value( a, &sc->sc_keys[i] );
719 sn->sn_vals[i] = *bv;
720 len += bv->bv_len + 1;
722 BER_BVZERO( &sn->sn_vals[i] );
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));
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;
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;
747 op->o_tmpfree( sn, op->o_tmpmemctx );
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 );
752 /* Insert into the AVL tree */
753 tavl_insert(&(so->so_tree), sn, node_insert, avl_dup_error);
757 /* Collected the keys so that they can be sorted. Thus, stop
758 * the entry from propagating.
760 rs->sr_err = LDAP_SUCCESS;
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.
767 if ( op->o_callback->sc_response == sssvlv_op_response ) {
768 op->o_callback = op->o_callback->sc_next;
771 send_entry( op, rs, so );
772 send_result( op, rs, so );
778 static int sssvlv_op_search(
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;
786 sort_op *so = NULL, so2;
788 PagedResultsState *ps;
792 if ( op->o_ctrlflag[sss_cid] <= SLAP_CONTROL_IGNORED ) {
793 if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
794 LDAPControl *ctrls[2];
796 so2.so_vlv_target = 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 ) {
803 slap_add_ctrls( op, rs, ctrls );
805 rs->sr_err = LDAP_VLV_ERROR;
806 rs->sr_text = "Sort control is required with VLV";
809 /* Not server side sort so just continue */
810 return SLAP_CB_CONTINUE;
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]);
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;
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;
831 rs->sr_text = "VLV incompatible with PagedResults";
832 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
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 ) {
849 } else if ( !ps->ps_size ) {
850 /* Abandoning current request */
853 rs->sr_err = LDAP_SUCCESS;
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 */
861 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
863 /* Are there too many running overall? */
864 } else if ( si->svi_num >= si->svi_max ) {
866 } else if ( ( sess_id = find_next_session(si->svi_max_percon, op->o_conn->c_conn_idx ) ) < 0 ) {
869 /* OK, this connection now has a sort running */
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;
874 ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
876 /* If we're a global overlay, this check got bypassed */
877 if ( !op->ors_limit && limits_check( op, rs ))
879 /* are we continuing a VLV search? */
880 if ( so && vc && vc->vc_context ) {
882 send_list( op, rs, so );
883 send_result( op, rs, so );
885 /* are we continuing a paged search? */
886 } else if ( so && ps && ps->ps_cookie ) {
888 send_page( op, rs, so );
889 send_result( op, rs, so );
892 slap_callback *cb = op->o_tmpalloc( sizeof(slap_callback),
894 /* Install serversort response callback to handle a new search */
896 so = ch_calloc( 1, sizeof(sort_op));
898 so = op->o_tmpcalloc( 1, sizeof(sort_op), op->o_tmpmemctx );
900 sort_conns[op->o_conn->c_conn_idx][sess_id] = so;
902 cb->sc_cleanup = NULL;
903 cb->sc_response = sssvlv_op_response;
904 cb->sc_next = op->o_callback;
911 so->so_paged = op->o_pagedresults;
912 so->so_page_size = ps->ps_size;
913 op->o_pagedresults = SLAP_CONTROL_IGNORED;
916 so->so_page_size = 0;
918 so->so_vlv = op->o_ctrlflag[vlv_cid];
919 so->so_vlv_target = 0;
922 so->so_vlv = SLAP_CONTROL_NONE;
925 so->so_session = sess_id;
926 so->so_vlv = op->o_ctrlflag[vlv_cid];
927 so->so_vcontext = (unsigned long)so;
933 if ( so && !so->so_nentries ) {
934 free_sort_op( op->o_conn, so );
936 rs->sr_text = "Other sort requests already in progress";
937 rs->sr_err = LDAP_BUSY;
941 send_ldap_result( op, rs );
947 static int get_ordering_rule(
948 AttributeDescription *ad,
949 struct berval *matchrule,
951 MatchingRule **ordering )
955 if ( matchrule && matchrule->bv_val ) {
956 mr = mr_find( matchrule->bv_val );
958 rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
959 rs->sr_text = "serverSort control: No ordering rule";
960 Debug(LDAP_DEBUG_TRACE, "%s: no ordering rule function for %s\n",
961 debug_header, matchrule->bv_val, 0);
965 mr = ad->ad_type->sat_ordering;
967 rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
968 rs->sr_text = "serverSort control: No ordering rule";
969 Debug(LDAP_DEBUG_TRACE,
970 "%s: no ordering rule specified and no default ordering rule for attribute %s\n",
971 debug_header, ad->ad_cname.bv_val, 0);
979 static int count_key(BerElement *ber)
986 /* Server Side Sort Control is a SEQUENCE of SEQUENCE */
987 for ( tag = ber_first_element( ber, &len, &end );
988 tag == LBER_SEQUENCE;
989 tag = ber_next_element( ber, &len, end ))
991 tag = ber_skip_tag( ber, &len );
992 ber_skip_data( ber, len );
1000 static int build_key(
1006 struct berval matchrule = BER_BVNULL;
1007 ber_int_t reverse = 0;
1010 MatchingRule *ordering = NULL;
1011 AttributeDescription *ad = NULL;
1014 if (( tag = ber_scanf( ber, "{" )) == LBER_ERROR ) {
1015 rs->sr_text = "serverSort control: decoding error";
1016 rs->sr_err = LDAP_PROTOCOL_ERROR;
1020 if (( tag = ber_scanf( ber, "m", &attr )) == LBER_ERROR ) {
1021 rs->sr_text = "serverSort control: attribute decoding error";
1022 rs->sr_err = LDAP_PROTOCOL_ERROR;
1026 tag = ber_peek_tag( ber, &len );
1027 if ( tag == LDAP_MATCHRULE_IDENTIFIER ) {
1028 if (( tag = ber_scanf( ber, "m", &matchrule )) == LBER_ERROR ) {
1029 rs->sr_text = "serverSort control: matchrule decoding error";
1030 rs->sr_err = LDAP_PROTOCOL_ERROR;
1033 tag = ber_peek_tag( ber, &len );
1036 if ( tag == LDAP_REVERSEORDER_IDENTIFIER ) {
1037 if (( tag = ber_scanf( ber, "b", &reverse )) == LBER_ERROR ) {
1038 rs->sr_text = "serverSort control: reverse decoding error";
1039 rs->sr_err = LDAP_PROTOCOL_ERROR;
1044 if (( tag = ber_scanf( ber, "}" )) == LBER_ERROR ) {
1045 rs->sr_text = "serverSort control: decoding error";
1046 rs->sr_err = LDAP_PROTOCOL_ERROR;
1050 if ( slap_bv2ad( &attr, &ad, &text ) != LDAP_SUCCESS ) {
1052 "serverSort control: Unrecognized attribute type in sort key";
1053 Debug(LDAP_DEBUG_TRACE,
1054 "%s: Unrecognized attribute type in sort key: %s\n",
1055 debug_header, SAFESTR(attr.bv_val, "<None>"), 0);
1056 rs->sr_err = LDAP_NO_SUCH_ATTRIBUTE;
1060 /* get_ordering_rule will set sr_err and sr_text */
1061 get_ordering_rule( ad, &matchrule, rs, &ordering );
1062 if ( rs->sr_err != LDAP_SUCCESS ) {
1067 key->sk_ordering = ordering;
1068 key->sk_direction = reverse ? -1 : 1;
1073 static int sss_parseCtrl(
1078 BerElementBuffer berbuf;
1085 rs->sr_err = LDAP_PROTOCOL_ERROR;
1087 if ( op->o_ctrlflag[sss_cid] > SLAP_CONTROL_IGNORED ) {
1088 rs->sr_text = "sorted results control specified multiple times";
1089 } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1090 rs->sr_text = "sorted results control value is absent";
1091 } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1092 rs->sr_text = "sorted results control value is empty";
1094 rs->sr_err = LDAP_SUCCESS;
1096 if ( rs->sr_err != LDAP_SUCCESS )
1099 op->o_ctrlflag[sss_cid] = ctrl->ldctl_iscritical ?
1100 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1102 ber = (BerElement *)&berbuf;
1103 ber_init2( ber, &ctrl->ldctl_value, 0 );
1104 i = count_key( ber );
1106 sc = op->o_tmpalloc( sizeof(sort_ctrl) +
1107 (i-1) * sizeof(sort_key), op->o_tmpmemctx );
1109 op->o_controls[sss_cid] = sc;
1111 /* peel off initial sequence */
1112 ber_scanf( ber, "{" );
1116 if ( build_key( ber, rs, &sc->sc_keys[i] ) != LDAP_SUCCESS )
1119 tag = ber_peek_tag( ber, &len );
1120 } while ( tag != LBER_DEFAULT );
1125 static int vlv_parseCtrl(
1130 BerElementBuffer berbuf;
1136 rs->sr_err = LDAP_PROTOCOL_ERROR;
1139 if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
1140 rs->sr_text = "vlv control specified multiple times";
1141 } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1142 rs->sr_text = "vlv control value is absent";
1143 } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1144 rs->sr_text = "vlv control value is empty";
1146 if ( rs->sr_text != NULL )
1149 op->o_ctrlflag[vlv_cid] = ctrl->ldctl_iscritical ?
1150 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1152 ber = (BerElement *)&berbuf;
1153 ber_init2( ber, &ctrl->ldctl_value, 0 );
1155 rs->sr_err = LDAP_PROTOCOL_ERROR;
1157 tag = ber_scanf( ber, "{ii", &vc2.vc_before, &vc2.vc_after );
1158 if ( tag == LBER_ERROR ) {
1162 tag = ber_peek_tag( ber, &len );
1163 if ( tag == LDAP_VLVBYINDEX_IDENTIFIER ) {
1164 tag = ber_scanf( ber, "{ii}", &vc2.vc_offset, &vc2.vc_count );
1165 if ( tag == LBER_ERROR )
1167 BER_BVZERO( &vc2.vc_value );
1168 } else if ( tag == LDAP_VLVBYVALUE_IDENTIFIER ) {
1169 tag = ber_scanf( ber, "m", &vc2.vc_value );
1170 if ( tag == LBER_ERROR || BER_BVISNULL( &vc2.vc_value ))
1175 tag = ber_peek_tag( ber, &len );
1176 if ( tag == LDAP_VLVCONTEXT_IDENTIFIER ) {
1178 tag = ber_scanf( ber, "m", &bv );
1179 if ( tag == LBER_ERROR || bv.bv_len != sizeof(vc2.vc_context))
1181 AC_MEMCPY( &vc2.vc_context, bv.bv_val, bv.bv_len );
1186 vc = op->o_tmpalloc( sizeof(vlv_ctrl), op->o_tmpmemctx );
1188 op->o_controls[vlv_cid] = vc;
1189 rs->sr_err = LDAP_SUCCESS;
1194 static int sssvlv_connection_destroy( BackendDB *be, Connection *conn )
1196 slap_overinst *on = (slap_overinst *)be->bd_info;
1197 sssvlv_info *si = on->on_bi.bi_private;
1199 if ( sort_conns[conn->c_conn_idx] ) {
1200 free_sort_ops( conn, sort_conns[conn->c_conn_idx], si->svi_max_percon );
1203 return LDAP_SUCCESS;
1206 static int sssvlv_db_open(
1210 slap_overinst *on = (slap_overinst *)be->bd_info;
1211 sssvlv_info *si = on->on_bi.bi_private;
1215 /* If not set, default to 1/2 of available threads */
1217 si->svi_max = connection_pool_max / 2;
1219 if ( dtblsize && !sort_conns ) {
1220 ldap_pvt_thread_mutex_init( &sort_conns_mutex );
1221 /* accommodate for c_conn_idx == -1 */
1222 sort_conns = ch_calloc( dtblsize + 1, sizeof(sort_op **) );
1223 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1224 sort_conns[conn_index] = ch_calloc( si->svi_max_percon, sizeof(sort_op *) );
1229 rc = overlay_register_control( be, LDAP_CONTROL_SORTREQUEST );
1230 if ( rc == LDAP_SUCCESS )
1231 rc = overlay_register_control( be, LDAP_CONTROL_VLVREQUEST );
1235 static ConfigTable sssvlv_cfg[] = {
1236 { "sssvlv-max", "num",
1237 2, 2, 0, ARG_INT|ARG_OFFSET,
1238 (void *)offsetof(sssvlv_info, svi_max),
1239 "( OLcfgOvAt:21.1 NAME 'olcSssVlvMax' "
1240 "DESC 'Maximum number of concurrent Sort requests' "
1241 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1242 { "sssvlv-maxkeys", "num",
1243 2, 2, 0, ARG_INT|ARG_OFFSET,
1244 (void *)offsetof(sssvlv_info, svi_max_keys),
1245 "( OLcfgOvAt:21.2 NAME 'olcSssVlvMaxKeys' "
1246 "DESC 'Maximum number of Keys in a Sort request' "
1247 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1248 { "sssvlv-maxpercon", "num",
1249 2, 2, 0, ARG_INT|ARG_OFFSET,
1250 (void *)offsetof(sssvlv_info, svi_max_percon),
1251 "( OLcfgOvAt:21.3 NAME 'olcSssVlvMaxPerConn' "
1252 "DESC 'Maximum number of concurrent paged search requests per connection' "
1253 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1254 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1257 static ConfigOCs sssvlv_ocs[] = {
1258 { "( OLcfgOvOc:21.1 "
1259 "NAME 'olcSssVlvConfig' "
1260 "DESC 'SSS VLV configuration' "
1261 "SUP olcOverlayConfig "
1262 "MAY ( olcSssVlvMax $ olcSssVlvMaxKeys ) )",
1263 Cft_Overlay, sssvlv_cfg, NULL, NULL },
1267 static int sssvlv_db_init(
1271 slap_overinst *on = (slap_overinst *)be->bd_info;
1274 if ( ov_count == 0 ) {
1277 rc = register_supported_control2( LDAP_CONTROL_SORTREQUEST,
1283 if ( rc != LDAP_SUCCESS ) {
1284 Debug( LDAP_DEBUG_ANY, "Failed to register Sort Request control '%s' (%d)\n",
1285 LDAP_CONTROL_SORTREQUEST, rc, 0 );
1289 rc = register_supported_control2( LDAP_CONTROL_VLVREQUEST,
1295 if ( rc != LDAP_SUCCESS ) {
1296 Debug( LDAP_DEBUG_ANY, "Failed to register VLV Request control '%s' (%d)\n",
1297 LDAP_CONTROL_VLVREQUEST, rc, 0 );
1298 #ifdef SLAP_CONFIG_DELETE
1299 overlay_unregister_control( be, LDAP_CONTROL_SORTREQUEST );
1300 unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1301 #endif /* SLAP_CONFIG_DELETE */
1306 si = (sssvlv_info *)ch_malloc(sizeof(sssvlv_info));
1307 on->on_bi.bi_private = si;
1311 si->svi_max_keys = SSSVLV_DEFAULT_MAX_KEYS;
1312 si->svi_max_percon = SSSVLV_DEFAULT_MAX_REQUEST_PER_CONN;
1316 return LDAP_SUCCESS;
1319 static int sssvlv_db_destroy(
1323 slap_overinst *on = (slap_overinst *)be->bd_info;
1324 sssvlv_info *si = (sssvlv_info *)on->on_bi.bi_private;
1328 if ( !ov_count && sort_conns) {
1330 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1331 ch_free(sort_conns[conn_index]);
1333 ch_free(sort_conns);
1334 ldap_pvt_thread_mutex_destroy( &sort_conns_mutex );
1337 #ifdef SLAP_CONFIG_DELETE
1338 overlay_unregister_control( be, LDAP_CONTROL_SORTREQUEST );
1339 overlay_unregister_control( be, LDAP_CONTROL_VLVREQUEST );
1340 if ( ov_count == 0 ) {
1341 unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1342 unregister_supported_control( LDAP_CONTROL_VLVREQUEST );
1344 #endif /* SLAP_CONFIG_DELETE */
1348 on->on_bi.bi_private = NULL;
1350 return LDAP_SUCCESS;
1353 static slap_overinst sssvlv;
1355 int sssvlv_initialize()
1359 sssvlv.on_bi.bi_type = "sssvlv";
1360 sssvlv.on_bi.bi_db_init = sssvlv_db_init;
1361 sssvlv.on_bi.bi_db_destroy = sssvlv_db_destroy;
1362 sssvlv.on_bi.bi_db_open = sssvlv_db_open;
1363 sssvlv.on_bi.bi_connection_destroy = sssvlv_connection_destroy;
1364 sssvlv.on_bi.bi_op_search = sssvlv_op_search;
1366 sssvlv.on_bi.bi_cf_ocs = sssvlv_ocs;
1368 rc = config_register_schema( sssvlv_cfg, sssvlv_ocs );
1372 rc = overlay_register( &sssvlv );
1373 if ( rc != LDAP_SUCCESS ) {
1374 Debug( LDAP_DEBUG_ANY, "Failed to register server side sort overlay\n", 0, 0, 0 );
1380 #if SLAPD_OVER_SSSVLV == SLAPD_MOD_DYNAMIC
1381 int init_module( int argc, char *argv[])
1383 return sssvlv_initialize();
1387 #endif /* SLAPD_OVER_SSSVLV */