1 /* sssvlv.c - server side sort / virtual list view */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2009-2013 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 if ( so->so_paged > SLAP_CONTROL_IGNORED ) {
401 Avlnode *cur_node, *next_node;
402 cur_node = so->so_tree;
404 next_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
405 ch_free( cur_node->avl_data );
406 ber_memfree( cur_node );
408 cur_node = next_node;
411 tavl_free( so->so_tree, ch_free );
416 ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
417 sess_id = find_session_by_so( so->so_info->svi_max_percon, conn->c_conn_idx, so );
418 sort_conns[conn->c_conn_idx][sess_id] = NULL;
419 so->so_info->svi_num--;
420 ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
425 static void free_sort_ops( Connection *conn, sort_op **sos, int svi_max_percon )
430 for( sess_id = 0; sess_id < svi_max_percon ; sess_id++ ) {
431 so = sort_conns[conn->c_conn_idx][sess_id];
433 free_sort_op( conn, so );
434 sort_conns[conn->c_conn_idx][sess_id] = NULL;
439 static void send_list(
444 Avlnode *cur_node, *tmp_node;
445 vlv_ctrl *vc = op->o_controls[vlv_cid];
449 LDAPControl *ctrls[2];
451 rs->sr_attrs = op->ors_attrs;
453 /* FIXME: it may be better to just flatten the tree into
454 * an array before doing all of this...
457 /* Are we just counting an offset? */
458 if ( BER_BVISNULL( &vc->vc_value )) {
459 if ( vc->vc_offset == vc->vc_count ) {
460 /* wants the last entry in the list */
461 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
462 so->so_vlv_target = so->so_nentries;
463 } else if ( vc->vc_offset == 1 ) {
464 /* wants the first entry in the list */
465 cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
466 so->so_vlv_target = 1;
469 /* Just iterate to the right spot */
470 if ( vc->vc_count && vc->vc_count != so->so_nentries ) {
471 if ( vc->vc_offset > vc->vc_count )
473 target = so->so_nentries * vc->vc_offset / vc->vc_count;
475 if ( vc->vc_offset > so->so_nentries ) {
477 so->so_vlv_rc = LDAP_VLV_RANGE_ERROR;
478 pack_vlv_response_control( op, rs, so, ctrls );
480 slap_add_ctrls( op, rs, ctrls );
481 rs->sr_err = LDAP_VLV_ERROR;
484 target = vc->vc_offset;
486 so->so_vlv_target = target;
487 /* Start at left and go right, or start at right and go left? */
488 if ( target < so->so_nentries / 2 ) {
489 cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
490 dir = TAVL_DIR_RIGHT;
492 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
494 target = so->so_nentries - target + 1;
496 for ( i=1; i<target; i++ )
497 cur_node = tavl_next( cur_node, dir );
500 /* we're looking for a specific value */
501 sort_ctrl *sc = so->so_ctrl;
502 MatchingRule *mr = sc->sc_keys[0].sk_ordering;
506 if ( mr->smr_normalize ) {
507 rc = mr->smr_normalize( SLAP_MR_VALUE_OF_SYNTAX,
508 mr->smr_syntax, mr, &vc->vc_value, &bv, op->o_tmpmemctx );
510 so->so_vlv_rc = LDAP_INAPPROPRIATE_MATCHING;
511 pack_vlv_response_control( op, rs, so, ctrls );
513 slap_add_ctrls( op, rs, ctrls );
514 rs->sr_err = LDAP_VLV_ERROR;
521 sn = op->o_tmpalloc( sizeof(sort_node) +
522 sc->sc_nkeys * sizeof(struct berval), op->o_tmpmemctx );
523 sn->sn_vals = (struct berval *)(sn+1);
524 sn->sn_conn = op->o_conn->c_conn_idx;
525 sn->sn_session = find_session_by_so( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, so );
527 for (i=1; i<sc->sc_nkeys; i++) {
528 BER_BVZERO( &sn->sn_vals[i] );
530 cur_node = tavl_find3( so->so_tree, sn, node_cmp, &j );
531 /* didn't find >= match */
534 cur_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
536 op->o_tmpfree( sn, op->o_tmpmemctx );
539 so->so_vlv_target = so->so_nentries + 1;
541 sort_node *sn = so->so_tree->avl_data;
542 /* start from the left or the right side? */
543 mr->smr_match( &i, 0, mr->smr_syntax, mr, &bv, &sn->sn_vals[0] );
545 tmp_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
548 tmp_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
549 dir = TAVL_DIR_RIGHT;
551 for (i=0; tmp_node != cur_node;
552 tmp_node = tavl_next( tmp_node, dir ), i++);
553 so->so_vlv_target = (dir == TAVL_DIR_RIGHT) ? i+1 : so->so_nentries - i;
555 if ( bv.bv_val != vc->vc_value.bv_val )
556 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
560 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
564 for ( ; i<vc->vc_before; i++ ) {
565 tmp_node = tavl_next( cur_node, TAVL_DIR_LEFT );
566 if ( !tmp_node ) break;
569 j = i + vc->vc_after + 1;
571 for ( i=0; i<j; i++ ) {
572 sort_node *sn = cur_node->avl_data;
574 if ( slapd_shutdown ) break;
576 op->o_bd = select_backend( &sn->sn_dn, 0 );
578 rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );
580 if ( e && rc == LDAP_SUCCESS ) {
582 rs->sr_flags = REP_ENTRY_MUSTRELEASE;
583 rs->sr_err = send_search_entry( op, rs );
584 if ( rs->sr_err == LDAP_UNAVAILABLE )
587 cur_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
588 if ( !cur_node ) break;
590 so->so_vlv_rc = LDAP_SUCCESS;
595 static void send_page( Operation *op, SlapReply *rs, sort_op *so )
597 Avlnode *cur_node = so->so_tree;
598 Avlnode *next_node = NULL;
599 BackendDB *be = op->o_bd;
603 rs->sr_attrs = op->ors_attrs;
605 while ( cur_node && rs->sr_nentries < so->so_page_size ) {
606 sort_node *sn = cur_node->avl_data;
608 if ( slapd_shutdown ) break;
610 next_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
612 op->o_bd = select_backend( &sn->sn_dn, 0 );
614 rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );
616 ch_free( cur_node->avl_data );
617 ber_memfree( cur_node );
619 cur_node = next_node;
622 if ( e && rc == LDAP_SUCCESS ) {
624 rs->sr_flags = REP_ENTRY_MUSTRELEASE;
625 rs->sr_err = send_search_entry( op, rs );
626 if ( rs->sr_err == LDAP_UNAVAILABLE )
631 /* Set the first entry to send for the next page */
632 so->so_tree = next_node;
634 next_node->avl_left = NULL;
639 static void send_entry(
644 Debug(LDAP_DEBUG_TRACE,
645 "%s: response control: status=%d, text=%s\n",
646 debug_header, rs->sr_err, SAFESTR(rs->sr_text, "<None>"));
651 /* RFC 2891: If critical then send the entries iff they were
652 * succesfully sorted. If non-critical send all entries
653 * whether they were sorted or not.
655 if ( (op->o_ctrlflag[sss_cid] != SLAP_CONTROL_CRITICAL) ||
656 (rs->sr_err == LDAP_SUCCESS) )
658 if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
659 send_list( op, rs, so );
661 /* Get the first node to send */
662 Avlnode *start_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
663 so->so_tree = start_node;
665 if ( so->so_paged <= SLAP_CONTROL_IGNORED ) {
666 /* Not paged result search. Send all entries.
667 * Set the page size to the number of entries
668 * so that send_page() will send all entries.
670 so->so_page_size = so->so_nentries;
673 send_page( op, rs, so );
678 static void send_result(
683 LDAPControl *ctrls[3];
686 rc = pack_sss_response_control( op, rs, ctrls );
687 if ( rc == LDAP_SUCCESS ) {
690 if ( so->so_paged > SLAP_CONTROL_IGNORED ) {
691 rc = pack_pagedresult_response_control( op, rs, so, ctrls+1 );
692 } else if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
693 rc = pack_vlv_response_control( op, rs, so, ctrls+1 );
695 if ( rc == LDAP_SUCCESS )
700 if ( ctrls[0] != NULL )
701 slap_add_ctrls( op, rs, ctrls );
702 send_ldap_result( op, rs );
704 if ( so->so_tree == NULL ) {
705 /* Search finished, so clean up */
706 free_sort_op( op->o_conn, so );
710 static int sssvlv_op_response(
714 sort_ctrl *sc = op->o_controls[sss_cid];
715 sort_op *so = op->o_callback->sc_private;
717 if ( rs->sr_type == REP_SEARCH ) {
724 len = sizeof(sort_node) + sc->sc_nkeys * sizeof(struct berval) +
725 rs->sr_entry->e_nname.bv_len + 1;
726 sn = op->o_tmpalloc( len, op->o_tmpmemctx );
727 sn->sn_vals = (struct berval *)(sn+1);
729 /* Build tmp list of key values */
730 for ( i=0; i<sc->sc_nkeys; i++ ) {
731 Attribute *a = attr_find( rs->sr_entry->e_attrs,
732 sc->sc_keys[i].sk_ad );
734 if ( a->a_numvals > 1 ) {
735 bv = select_value( a, &sc->sc_keys[i] );
739 sn->sn_vals[i] = *bv;
740 len += bv->bv_len + 1;
742 BER_BVZERO( &sn->sn_vals[i] );
746 /* Now dup into regular memory */
747 sn2 = ch_malloc( len );
748 sn2->sn_vals = (struct berval *)(sn2+1);
749 AC_MEMCPY( sn2->sn_vals, sn->sn_vals,
750 sc->sc_nkeys * sizeof(struct berval));
752 ptr = (char *)(sn2->sn_vals + sc->sc_nkeys);
753 sn2->sn_dn.bv_val = ptr;
754 sn2->sn_dn.bv_len = rs->sr_entry->e_nname.bv_len;
755 AC_MEMCPY( ptr, rs->sr_entry->e_nname.bv_val,
756 rs->sr_entry->e_nname.bv_len );
757 ptr += rs->sr_entry->e_nname.bv_len;
759 for ( i=0; i<sc->sc_nkeys; i++ ) {
760 if ( !BER_BVISNULL( &sn2->sn_vals[i] )) {
761 AC_MEMCPY(ptr, sn2->sn_vals[i].bv_val, sn2->sn_vals[i].bv_len);
762 sn2->sn_vals[i].bv_val = ptr;
763 ptr += sn2->sn_vals[i].bv_len;
767 op->o_tmpfree( sn, op->o_tmpmemctx );
769 sn->sn_conn = op->o_conn->c_conn_idx;
770 sn->sn_session = find_session_by_so( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, so );
772 /* Insert into the AVL tree */
773 tavl_insert(&(so->so_tree), sn, node_insert, avl_dup_error);
777 /* Collected the keys so that they can be sorted. Thus, stop
778 * the entry from propagating.
780 rs->sr_err = LDAP_SUCCESS;
782 else if ( rs->sr_type == REP_RESULT ) {
783 /* Remove serversort response callback.
784 * We don't want the entries that we are about to send to be
785 * processed by serversort response again.
787 if ( op->o_callback->sc_response == sssvlv_op_response ) {
788 op->o_callback = op->o_callback->sc_next;
791 send_entry( op, rs, so );
792 send_result( op, rs, so );
798 static int sssvlv_op_search(
802 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
803 sssvlv_info *si = on->on_bi.bi_private;
804 int rc = SLAP_CB_CONTINUE;
806 sort_op *so = NULL, so2;
808 PagedResultsState *ps;
812 if ( op->o_ctrlflag[sss_cid] <= SLAP_CONTROL_IGNORED ) {
813 if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
814 LDAPControl *ctrls[2];
816 so2.so_vlv_target = 0;
818 so2.so_vlv_rc = LDAP_VLV_SSS_MISSING;
819 so2.so_vlv = op->o_ctrlflag[vlv_cid];
820 rc = pack_vlv_response_control( op, rs, &so2, ctrls );
821 if ( rc == LDAP_SUCCESS ) {
823 slap_add_ctrls( op, rs, ctrls );
825 rs->sr_err = LDAP_VLV_ERROR;
826 rs->sr_text = "Sort control is required with VLV";
829 /* Not server side sort so just continue */
830 return SLAP_CB_CONTINUE;
833 Debug(LDAP_DEBUG_TRACE,
834 "==> sssvlv_search: <%s> %s, control flag: %d\n",
835 op->o_req_dn.bv_val, op->ors_filterstr.bv_val,
836 op->o_ctrlflag[sss_cid]);
838 sc = op->o_controls[sss_cid];
839 if ( sc->sc_nkeys > si->svi_max_keys ) {
840 rs->sr_text = "Too many sort keys";
841 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
845 ps = ( op->o_pagedresults > SLAP_CONTROL_IGNORED ) ?
846 (PagedResultsState*)(op->o_pagedresults_state) : NULL;
847 vc = op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ?
848 op->o_controls[vlv_cid] : NULL;
851 rs->sr_text = "VLV incompatible with PagedResults";
852 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
857 ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
858 /* Is there already a sort running on this conn? */
859 sess_id = find_session_by_context( si->svi_max_percon, op->o_conn->c_conn_idx, vc ? vc->vc_context : NO_VC_CONTEXT, ps ? ps->ps_cookie : NO_PS_COOKIE );
860 if ( sess_id >= 0 ) {
861 so = sort_conns[op->o_conn->c_conn_idx][sess_id];
862 /* Is it a continuation of a VLV search? */
863 if ( !vc || so->so_vlv <= SLAP_CONTROL_IGNORED ||
864 vc->vc_context != so->so_vcontext ) {
865 /* Is it a continuation of a paged search? */
866 if ( !ps || so->so_paged <= SLAP_CONTROL_IGNORED ||
867 op->o_conn->c_pagedresults_state.ps_cookie != ps->ps_cookie ) {
869 } else if ( !ps->ps_size ) {
870 /* Abandoning current request */
873 rs->sr_err = LDAP_SUCCESS;
876 if (( vc && so->so_paged > SLAP_CONTROL_IGNORED ) ||
877 ( ps && so->so_vlv > SLAP_CONTROL_IGNORED )) {
878 /* changed from paged to vlv or vice versa, abandon */
881 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
883 /* Are there too many running overall? */
884 } else if ( si->svi_num >= si->svi_max ) {
886 } else if ( ( sess_id = find_next_session(si->svi_max_percon, op->o_conn->c_conn_idx ) ) < 0 ) {
889 /* OK, this connection now has a sort running */
891 sort_conns[op->o_conn->c_conn_idx][sess_id] = &so2;
892 sort_conns[op->o_conn->c_conn_idx][sess_id]->so_session = sess_id;
894 ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
896 /* If we're a global overlay, this check got bypassed */
897 if ( !op->ors_limit && limits_check( op, rs ))
899 /* are we continuing a VLV search? */
900 if ( so && vc && vc->vc_context ) {
902 send_list( op, rs, so );
903 send_result( op, rs, so );
905 /* are we continuing a paged search? */
906 } else if ( so && ps && ps->ps_cookie ) {
908 send_page( op, rs, so );
909 send_result( op, rs, so );
912 slap_callback *cb = op->o_tmpalloc( sizeof(slap_callback),
914 /* Install serversort response callback to handle a new search */
916 so = ch_calloc( 1, sizeof(sort_op));
918 so = op->o_tmpcalloc( 1, sizeof(sort_op), op->o_tmpmemctx );
920 sort_conns[op->o_conn->c_conn_idx][sess_id] = so;
922 cb->sc_cleanup = NULL;
923 cb->sc_response = sssvlv_op_response;
924 cb->sc_next = op->o_callback;
931 so->so_paged = op->o_pagedresults;
932 so->so_page_size = ps->ps_size;
933 op->o_pagedresults = SLAP_CONTROL_IGNORED;
936 so->so_page_size = 0;
938 so->so_vlv = op->o_ctrlflag[vlv_cid];
939 so->so_vlv_target = 0;
942 so->so_vlv = SLAP_CONTROL_NONE;
945 so->so_session = sess_id;
946 so->so_vlv = op->o_ctrlflag[vlv_cid];
947 so->so_vcontext = (unsigned long)so;
953 if ( so && !so->so_nentries ) {
954 free_sort_op( op->o_conn, so );
956 rs->sr_text = "Other sort requests already in progress";
957 rs->sr_err = LDAP_BUSY;
961 send_ldap_result( op, rs );
967 static int get_ordering_rule(
968 AttributeDescription *ad,
969 struct berval *matchrule,
971 MatchingRule **ordering )
975 if ( matchrule && matchrule->bv_val ) {
976 mr = mr_find( matchrule->bv_val );
978 rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
979 rs->sr_text = "serverSort control: No ordering rule";
980 Debug(LDAP_DEBUG_TRACE, "%s: no ordering rule function for %s\n",
981 debug_header, matchrule->bv_val, 0);
985 mr = ad->ad_type->sat_ordering;
987 rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
988 rs->sr_text = "serverSort control: No ordering rule";
989 Debug(LDAP_DEBUG_TRACE,
990 "%s: no ordering rule specified and no default ordering rule for attribute %s\n",
991 debug_header, ad->ad_cname.bv_val, 0);
999 static int count_key(BerElement *ber)
1006 /* Server Side Sort Control is a SEQUENCE of SEQUENCE */
1007 for ( tag = ber_first_element( ber, &len, &end );
1008 tag == LBER_SEQUENCE;
1009 tag = ber_next_element( ber, &len, end ))
1011 tag = ber_skip_tag( ber, &len );
1012 ber_skip_data( ber, len );
1020 static int build_key(
1026 struct berval matchrule = BER_BVNULL;
1027 ber_int_t reverse = 0;
1030 MatchingRule *ordering = NULL;
1031 AttributeDescription *ad = NULL;
1034 if (( tag = ber_scanf( ber, "{" )) == LBER_ERROR ) {
1035 rs->sr_text = "serverSort control: decoding error";
1036 rs->sr_err = LDAP_PROTOCOL_ERROR;
1040 if (( tag = ber_scanf( ber, "m", &attr )) == LBER_ERROR ) {
1041 rs->sr_text = "serverSort control: attribute decoding error";
1042 rs->sr_err = LDAP_PROTOCOL_ERROR;
1046 tag = ber_peek_tag( ber, &len );
1047 if ( tag == LDAP_MATCHRULE_IDENTIFIER ) {
1048 if (( tag = ber_scanf( ber, "m", &matchrule )) == LBER_ERROR ) {
1049 rs->sr_text = "serverSort control: matchrule decoding error";
1050 rs->sr_err = LDAP_PROTOCOL_ERROR;
1053 tag = ber_peek_tag( ber, &len );
1056 if ( tag == LDAP_REVERSEORDER_IDENTIFIER ) {
1057 if (( tag = ber_scanf( ber, "b", &reverse )) == LBER_ERROR ) {
1058 rs->sr_text = "serverSort control: reverse decoding error";
1059 rs->sr_err = LDAP_PROTOCOL_ERROR;
1064 if (( tag = ber_scanf( ber, "}" )) == LBER_ERROR ) {
1065 rs->sr_text = "serverSort control: decoding error";
1066 rs->sr_err = LDAP_PROTOCOL_ERROR;
1070 if ( slap_bv2ad( &attr, &ad, &text ) != LDAP_SUCCESS ) {
1072 "serverSort control: Unrecognized attribute type in sort key";
1073 Debug(LDAP_DEBUG_TRACE,
1074 "%s: Unrecognized attribute type in sort key: %s\n",
1075 debug_header, SAFESTR(attr.bv_val, "<None>"), 0);
1076 rs->sr_err = LDAP_NO_SUCH_ATTRIBUTE;
1080 /* get_ordering_rule will set sr_err and sr_text */
1081 get_ordering_rule( ad, &matchrule, rs, &ordering );
1082 if ( rs->sr_err != LDAP_SUCCESS ) {
1087 key->sk_ordering = ordering;
1088 key->sk_direction = reverse ? -1 : 1;
1093 /* Conforms to RFC4510 re: Criticality, original RFC2891 spec is broken
1094 * Also see ITS#7253 for discussion
1096 static int sss_parseCtrl(
1101 BerElementBuffer berbuf;
1108 rs->sr_err = LDAP_PROTOCOL_ERROR;
1110 if ( op->o_ctrlflag[sss_cid] > SLAP_CONTROL_IGNORED ) {
1111 rs->sr_text = "sorted results control specified multiple times";
1112 } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1113 rs->sr_text = "sorted results control value is absent";
1114 } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1115 rs->sr_text = "sorted results control value is empty";
1117 rs->sr_err = LDAP_SUCCESS;
1119 if ( rs->sr_err != LDAP_SUCCESS )
1122 op->o_ctrlflag[sss_cid] = ctrl->ldctl_iscritical ?
1123 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1125 ber = (BerElement *)&berbuf;
1126 ber_init2( ber, &ctrl->ldctl_value, 0 );
1127 i = count_key( ber );
1129 sc = op->o_tmpalloc( sizeof(sort_ctrl) +
1130 (i-1) * sizeof(sort_key), op->o_tmpmemctx );
1132 op->o_controls[sss_cid] = sc;
1134 /* peel off initial sequence */
1135 ber_scanf( ber, "{" );
1139 if ( build_key( ber, rs, &sc->sc_keys[i] ) != LDAP_SUCCESS )
1142 tag = ber_peek_tag( ber, &len );
1143 } while ( tag != LBER_DEFAULT );
1148 static int vlv_parseCtrl(
1153 BerElementBuffer berbuf;
1159 rs->sr_err = LDAP_PROTOCOL_ERROR;
1162 if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
1163 rs->sr_text = "vlv control specified multiple times";
1164 } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1165 rs->sr_text = "vlv control value is absent";
1166 } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1167 rs->sr_text = "vlv control value is empty";
1169 if ( rs->sr_text != NULL )
1172 op->o_ctrlflag[vlv_cid] = ctrl->ldctl_iscritical ?
1173 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1175 ber = (BerElement *)&berbuf;
1176 ber_init2( ber, &ctrl->ldctl_value, 0 );
1178 rs->sr_err = LDAP_PROTOCOL_ERROR;
1180 tag = ber_scanf( ber, "{ii", &vc2.vc_before, &vc2.vc_after );
1181 if ( tag == LBER_ERROR ) {
1185 tag = ber_peek_tag( ber, &len );
1186 if ( tag == LDAP_VLVBYINDEX_IDENTIFIER ) {
1187 tag = ber_scanf( ber, "{ii}", &vc2.vc_offset, &vc2.vc_count );
1188 if ( tag == LBER_ERROR )
1190 BER_BVZERO( &vc2.vc_value );
1191 } else if ( tag == LDAP_VLVBYVALUE_IDENTIFIER ) {
1192 tag = ber_scanf( ber, "m", &vc2.vc_value );
1193 if ( tag == LBER_ERROR || BER_BVISNULL( &vc2.vc_value ))
1198 tag = ber_peek_tag( ber, &len );
1199 if ( tag == LDAP_VLVCONTEXT_IDENTIFIER ) {
1201 tag = ber_scanf( ber, "m", &bv );
1202 if ( tag == LBER_ERROR || bv.bv_len != sizeof(vc2.vc_context))
1204 AC_MEMCPY( &vc2.vc_context, bv.bv_val, bv.bv_len );
1209 vc = op->o_tmpalloc( sizeof(vlv_ctrl), op->o_tmpmemctx );
1211 op->o_controls[vlv_cid] = vc;
1212 rs->sr_err = LDAP_SUCCESS;
1217 static int sssvlv_connection_destroy( BackendDB *be, Connection *conn )
1219 slap_overinst *on = (slap_overinst *)be->bd_info;
1220 sssvlv_info *si = on->on_bi.bi_private;
1222 if ( sort_conns[conn->c_conn_idx] ) {
1223 free_sort_ops( conn, sort_conns[conn->c_conn_idx], si->svi_max_percon );
1226 return LDAP_SUCCESS;
1229 static int sssvlv_db_open(
1233 slap_overinst *on = (slap_overinst *)be->bd_info;
1234 sssvlv_info *si = on->on_bi.bi_private;
1238 /* If not set, default to 1/2 of available threads */
1240 si->svi_max = connection_pool_max / 2;
1242 if ( dtblsize && !sort_conns ) {
1243 ldap_pvt_thread_mutex_init( &sort_conns_mutex );
1244 /* accommodate for c_conn_idx == -1 */
1245 sort_conns = ch_calloc( dtblsize + 1, sizeof(sort_op **) );
1246 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1247 sort_conns[conn_index] = ch_calloc( si->svi_max_percon, sizeof(sort_op *) );
1252 rc = overlay_register_control( be, LDAP_CONTROL_SORTREQUEST );
1253 if ( rc == LDAP_SUCCESS )
1254 rc = overlay_register_control( be, LDAP_CONTROL_VLVREQUEST );
1258 static ConfigTable sssvlv_cfg[] = {
1259 { "sssvlv-max", "num",
1260 2, 2, 0, ARG_INT|ARG_OFFSET,
1261 (void *)offsetof(sssvlv_info, svi_max),
1262 "( OLcfgOvAt:21.1 NAME 'olcSssVlvMax' "
1263 "DESC 'Maximum number of concurrent Sort requests' "
1264 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1265 { "sssvlv-maxkeys", "num",
1266 2, 2, 0, ARG_INT|ARG_OFFSET,
1267 (void *)offsetof(sssvlv_info, svi_max_keys),
1268 "( OLcfgOvAt:21.2 NAME 'olcSssVlvMaxKeys' "
1269 "DESC 'Maximum number of Keys in a Sort request' "
1270 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1271 { "sssvlv-maxperconn", "num",
1272 2, 2, 0, ARG_INT|ARG_OFFSET,
1273 (void *)offsetof(sssvlv_info, svi_max_percon),
1274 "( OLcfgOvAt:21.3 NAME 'olcSssVlvMaxPerConn' "
1275 "DESC 'Maximum number of concurrent paged search requests per connection' "
1276 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1277 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1280 static ConfigOCs sssvlv_ocs[] = {
1281 { "( OLcfgOvOc:21.1 "
1282 "NAME 'olcSssVlvConfig' "
1283 "DESC 'SSS VLV configuration' "
1284 "SUP olcOverlayConfig "
1285 "MAY ( olcSssVlvMax $ olcSssVlvMaxKeys ) )",
1286 Cft_Overlay, sssvlv_cfg, NULL, NULL },
1290 static int sssvlv_db_init(
1294 slap_overinst *on = (slap_overinst *)be->bd_info;
1297 if ( ov_count == 0 ) {
1300 rc = register_supported_control2( LDAP_CONTROL_SORTREQUEST,
1306 if ( rc != LDAP_SUCCESS ) {
1307 Debug( LDAP_DEBUG_ANY, "Failed to register Sort Request control '%s' (%d)\n",
1308 LDAP_CONTROL_SORTREQUEST, rc, 0 );
1312 rc = register_supported_control2( LDAP_CONTROL_VLVREQUEST,
1318 if ( rc != LDAP_SUCCESS ) {
1319 Debug( LDAP_DEBUG_ANY, "Failed to register VLV Request control '%s' (%d)\n",
1320 LDAP_CONTROL_VLVREQUEST, rc, 0 );
1321 #ifdef SLAP_CONFIG_DELETE
1322 overlay_unregister_control( be, LDAP_CONTROL_SORTREQUEST );
1323 unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1324 #endif /* SLAP_CONFIG_DELETE */
1329 si = (sssvlv_info *)ch_malloc(sizeof(sssvlv_info));
1330 on->on_bi.bi_private = si;
1334 si->svi_max_keys = SSSVLV_DEFAULT_MAX_KEYS;
1335 si->svi_max_percon = SSSVLV_DEFAULT_MAX_REQUEST_PER_CONN;
1339 return LDAP_SUCCESS;
1342 static int sssvlv_db_destroy(
1346 slap_overinst *on = (slap_overinst *)be->bd_info;
1347 sssvlv_info *si = (sssvlv_info *)on->on_bi.bi_private;
1351 if ( !ov_count && sort_conns) {
1353 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1354 ch_free(sort_conns[conn_index]);
1356 ch_free(sort_conns);
1357 ldap_pvt_thread_mutex_destroy( &sort_conns_mutex );
1360 #ifdef SLAP_CONFIG_DELETE
1361 overlay_unregister_control( be, LDAP_CONTROL_SORTREQUEST );
1362 overlay_unregister_control( be, LDAP_CONTROL_VLVREQUEST );
1363 if ( ov_count == 0 ) {
1364 unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1365 unregister_supported_control( LDAP_CONTROL_VLVREQUEST );
1367 #endif /* SLAP_CONFIG_DELETE */
1371 on->on_bi.bi_private = NULL;
1373 return LDAP_SUCCESS;
1376 static slap_overinst sssvlv;
1378 int sssvlv_initialize()
1382 sssvlv.on_bi.bi_type = "sssvlv";
1383 sssvlv.on_bi.bi_db_init = sssvlv_db_init;
1384 sssvlv.on_bi.bi_db_destroy = sssvlv_db_destroy;
1385 sssvlv.on_bi.bi_db_open = sssvlv_db_open;
1386 sssvlv.on_bi.bi_connection_destroy = sssvlv_connection_destroy;
1387 sssvlv.on_bi.bi_op_search = sssvlv_op_search;
1389 sssvlv.on_bi.bi_cf_ocs = sssvlv_ocs;
1391 rc = config_register_schema( sssvlv_cfg, sssvlv_ocs );
1395 rc = overlay_register( &sssvlv );
1396 if ( rc != LDAP_SUCCESS ) {
1397 Debug( LDAP_DEBUG_ANY, "Failed to register server side sort overlay\n", 0, 0, 0 );
1403 #if SLAPD_OVER_SSSVLV == SLAPD_MOD_DYNAMIC
1404 int init_module( int argc, char *argv[])
1406 return sssvlv_initialize();
1410 #endif /* SLAPD_OVER_SSSVLV */