1 /* sssvlv.c - server side sort / virtual list view */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2009-2010 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;
167 assert( sort_conns[sn1->sn_conn] && sort_conns[sn1->sn_conn][sn1->sn_session]
168 && sort_conns[sn1->sn_conn][sn1->sn_session]->so_ctrl );
169 sort_ctrl *sc = sort_conns[sn1->sn_conn][sn1->sn_session]->so_ctrl;
173 for ( i=0; cmp == 0 && i<sc->sc_nkeys; i++ ) {
174 if ( BER_BVISNULL( &sn1->sn_vals[i] )) {
175 if ( BER_BVISNULL( &sn2->sn_vals[i] ))
178 cmp = sc->sc_keys[i].sk_direction;
179 } else if ( BER_BVISNULL( &sn2->sn_vals[i] )) {
180 cmp = sc->sc_keys[i].sk_direction * -1;
182 mr = sc->sc_keys[i].sk_ordering;
183 mr->smr_match( &cmp, 0, mr->smr_syntax, mr,
184 &sn1->sn_vals[i], &sn2->sn_vals[i] );
186 cmp *= sc->sc_keys[i].sk_direction;
192 static int node_insert( const void *val1, const void *val2 )
194 /* Never return equal so that new entries are always inserted */
195 return node_cmp( val1, val2 ) < 0 ? -1 : 1;
198 static int pack_vlv_response_control(
202 LDAPControl **ctrlsp )
205 BerElementBuffer berbuf;
206 BerElement *ber = (BerElement *)&berbuf;
207 struct berval cookie, bv;
210 ber_init2( ber, NULL, LBER_USE_DER );
211 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
213 rc = ber_printf( ber, "{iie", so->so_vlv_target, so->so_nentries,
216 if ( rc != -1 && so->so_vcontext ) {
217 cookie.bv_val = (char *)&so->so_vcontext;
218 cookie.bv_len = sizeof(so->so_vcontext);
219 rc = ber_printf( ber, "tO", LDAP_VLVCONTEXT_IDENTIFIER, &cookie );
223 rc = ber_printf( ber, "}" );
227 rc = ber_flatten2( ber, &bv, 0 );
231 ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
232 bv.bv_len, op->o_tmpmemctx );
233 ctrl->ldctl_oid = LDAP_CONTROL_VLVRESPONSE;
234 ctrl->ldctl_iscritical = 0;
235 ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
236 ctrl->ldctl_value.bv_len = bv.bv_len;
237 AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
241 rs->sr_err = LDAP_OTHER;
249 static int pack_pagedresult_response_control(
253 LDAPControl **ctrlsp )
256 BerElementBuffer berbuf;
257 BerElement *ber = (BerElement *)&berbuf;
258 PagedResultsCookie resp_cookie;
259 struct berval cookie, bv;
262 ber_init2( ber, NULL, LBER_USE_DER );
263 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
265 if ( so->so_nentries > 0 ) {
266 resp_cookie = ( PagedResultsCookie )so->so_tree;
267 cookie.bv_len = sizeof( PagedResultsCookie );
268 cookie.bv_val = (char *)&resp_cookie;
270 resp_cookie = ( PagedResultsCookie )0;
271 BER_BVZERO( &cookie );
274 op->o_conn->c_pagedresults_state.ps_cookie = resp_cookie;
275 op->o_conn->c_pagedresults_state.ps_count
276 = ((PagedResultsState *)op->o_pagedresults_state)->ps_count
279 rc = ber_printf( ber, "{iO}", so->so_nentries, &cookie );
281 rc = ber_flatten2( ber, &bv, 0 );
285 ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
286 bv.bv_len, op->o_tmpmemctx );
287 ctrl->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
288 ctrl->ldctl_iscritical = 0;
289 ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
290 ctrl->ldctl_value.bv_len = bv.bv_len;
291 AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
295 rs->sr_err = LDAP_OTHER;
303 static int pack_sss_response_control(
306 LDAPControl **ctrlsp )
309 BerElementBuffer berbuf;
310 BerElement *ber = (BerElement *)&berbuf;
314 ber_init2( ber, NULL, LBER_USE_DER );
315 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
317 /* Pack error code */
318 rc = ber_printf(ber, "{e}", rs->sr_err);
321 rc = ber_flatten2( ber, &bv, 0 );
324 ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
325 bv.bv_len, op->o_tmpmemctx );
326 ctrl->ldctl_oid = LDAP_CONTROL_SORTRESPONSE;
327 ctrl->ldctl_iscritical = 0;
328 ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
329 ctrl->ldctl_value.bv_len = bv.bv_len;
330 AC_MEMCPY( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
334 rs->sr_err = LDAP_OTHER;
342 /* Return the session id or -1 if unknown */
343 static int find_session_by_context(
346 unsigned long vc_context,
347 PagedResultsCookie ps_cookie )
350 for(sess_id = 0; sess_id < svi_max_percon; sess_id++) {
351 if( sort_conns[conn_id] && sort_conns[conn_id][sess_id] &&
352 ( sort_conns[conn_id][sess_id]->so_vcontext == vc_context ||
353 (PagedResultsCookie) sort_conns[conn_id][sess_id]->so_tree == ps_cookie ) )
359 static int find_next_session(
364 assert(sort_conns[conn_id] != NULL);
365 for(sess_id = 0; sess_id < svi_max_percon; sess_id++) {
366 if(!sort_conns[conn_id][sess_id]) {
370 if (sess_id >= svi_max_percon) {
377 static void free_sort_op( Connection *conn, sort_op *so )
380 PagedResultsCookie ps_cookie = (PagedResultsCookie) so->so_tree;
382 tavl_free( so->so_tree, ch_free );
386 ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
387 sess_id = find_session_by_context( so->so_info->svi_max_percon, conn->c_conn_idx, so->so_vcontext, ps_cookie );
388 sort_conns[conn->c_conn_idx][sess_id] = NULL;
389 so->so_info->svi_num--;
390 ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
395 static void free_sort_ops( Connection *conn, sort_op **sos, int svi_max_percon )
400 for( sess_id = 0; sess_id < svi_max_percon ; sess_id++ ) {
401 so = sort_conns[conn->c_conn_idx][sess_id];
403 free_sort_op( conn, so );
404 sort_conns[conn->c_conn_idx][sess_id] = NULL;
409 static void send_list(
414 Avlnode *cur_node, *tmp_node;
415 vlv_ctrl *vc = op->o_controls[vlv_cid];
419 LDAPControl *ctrls[2];
421 /* FIXME: it may be better to just flatten the tree into
422 * an array before doing all of this...
425 /* Are we just counting an offset? */
426 if ( BER_BVISNULL( &vc->vc_value )) {
427 if ( vc->vc_offset == vc->vc_count ) {
428 /* wants the last entry in the list */
429 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
430 so->so_vlv_target = so->so_nentries;
431 } else if ( vc->vc_offset == 1 ) {
432 /* wants the first entry in the list */
433 cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
434 so->so_vlv_target = 1;
437 /* Just iterate to the right spot */
438 if ( vc->vc_count && vc->vc_count != so->so_nentries ) {
439 if ( vc->vc_offset > vc->vc_count )
441 target = so->so_nentries * vc->vc_offset / vc->vc_count;
443 if ( vc->vc_offset > so->so_nentries ) {
445 so->so_vlv_rc = LDAP_VLV_RANGE_ERROR;
446 pack_vlv_response_control( op, rs, so, ctrls );
448 slap_add_ctrls( op, rs, ctrls );
449 rs->sr_err = LDAP_VLV_ERROR;
452 target = vc->vc_offset;
454 so->so_vlv_target = target;
455 /* Start at left and go right, or start at right and go left? */
456 if ( target < so->so_nentries / 2 ) {
457 cur_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
458 dir = TAVL_DIR_RIGHT;
460 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
462 target = so->so_nentries - target + 1;
464 for ( i=1; i<target; i++ )
465 cur_node = tavl_next( cur_node, dir );
468 /* we're looking for a specific value */
469 sort_ctrl *sc = so->so_ctrl;
470 MatchingRule *mr = sc->sc_keys[0].sk_ordering;
474 if ( mr->smr_normalize ) {
475 rc = mr->smr_normalize( SLAP_MR_VALUE_OF_SYNTAX,
476 mr->smr_syntax, mr, &vc->vc_value, &bv, op->o_tmpmemctx );
478 so->so_vlv_rc = LDAP_INAPPROPRIATE_MATCHING;
479 pack_vlv_response_control( op, rs, so, ctrls );
481 slap_add_ctrls( op, rs, ctrls );
482 rs->sr_err = LDAP_VLV_ERROR;
489 sn = op->o_tmpalloc( sizeof(sort_node) +
490 sc->sc_nkeys * sizeof(struct berval), op->o_tmpmemctx );
491 sn->sn_vals = (struct berval *)(sn+1);
492 sn->sn_conn = op->o_conn->c_conn_idx;
493 sn->sn_session = find_session_by_context( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, vc->vc_context, NO_PS_COOKIE );
495 for (i=1; i<sc->sc_nkeys; i++) {
496 BER_BVZERO( &sn->sn_vals[i] );
498 cur_node = tavl_find3( so->so_tree, sn, node_cmp, &j );
499 /* didn't find >= match */
502 op->o_tmpfree( sn, op->o_tmpmemctx );
505 so->so_vlv_target = so->so_nentries + 1;
507 sort_node *sn = so->so_tree->avl_data;
508 /* start from the left or the right side? */
509 mr->smr_match( &i, 0, mr->smr_syntax, mr, &bv, &sn->sn_vals[0] );
511 tmp_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
514 tmp_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
515 dir = TAVL_DIR_RIGHT;
517 for (i=0; tmp_node != cur_node;
518 tmp_node = tavl_next( tmp_node, dir ), i++);
519 so->so_vlv_target = i;
521 if ( bv.bv_val != vc->vc_value.bv_val )
522 op->o_tmpfree( bv.bv_val, op->o_tmpmemctx );
526 cur_node = tavl_end(so->so_tree, TAVL_DIR_RIGHT);
530 for ( ; i<vc->vc_before; i++ ) {
531 tmp_node = tavl_next( cur_node, TAVL_DIR_LEFT );
532 if ( !tmp_node ) break;
535 j = i + vc->vc_after + 1;
537 for ( i=0; i<j; i++ ) {
538 sort_node *sn = cur_node->avl_data;
540 if ( slapd_shutdown ) break;
542 op->o_bd = select_backend( &sn->sn_dn, 0 );
544 rc = be_entry_get_rw( op, &sn->sn_dn, NULL, NULL, 0, &e );
546 if ( e && rc == LDAP_SUCCESS ) {
548 rs->sr_flags = REP_ENTRY_MUSTRELEASE;
549 rs->sr_err = send_search_entry( op, rs );
550 if ( rs->sr_err == LDAP_UNAVAILABLE )
553 cur_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
554 if ( !cur_node ) break;
556 so->so_vlv_rc = LDAP_SUCCESS;
561 static void send_page( Operation *op, SlapReply *rs, sort_op *so )
563 Avlnode *cur_node = so->so_tree;
564 Avlnode *next_node = NULL;
565 BackendDB *be = op->o_bd;
569 while ( cur_node && rs->sr_nentries < so->so_page_size ) {
570 sort_node *sn = cur_node->avl_data;
572 if ( slapd_shutdown ) break;
574 next_node = tavl_next( cur_node, TAVL_DIR_RIGHT );
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 ch_free( cur_node->avl_data );
581 ber_memfree( cur_node );
583 cur_node = next_node;
586 if ( e && rc == LDAP_SUCCESS ) {
588 rs->sr_flags = REP_ENTRY_MUSTRELEASE;
589 rs->sr_err = send_search_entry( op, rs );
590 if ( rs->sr_err == LDAP_UNAVAILABLE )
595 /* Set the first entry to send for the next page */
596 so->so_tree = next_node;
601 static void send_entry(
606 Debug(LDAP_DEBUG_TRACE,
607 "%s: response control: status=%d, text=%s\n",
608 debug_header, rs->sr_err, SAFESTR(rs->sr_text, "<None>"));
613 /* RFC 2891: If critical then send the entries iff they were
614 * succesfully sorted. If non-critical send all entries
615 * whether they were sorted or not.
617 if ( (op->o_ctrlflag[sss_cid] != SLAP_CONTROL_CRITICAL) ||
618 (rs->sr_err == LDAP_SUCCESS) )
620 if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
621 send_list( op, rs, so );
623 /* Get the first node to send */
624 Avlnode *start_node = tavl_end(so->so_tree, TAVL_DIR_LEFT);
625 so->so_tree = start_node;
627 if ( so->so_paged <= SLAP_CONTROL_IGNORED ) {
628 /* Not paged result search. Send all entries.
629 * Set the page size to the number of entries
630 * so that send_page() will send all entries.
632 so->so_page_size = so->so_nentries;
635 send_page( op, rs, so );
640 static void send_result(
645 LDAPControl *ctrls[3];
648 rc = pack_sss_response_control( op, rs, ctrls );
649 if ( rc == LDAP_SUCCESS ) {
652 if ( so->so_paged > SLAP_CONTROL_IGNORED ) {
653 rc = pack_pagedresult_response_control( op, rs, so, ctrls+1 );
654 } else if ( so->so_vlv > SLAP_CONTROL_IGNORED ) {
655 rc = pack_vlv_response_control( op, rs, so, ctrls+1 );
657 if ( rc == LDAP_SUCCESS )
662 if ( ctrls[0] != NULL )
663 slap_add_ctrls( op, rs, ctrls );
664 send_ldap_result( op, rs );
666 if ( so->so_tree == NULL ) {
667 /* Search finished, so clean up */
668 free_sort_op( op->o_conn, so );
672 static int sssvlv_op_response(
676 sort_ctrl *sc = op->o_controls[sss_cid];
677 sort_op *so = op->o_callback->sc_private;
679 if ( rs->sr_type == REP_SEARCH ) {
686 len = sizeof(sort_node) + sc->sc_nkeys * sizeof(struct berval) +
687 rs->sr_entry->e_nname.bv_len + 1;
688 sn = op->o_tmpalloc( len, op->o_tmpmemctx );
689 sn->sn_vals = (struct berval *)(sn+1);
691 /* Build tmp list of key values */
692 for ( i=0; i<sc->sc_nkeys; i++ ) {
693 Attribute *a = attr_find( rs->sr_entry->e_attrs,
694 sc->sc_keys[i].sk_ad );
696 if ( a->a_numvals > 1 ) {
697 bv = select_value( a, &sc->sc_keys[i] );
701 sn->sn_vals[i] = *bv;
702 len += bv->bv_len + 1;
704 BER_BVZERO( &sn->sn_vals[i] );
708 /* Now dup into regular memory */
709 sn2 = ch_malloc( len );
710 sn2->sn_vals = (struct berval *)(sn2+1);
711 AC_MEMCPY( sn2->sn_vals, sn->sn_vals,
712 sc->sc_nkeys * sizeof(struct berval));
714 ptr = (char *)(sn2->sn_vals + sc->sc_nkeys);
715 sn2->sn_dn.bv_val = ptr;
716 sn2->sn_dn.bv_len = rs->sr_entry->e_nname.bv_len;
717 AC_MEMCPY( ptr, rs->sr_entry->e_nname.bv_val,
718 rs->sr_entry->e_nname.bv_len );
719 ptr += rs->sr_entry->e_nname.bv_len;
721 for ( i=0; i<sc->sc_nkeys; i++ ) {
722 if ( !BER_BVISNULL( &sn2->sn_vals[i] )) {
723 AC_MEMCPY(ptr, sn2->sn_vals[i].bv_val, sn2->sn_vals[i].bv_len);
724 sn2->sn_vals[i].bv_val = ptr;
725 ptr += sn2->sn_vals[i].bv_len;
729 op->o_tmpfree( sn, op->o_tmpmemctx );
731 sn->sn_conn = op->o_conn->c_conn_idx;
732 sn->sn_session = find_session_by_context( so->so_info->svi_max_percon, op->o_conn->c_conn_idx, so->so_vcontext, (PagedResultsCookie) so->so_tree );
734 /* Insert into the AVL tree */
735 tavl_insert(&(so->so_tree), sn, node_insert, avl_dup_error);
739 /* Collected the keys so that they can be sorted. Thus, stop
740 * the entry from propagating.
742 rs->sr_err = LDAP_SUCCESS;
744 else if ( rs->sr_type == REP_RESULT ) {
745 /* Remove serversort response callback.
746 * We don't want the entries that we are about to send to be
747 * processed by serversort response again.
749 if ( op->o_callback->sc_response == sssvlv_op_response ) {
750 op->o_callback = op->o_callback->sc_next;
753 send_entry( op, rs, so );
754 send_result( op, rs, so );
760 static int sssvlv_op_search(
764 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
765 sssvlv_info *si = on->on_bi.bi_private;
766 int rc = SLAP_CB_CONTINUE;
768 sort_op *so = NULL, so2;
770 PagedResultsState *ps;
774 if ( op->o_ctrlflag[sss_cid] <= SLAP_CONTROL_IGNORED ) {
775 if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
776 LDAPControl *ctrls[2];
778 so2.so_vlv_target = 0;
780 so2.so_vlv_rc = LDAP_VLV_SSS_MISSING;
781 so2.so_vlv = op->o_ctrlflag[vlv_cid];
782 rc = pack_vlv_response_control( op, rs, &so2, ctrls );
783 if ( rc == LDAP_SUCCESS ) {
785 slap_add_ctrls( op, rs, ctrls );
787 rs->sr_err = LDAP_VLV_ERROR;
788 rs->sr_text = "Sort control is required with VLV";
791 /* Not server side sort so just continue */
792 return SLAP_CB_CONTINUE;
795 Debug(LDAP_DEBUG_TRACE,
796 "==> sssvlv_search: <%s> %s, control flag: %d\n",
797 op->o_req_dn.bv_val, op->ors_filterstr.bv_val,
798 op->o_ctrlflag[sss_cid]);
800 sc = op->o_controls[sss_cid];
801 if ( sc->sc_nkeys > si->svi_max_keys ) {
802 rs->sr_text = "Too many sort keys";
803 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
807 ps = ( op->o_pagedresults > SLAP_CONTROL_IGNORED ) ?
808 (PagedResultsState*)(op->o_pagedresults_state) : NULL;
809 vc = op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ?
810 op->o_controls[vlv_cid] : NULL;
813 rs->sr_text = "VLV incompatible with PagedResults";
814 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
819 ldap_pvt_thread_mutex_lock( &sort_conns_mutex );
820 /* Is there already a sort running on this conn? */
821 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 );
822 if ( sess_id >= 0 ) {
823 so = sort_conns[op->o_conn->c_conn_idx][sess_id];
824 /* Is it a continuation of a VLV search? */
825 if ( !vc || so->so_vlv <= SLAP_CONTROL_IGNORED ||
826 vc->vc_context != so->so_vcontext ) {
827 /* Is it a continuation of a paged search? */
828 if ( !ps || so->so_paged <= SLAP_CONTROL_IGNORED ||
829 op->o_conn->c_pagedresults_state.ps_cookie != ps->ps_cookie ) {
831 } else if ( !ps->ps_size ) {
832 /* Abandoning current request */
835 rs->sr_err = LDAP_SUCCESS;
838 if (( vc && so->so_paged > SLAP_CONTROL_IGNORED ) ||
839 ( ps && so->so_vlv > SLAP_CONTROL_IGNORED )) {
840 /* changed from paged to vlv or vice versa, abandon */
843 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
845 /* Are there too many running overall? */
846 } else if ( si->svi_num >= si->svi_max ) {
848 } else if ( ( sess_id = find_next_session(si->svi_max_percon, op->o_conn->c_conn_idx ) ) < 0 ) {
851 /* OK, this connection now has a sort running */
853 sort_conns[op->o_conn->c_conn_idx][sess_id] = &so2;
854 sort_conns[op->o_conn->c_conn_idx][sess_id]->so_session = sess_id;
856 ldap_pvt_thread_mutex_unlock( &sort_conns_mutex );
858 /* are we continuing a VLV search? */
859 if ( so && vc && vc->vc_context ) {
861 send_list( op, rs, so );
862 send_result( op, rs, so );
864 /* are we continuing a paged search? */
865 } else if ( so && ps && ps->ps_cookie ) {
867 send_page( op, rs, so );
868 send_result( op, rs, so );
871 slap_callback *cb = op->o_tmpalloc( sizeof(slap_callback),
873 /* Install serversort response callback to handle a new search */
875 so = ch_calloc( 1, sizeof(sort_op));
877 so = op->o_tmpcalloc( 1, sizeof(sort_op), op->o_tmpmemctx );
879 sort_conns[op->o_conn->c_conn_idx][sess_id] = so;
881 cb->sc_cleanup = NULL;
882 cb->sc_response = sssvlv_op_response;
883 cb->sc_next = op->o_callback;
890 so->so_paged = op->o_pagedresults;
891 so->so_page_size = ps->ps_size;
892 op->o_pagedresults = SLAP_CONTROL_IGNORED;
895 so->so_page_size = 0;
897 so->so_vlv = op->o_ctrlflag[vlv_cid];
898 so->so_vlv_target = 0;
901 so->so_vlv = SLAP_CONTROL_NONE;
904 so->so_session = sess_id;
905 so->so_vlv = op->o_ctrlflag[vlv_cid];
906 so->so_vcontext = (unsigned long)so;
912 if ( so && !so->so_nentries ) {
913 free_sort_op( op->o_conn, so );
915 rs->sr_text = "Other sort requests already in progress";
916 rs->sr_err = LDAP_BUSY;
920 send_ldap_result( op, rs );
926 static int get_ordering_rule(
927 AttributeDescription *ad,
928 struct berval *matchrule,
930 MatchingRule **ordering )
934 if ( matchrule && matchrule->bv_val ) {
935 mr = mr_find( matchrule->bv_val );
937 rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
938 rs->sr_text = "serverSort control: No ordering rule";
939 Debug(LDAP_DEBUG_TRACE, "%s: no ordering rule function for %s\n",
940 debug_header, matchrule->bv_val, 0);
944 mr = ad->ad_type->sat_ordering;
946 rs->sr_err = LDAP_INAPPROPRIATE_MATCHING;
947 rs->sr_text = "serverSort control: No ordering rule";
948 Debug(LDAP_DEBUG_TRACE,
949 "%s: no ordering rule specified and no default ordering rule for attribute %s\n",
950 debug_header, ad->ad_cname.bv_val, 0);
958 static int count_key(BerElement *ber)
965 /* Server Side Sort Control is a SEQUENCE of SEQUENCE */
966 for ( tag = ber_first_element( ber, &len, &end );
967 tag == LBER_SEQUENCE;
968 tag = ber_next_element( ber, &len, end ))
970 tag = ber_skip_tag( ber, &len );
971 ber_skip_data( ber, len );
979 static int build_key(
985 struct berval matchrule = BER_BVNULL;
986 ber_int_t reverse = 0;
989 MatchingRule *ordering = NULL;
990 AttributeDescription *ad = NULL;
993 if (( tag = ber_scanf( ber, "{" )) == LBER_ERROR ) {
994 rs->sr_text = "serverSort control: decoding error";
995 rs->sr_err = LDAP_PROTOCOL_ERROR;
999 if (( tag = ber_scanf( ber, "m", &attr )) == LBER_ERROR ) {
1000 rs->sr_text = "serverSort control: attribute decoding error";
1001 rs->sr_err = LDAP_PROTOCOL_ERROR;
1005 tag = ber_peek_tag( ber, &len );
1006 if ( tag == LDAP_MATCHRULE_IDENTIFIER ) {
1007 if (( tag = ber_scanf( ber, "m", &matchrule )) == LBER_ERROR ) {
1008 rs->sr_text = "serverSort control: matchrule decoding error";
1009 rs->sr_err = LDAP_PROTOCOL_ERROR;
1012 tag = ber_peek_tag( ber, &len );
1015 if ( tag == LDAP_REVERSEORDER_IDENTIFIER ) {
1016 if (( tag = ber_scanf( ber, "b", &reverse )) == LBER_ERROR ) {
1017 rs->sr_text = "serverSort control: reverse decoding error";
1018 rs->sr_err = LDAP_PROTOCOL_ERROR;
1023 if (( tag = ber_scanf( ber, "}" )) == LBER_ERROR ) {
1024 rs->sr_text = "serverSort control: decoding error";
1025 rs->sr_err = LDAP_PROTOCOL_ERROR;
1029 if ( slap_bv2ad( &attr, &ad, &text ) != LDAP_SUCCESS ) {
1031 "serverSort control: Unrecognized attribute type in sort key";
1032 Debug(LDAP_DEBUG_TRACE,
1033 "%s: Unrecognized attribute type in sort key: %s\n",
1034 debug_header, SAFESTR(attr.bv_val, "<None>"), 0);
1035 rs->sr_err = LDAP_NO_SUCH_ATTRIBUTE;
1039 /* get_ordering_rule will set sr_err and sr_text */
1040 get_ordering_rule( ad, &matchrule, rs, &ordering );
1041 if ( rs->sr_err != LDAP_SUCCESS ) {
1046 key->sk_ordering = ordering;
1047 key->sk_direction = reverse ? -1 : 1;
1052 static int sss_parseCtrl(
1057 BerElementBuffer berbuf;
1064 rs->sr_err = LDAP_PROTOCOL_ERROR;
1066 if ( op->o_ctrlflag[sss_cid] > SLAP_CONTROL_IGNORED ) {
1067 rs->sr_text = "sorted results control specified multiple times";
1068 } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1069 rs->sr_text = "sorted results control value is absent";
1070 } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1071 rs->sr_text = "sorted results control value is empty";
1073 rs->sr_err = LDAP_SUCCESS;
1075 if ( rs->sr_err != LDAP_SUCCESS )
1078 op->o_ctrlflag[sss_cid] = ctrl->ldctl_iscritical ?
1079 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1081 ber = (BerElement *)&berbuf;
1082 ber_init2( ber, &ctrl->ldctl_value, 0 );
1083 i = count_key( ber );
1085 sc = op->o_tmpalloc( sizeof(sort_ctrl) +
1086 (i-1) * sizeof(sort_key), op->o_tmpmemctx );
1088 op->o_controls[sss_cid] = sc;
1090 /* peel off initial sequence */
1091 ber_scanf( ber, "{" );
1095 if ( build_key( ber, rs, &sc->sc_keys[i] ) != LDAP_SUCCESS )
1098 tag = ber_peek_tag( ber, &len );
1099 } while ( tag != LBER_DEFAULT );
1104 static int vlv_parseCtrl(
1109 BerElementBuffer berbuf;
1115 rs->sr_err = LDAP_PROTOCOL_ERROR;
1118 if ( op->o_ctrlflag[vlv_cid] > SLAP_CONTROL_IGNORED ) {
1119 rs->sr_text = "vlv control specified multiple times";
1120 } else if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
1121 rs->sr_text = "vlv control value is absent";
1122 } else if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1123 rs->sr_text = "vlv control value is empty";
1125 if ( rs->sr_text != NULL )
1128 op->o_ctrlflag[vlv_cid] = ctrl->ldctl_iscritical ?
1129 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
1131 ber = (BerElement *)&berbuf;
1132 ber_init2( ber, &ctrl->ldctl_value, 0 );
1134 rs->sr_err = LDAP_PROTOCOL_ERROR;
1136 tag = ber_scanf( ber, "{ii", &vc2.vc_before, &vc2.vc_after );
1137 if ( tag == LBER_ERROR ) {
1141 tag = ber_peek_tag( ber, &len );
1142 if ( tag == LDAP_VLVBYINDEX_IDENTIFIER ) {
1143 tag = ber_scanf( ber, "{ii}", &vc2.vc_offset, &vc2.vc_count );
1144 if ( tag == LBER_ERROR )
1146 BER_BVZERO( &vc2.vc_value );
1147 } else if ( tag == LDAP_VLVBYVALUE_IDENTIFIER ) {
1148 tag = ber_scanf( ber, "m", &vc2.vc_value );
1149 if ( tag == LBER_ERROR || BER_BVISNULL( &vc2.vc_value ))
1154 tag = ber_peek_tag( ber, &len );
1155 if ( tag == LDAP_VLVCONTEXT_IDENTIFIER ) {
1157 tag = ber_scanf( ber, "m", &bv );
1158 if ( tag == LBER_ERROR || bv.bv_len != sizeof(vc2.vc_context))
1160 AC_MEMCPY( &vc2.vc_context, bv.bv_val, bv.bv_len );
1165 vc = op->o_tmpalloc( sizeof(vlv_ctrl), op->o_tmpmemctx );
1167 op->o_controls[vlv_cid] = vc;
1168 rs->sr_err = LDAP_SUCCESS;
1173 static int sssvlv_connection_destroy( BackendDB *be, Connection *conn )
1175 slap_overinst *on = (slap_overinst *)be->bd_info;
1176 sssvlv_info *si = on->on_bi.bi_private;
1178 if ( sort_conns[conn->c_conn_idx] ) {
1179 free_sort_ops( conn, sort_conns[conn->c_conn_idx], si->svi_max_percon );
1182 return LDAP_SUCCESS;
1185 static int sssvlv_db_open(
1189 slap_overinst *on = (slap_overinst *)be->bd_info;
1190 sssvlv_info *si = on->on_bi.bi_private;
1194 /* If not set, default to 1/2 of available threads */
1196 si->svi_max = connection_pool_max / 2;
1198 if ( dtblsize && !sort_conns ) {
1199 ldap_pvt_thread_mutex_init( &sort_conns_mutex );
1200 /* accommodate for c_conn_idx == -1 */
1201 sort_conns = ch_calloc( dtblsize + 1, sizeof(sort_op **) );
1202 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1203 sort_conns[conn_index] = ch_calloc( si->svi_max_percon, sizeof(sort_op *) );
1208 rc = overlay_register_control( be, LDAP_CONTROL_SORTREQUEST );
1209 if ( rc == LDAP_SUCCESS )
1210 rc = overlay_register_control( be, LDAP_CONTROL_VLVREQUEST );
1214 static ConfigTable sssvlv_cfg[] = {
1215 { "sssvlv-max", "num",
1216 2, 2, 0, ARG_INT|ARG_OFFSET,
1217 (void *)offsetof(sssvlv_info, svi_max),
1218 "( OLcfgOvAt:21.1 NAME 'olcSssVlvMax' "
1219 "DESC 'Maximum number of concurrent Sort requests' "
1220 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1221 { "sssvlv-maxkeys", "num",
1222 2, 2, 0, ARG_INT|ARG_OFFSET,
1223 (void *)offsetof(sssvlv_info, svi_max_keys),
1224 "( OLcfgOvAt:21.2 NAME 'olcSssVlvMaxKeys' "
1225 "DESC 'Maximum number of Keys in a Sort request' "
1226 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1227 { "sssvlv-maxpercon", "num",
1228 2, 2, 0, ARG_INT|ARG_OFFSET,
1229 (void *)offsetof(sssvlv_info, svi_max_percon),
1230 "( OLcfgOvAt:21.3 NAME 'olcSssVlvMaxPerConn' "
1231 "DESC 'Maximum number of concurrent paged search requests per connection' "
1232 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
1233 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1236 static ConfigOCs sssvlv_ocs[] = {
1237 { "( OLcfgOvOc:21.1 "
1238 "NAME 'olcSssVlvConfig' "
1239 "DESC 'SSS VLV configuration' "
1240 "SUP olcOverlayConfig "
1241 "MAY ( olcSssVlvMax $ olcSssVlvMaxKeys ) )",
1242 Cft_Overlay, sssvlv_cfg, NULL, NULL },
1246 static int sssvlv_db_init(
1250 slap_overinst *on = (slap_overinst *)be->bd_info;
1253 if ( ov_count == 0 ) {
1256 rc = register_supported_control2( LDAP_CONTROL_SORTREQUEST,
1262 if ( rc != LDAP_SUCCESS ) {
1263 Debug( LDAP_DEBUG_ANY, "Failed to register Sort Request control '%s' (%d)\n",
1264 LDAP_CONTROL_SORTREQUEST, rc, 0 );
1268 rc = register_supported_control2( LDAP_CONTROL_VLVREQUEST,
1274 if ( rc != LDAP_SUCCESS ) {
1275 Debug( LDAP_DEBUG_ANY, "Failed to register VLV Request control '%s' (%d)\n",
1276 LDAP_CONTROL_VLVREQUEST, rc, 0 );
1277 #ifdef SLAP_CONFIG_DELETE
1278 overlay_unregister_control( be, LDAP_CONTROL_SORTREQUEST );
1279 #endif /* SLAP_CONFIG_DELETE */
1280 unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1285 si = (sssvlv_info *)ch_malloc(sizeof(sssvlv_info));
1286 on->on_bi.bi_private = si;
1290 si->svi_max_keys = SSSVLV_DEFAULT_MAX_KEYS;
1291 si->svi_max_percon = SSSVLV_DEFAULT_MAX_REQUEST_PER_CONN;
1295 return LDAP_SUCCESS;
1298 static int sssvlv_db_destroy(
1302 slap_overinst *on = (slap_overinst *)be->bd_info;
1303 sssvlv_info *si = (sssvlv_info *)on->on_bi.bi_private;
1307 if ( !ov_count && sort_conns) {
1309 for ( conn_index = 0 ; conn_index < dtblsize + 1 ; conn_index++ ) {
1310 ch_free(sort_conns[conn_index]);
1312 ch_free(sort_conns);
1313 ldap_pvt_thread_mutex_destroy( &sort_conns_mutex );
1316 if ( ov_count == 0 ) {
1317 unregister_supported_control( LDAP_CONTROL_SORTREQUEST );
1322 on->on_bi.bi_private = NULL;
1324 return LDAP_SUCCESS;
1327 static slap_overinst sssvlv;
1329 int sssvlv_initialize()
1333 sssvlv.on_bi.bi_type = "sssvlv";
1334 sssvlv.on_bi.bi_db_init = sssvlv_db_init;
1335 sssvlv.on_bi.bi_db_destroy = sssvlv_db_destroy;
1336 sssvlv.on_bi.bi_db_open = sssvlv_db_open;
1337 sssvlv.on_bi.bi_connection_destroy = sssvlv_connection_destroy;
1338 sssvlv.on_bi.bi_op_search = sssvlv_op_search;
1340 sssvlv.on_bi.bi_cf_ocs = sssvlv_ocs;
1342 rc = config_register_schema( sssvlv_cfg, sssvlv_ocs );
1346 rc = overlay_register( &sssvlv );
1347 if ( rc != LDAP_SUCCESS ) {
1348 Debug( LDAP_DEBUG_ANY, "Failed to register server side sort overlay\n", 0, 0, 0 );
1354 #if SLAPD_OVER_SSSVLV == SLAPD_MOD_DYNAMIC
1355 int init_module( int argc, char *argv[])
1357 return sssvlv_initialize();
1361 #endif /* SLAPD_OVER_SSSVLV */