]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/valsort.c
98290733d6010e7d2864d66a96ef33fb742a8b1e
[openldap] / servers / slapd / overlays / valsort.c
1 /* valsort.c - sort attribute values */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2005 The OpenLDAP Foundation.
6  * Portions copyright 2005 Symas Corporation.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by Howard Chu for inclusion in
19  * OpenLDAP Software. This work was sponsored by Stanford University.
20  */
21
22 /*
23  * This overlay sorts the values of multi-valued attributes when returning
24  * them in a search response.
25  */
26 #include "portable.h"
27
28 #ifdef SLAPD_OVER_VALSORT
29
30 #include <stdio.h>
31
32 #include <ac/string.h>
33 #include <ac/ctype.h>
34
35 #include "slap.h"
36 #include "config.h"
37 #include "lutil.h"
38
39 #define VALSORT_ASCEND  0
40 #define VALSORT_DESCEND 1
41
42 #define VALSORT_ALPHA   2
43 #define VALSORT_NUMERIC 4
44
45 #define VALSORT_WEIGHTED        8
46
47 typedef struct valsort_info {
48         struct valsort_info *vi_next;
49         struct berval vi_dn;
50         AttributeDescription *vi_ad;
51         slap_mask_t vi_sort;
52 } valsort_info;
53
54 static int valsort_cid;
55
56 static ConfigDriver valsort_cf_func;
57
58 static ConfigTable valsort_cfats[] = {
59         { "valsort-attr", "attribute> <dn> <sort-type", 4, 5, 0, ARG_MAGIC,
60                 valsort_cf_func, "( OLcfgOvAt:5.1 NAME 'olcValSortAttr' "
61                         "DESC 'Sorting rule for attribute under given DN' "
62                         "EQUALITY caseIgnoreMatch "
63                         "SYNTAX OMsDirectoryString )", NULL, NULL },
64         { NULL }
65 };
66
67 static ConfigOCs valsort_cfocs[] = {
68         { "( OLcfgOvOc:5.1 "
69                 "NAME 'olcValSortConfig' "
70                 "DESC 'Value Sorting configuration' "
71                 "SUP olcOverlayConfig "
72                 "MUST olcValSortAttr )",
73                         Cft_Overlay, valsort_cfats },
74         { NULL }
75 };
76
77 static slap_verbmasks sorts[] = {
78         { BER_BVC("alpha-ascend"), VALSORT_ASCEND|VALSORT_ALPHA },
79         { BER_BVC("alpha-descend"), VALSORT_DESCEND|VALSORT_ALPHA },
80         { BER_BVC("numeric-ascend"), VALSORT_ASCEND|VALSORT_NUMERIC },
81         { BER_BVC("numeric-descend"), VALSORT_DESCEND|VALSORT_NUMERIC },
82         { BER_BVC("weighted"), VALSORT_WEIGHTED },
83         { BER_BVNULL, 0 }
84 };
85
86 static Syntax *syn_numericString;
87
88 static int
89 valsort_cf_func(ConfigArgs *c) {
90         slap_overinst *on = (slap_overinst *)c->bi;
91         valsort_info vitmp, *vi;
92         const char *text = NULL;
93         int i, is_numeric;
94         struct berval bv = BER_BVNULL;
95
96         if ( c->op == SLAP_CONFIG_EMIT ) {
97                 for ( vi = on->on_bi.bi_private; vi; vi = vi->vi_next ) {
98                         struct berval bv2 = BER_BVNULL, bvret;
99                         char *ptr;
100                         int len;
101                         
102                         len = vi->vi_ad->ad_cname.bv_len + 1 + vi->vi_dn.bv_len + 2;
103                         i = vi->vi_sort;
104                         if ( i & VALSORT_WEIGHTED ) {
105                                 enum_to_verb( sorts, VALSORT_WEIGHTED, &bv2 );
106                                 len += bv2.bv_len + 1;
107                                 i ^= VALSORT_WEIGHTED;
108                         }
109                         if ( i ) {
110                                 enum_to_verb( sorts, i, &bv );
111                                 len += bv.bv_len + 1;
112                         }
113                         bvret.bv_val = ch_malloc( len+1 );
114                         bvret.bv_len = len;
115
116                         ptr = lutil_strcopy( bvret.bv_val, vi->vi_ad->ad_cname.bv_val );
117                         *ptr++ = ' ';
118                         *ptr++ = '"';
119                         ptr = lutil_strcopy( ptr, vi->vi_dn.bv_val );
120                         *ptr++ = '"';
121                         if ( vi->vi_sort & VALSORT_WEIGHTED ) {
122                                 *ptr++ = ' ';
123                                 ptr = lutil_strcopy( ptr, bv2.bv_val );
124                         }
125                         if ( i ) {
126                                 *ptr++ = ' ';
127                                 strcpy( ptr, bv.bv_val );
128                         }
129                         ber_bvarray_add( &c->rvalue_vals, &bvret );
130                 }
131                 i = ( c->rvalue_vals != NULL ) ? 0 : 1;
132                 return i;
133         } else if ( c->op == LDAP_MOD_DELETE ) {
134                 if ( c->valx < 0 ) {
135                         for ( vi = on->on_bi.bi_private; vi; vi = on->on_bi.bi_private ) {
136                                 on->on_bi.bi_private = vi->vi_next;
137                                 ch_free( vi->vi_dn.bv_val );
138                                 ch_free( vi );
139                         }
140                 } else {
141                         valsort_info **prev;
142
143                         for (i=0, prev = (valsort_info **)&on->on_bi.bi_private,
144                                 vi = *prev; vi && i<c->valx;
145                                 prev = &vi->vi_next, vi = vi->vi_next, i++ );
146                         (*prev)->vi_next = vi->vi_next;
147                         ch_free( vi->vi_dn.bv_val );
148                         ch_free( vi );
149                 }
150                 return 0;
151         }
152         vitmp.vi_ad = NULL;
153         i = slap_str2ad( c->argv[1], &vitmp.vi_ad, &text );
154         if ( i ) {
155                 sprintf( c->msg, "<%s> %s", c->argv[0], text );
156                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
157                         c->log, c->msg, c->argv[1] );
158                 return(1);
159         }
160         if ( is_at_single_value( vitmp.vi_ad->ad_type )) {
161                 sprintf( c->msg, "<%s> %s is single-valued, ignoring", c->argv[0],
162                         vitmp.vi_ad->ad_cname.bv_val );
163                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
164                         c->log, c->msg, c->argv[1] );
165                 return(0);
166         }
167         is_numeric = ( vitmp.vi_ad->ad_type->sat_syntax == syn_numericString ||
168                 vitmp.vi_ad->ad_type->sat_syntax == slap_schema.si_syn_integer ) ? 1
169                 : 0;
170         ber_str2bv( c->argv[2], 0, 0, &bv );
171         i = dnNormalize( 0, NULL, NULL, &bv, &vitmp.vi_dn, NULL );
172         if ( i ) {
173                 sprintf( c->msg, "<%s> unable to normalize DN", c->argv[0] );
174                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
175                         c->log, c->msg, c->argv[2] );
176                 return(1);
177         }
178         i = verb_to_mask( c->argv[3], sorts );
179         if ( BER_BVISNULL( &sorts[i].word )) {
180                 sprintf( c->msg, "<%s> unrecognized sort type", c->argv[0] );
181                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
182                         c->log, c->msg, c->argv[3] );
183                 return(1);
184         }
185         vitmp.vi_sort = sorts[i].mask;
186         if ( sorts[i].mask == VALSORT_WEIGHTED && c->argc == 5 ) {
187                 i = verb_to_mask( c->argv[4], sorts );
188                 if ( BER_BVISNULL( &sorts[i].word )) {
189                         sprintf( c->msg, "<%s> unrecognized sort type", c->argv[0] );
190                         Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
191                                 c->log, c->msg, c->argv[4] );
192                         return(1);
193                 }
194                 vitmp.vi_sort |= sorts[i].mask;
195         }
196         if (( vitmp.vi_sort & VALSORT_NUMERIC ) && !is_numeric ) {
197                 sprintf( c->msg, "<%s> numeric sort specified for non-numeric syntax",
198                         c->argv[0] );
199                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
200                         c->log, c->msg, c->argv[1] );
201                 return(1);
202         }
203         vi = ch_malloc( sizeof(valsort_info) );
204         *vi = vitmp;
205         vi->vi_next = on->on_bi.bi_private;
206         on->on_bi.bi_private = vi;
207         return 0;
208 }
209
210 /* Use Insertion Sort algorithm on selected values */
211 static void
212 do_sort( Operation *op, Attribute *a, int beg, int num, slap_mask_t sort )
213 {
214         int i, j, gotnvals;
215         struct berval tmp, ntmp, *vals, *nvals;
216
217         gotnvals = (a->a_vals != a->a_nvals );
218
219         nvals = a->a_nvals + beg;
220         if ( gotnvals )
221                 vals = a->a_vals + beg;
222
223         if ( sort & VALSORT_NUMERIC ) {
224                 long *numbers = op->o_tmpalloc( num * sizeof(long), op->o_tmpmemctx ),
225                         idx;
226                 for (i=0; i<num; i++)
227                         numbers[i] = strtol( nvals[i].bv_val, NULL, 0 );
228
229                 for (i=1; i<num; i++) {
230                         idx = numbers[i];
231                         ntmp = nvals[i];
232                         if ( gotnvals ) tmp = vals[i];
233                         j = i;
234                         while ( j>0 ) {
235                                 int cmp = (sort & VALSORT_DESCEND) ? numbers[j-1] < idx :
236                                         numbers[j-1] > idx;
237                                 if ( !cmp ) break;
238                                 numbers[j] = numbers[j-1];
239                                 nvals[j] = nvals[j-1];
240                                 if ( gotnvals ) vals[j] = vals[j-1];
241                                 j--;
242                         }
243                         numbers[j] = idx;
244                         nvals[j] = ntmp;
245                         if ( gotnvals ) vals[j] = tmp;
246                 }
247                 op->o_tmpfree( numbers, op->o_tmpmemctx );
248         } else {
249                 for (i=1; i<num; i++) {
250                         ntmp = nvals[i];
251                         if ( gotnvals ) tmp = vals[i];
252                         j = i;
253                         while ( j>0 ) {
254                                 int cmp = strcmp( nvals[j-1].bv_val, ntmp.bv_val );
255                                 cmp = (sort & VALSORT_DESCEND) ? (cmp < 0) : (cmp > 0);
256                                 if ( !cmp ) break;
257
258                                 nvals[j] = nvals[j-1];
259                                 if ( gotnvals ) vals[j] = vals[j-1];
260                                 j--;
261                         }
262                         nvals[j] = ntmp;
263                         if ( gotnvals ) vals[j] = tmp;
264                 }
265         }
266 }
267
268 static int
269 valsort_response( Operation *op, SlapReply *rs )
270 {
271         slap_overinst *on;
272         valsort_info *vi;
273         Attribute *a;
274
275         /* We only want search responses */
276         if ( rs->sr_type != REP_SEARCH ) return SLAP_CB_CONTINUE;
277
278         on = (slap_overinst *) op->o_bd->bd_info;
279         vi = on->on_bi.bi_private;
280
281         /* And we must have something configured */
282         if ( !vi ) return SLAP_CB_CONTINUE;
283
284         /* Find a rule whose baseDN matches this entry */
285         for (; vi; vi = vi->vi_next ) {
286                 int i, n;
287
288                 if ( !dnIsSuffix( &rs->sr_entry->e_nname, &vi->vi_dn ))
289                         continue;
290
291                 /* Find attr that this rule affects */
292                 a = attr_find( rs->sr_entry->e_attrs, vi->vi_ad );
293                 if ( !a ) continue;
294
295                 if (( rs->sr_flags & ( REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED )) !=
296                         ( REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED )) {
297                         rs->sr_entry = entry_dup( rs->sr_entry );
298                         rs->sr_flags |= REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED;
299                         a = attr_find( rs->sr_entry->e_attrs, vi->vi_ad );
300                 }
301
302                 /* count values */
303                 for ( n = 0; !BER_BVISNULL( &a->a_vals[n] ); n++ );
304
305                 if ( vi->vi_sort & VALSORT_WEIGHTED ) {
306                         int j, gotnvals;
307                         long *index = op->o_tmpalloc( n * sizeof(long), op->o_tmpmemctx );
308
309                         gotnvals = (a->a_vals != a->a_nvals );
310
311                         for (i=0; i<n; i++) {
312                                 char *ptr = strchr( a->a_nvals[i].bv_val, '{' );
313                                 char *end = NULL;
314                                 if ( !ptr ) {
315                                         Debug(LDAP_DEBUG_TRACE, "weights missing from attr %s "
316                                                 "in entry %s\n", vi->vi_ad->ad_cname.bv_val,
317                                                 rs->sr_entry->e_name.bv_val, 0 );
318                                         break;
319                                 }
320                                 index[i] = strtol( ptr+1, &end, 0 );
321                                 if ( *end != '}' ) {
322                                         Debug(LDAP_DEBUG_TRACE, "weights misformatted "
323                                                 "in entry %s\n", 
324                                                 rs->sr_entry->e_name.bv_val, 0, 0 );
325                                         break;
326                                 }
327                                 /* Strip out weights */
328                                 ptr = a->a_nvals[i].bv_val;
329                                 end++;
330                                 for (;*end;)
331                                         *ptr++ = *end++;
332                                 *ptr = '\0';
333                                 a->a_nvals[i].bv_len = ptr - a->a_nvals[i].bv_val;
334
335                                 if ( a->a_vals != a->a_nvals ) {
336                                         ptr = a->a_vals[i].bv_val;
337                                         end = strchr( ptr, '}' ) + 1;
338                                         for (;*end;)
339                                                 *ptr++ = *end++;
340                                         *ptr = '\0';
341                                         a->a_vals[i].bv_len = ptr - a->a_vals[i].bv_val;
342                                 }
343                         }
344                         /* An attr was missing weights here, ignore it */
345                         if ( i<n ) {
346                                 op->o_tmpfree( index, op->o_tmpmemctx );
347                                 continue;
348                         }
349                         /* Insertion sort */
350                         for ( i=1; i<n; i++) {
351                                 long idx = index[i];
352                                 struct berval tmp = a->a_vals[i], ntmp;
353                                 if ( gotnvals ) ntmp = a->a_nvals[i];
354                                 j = i;
355                                 while (( j>0 ) && (index[j-1] > idx )) {
356                                         index[j] = index[j-1];
357                                         a->a_vals[j] = a->a_vals[j-1];
358                                         if ( gotnvals ) a->a_nvals[j] = a->a_nvals[j-1];
359                                         j--;
360                                 }
361                                 index[j] = idx;
362                                 a->a_vals[j] = tmp;
363                                 if ( gotnvals ) a->a_nvals[j] = ntmp;
364                         }
365                         /* Check for secondary sort */
366                         if ( vi->vi_sort ^ VALSORT_WEIGHTED ) {
367                                 for ( i=0; i<n;) {
368                                         for (j=i+1; j<n; j++) {
369                                                 if (index[i] != index[j])
370                                                         break;
371                                         }
372                                         if( j-i > 1 )
373                                                 do_sort( op, a, i, j-i, vi->vi_sort );
374                                         i = j;
375                                 }
376                         }
377                         op->o_tmpfree( index, op->o_tmpmemctx );
378                 } else {
379                         do_sort( op, a, 0, n, vi->vi_sort );
380                 }
381         }
382         return SLAP_CB_CONTINUE;
383 }
384
385 static int
386 valsort_add( Operation *op, SlapReply *rs )
387 {
388         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
389         valsort_info *vi = on->on_bi.bi_private;
390
391         Attribute *a;
392         int i;
393         char *ptr, *end;
394
395         /* See if any weighted sorting applies to this entry */
396         for ( ;vi;vi=vi->vi_next ) {
397                 if ( !dnIsSuffix( &op->o_req_ndn, &vi->vi_dn ))
398                         continue;
399                 if ( !(vi->vi_sort & VALSORT_WEIGHTED ))
400                         continue;
401                 a = attr_find( op->ora_e->e_attrs, vi->vi_ad );
402                 if ( !a )
403                         continue;
404                 for (i=0; !BER_BVISNULL( &a->a_vals[i] ); i++) {
405                         ptr = strchr(a->a_vals[i].bv_val, '{' );
406                         if ( !ptr ) {
407                                 Debug(LDAP_DEBUG_TRACE, "weight missing from attribute %s\n",
408                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
409                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
410                                         "weight missing from attribute" );
411                                 return rs->sr_err;
412                         }
413                         strtol( ptr+1, &end, 0 );
414                         if ( *end != '}' ) {
415                                 Debug(LDAP_DEBUG_TRACE, "weight is misformatted in %s\n",
416                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
417                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
418                                         "weight is misformatted" );
419                                 return rs->sr_err;
420                         }
421                 }
422         }
423         return SLAP_CB_CONTINUE;
424 }
425
426 static int
427 valsort_modify( Operation *op, SlapReply *rs )
428 {
429         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
430         valsort_info *vi = on->on_bi.bi_private;
431
432         Modifications *ml;
433         int i;
434         char *ptr, *end;
435
436         /* See if any weighted sorting applies to this entry */
437         for ( ;vi;vi=vi->vi_next ) {
438                 if ( !dnIsSuffix( &op->o_req_ndn, &vi->vi_dn ))
439                         continue;
440                 if ( !(vi->vi_sort & VALSORT_WEIGHTED ))
441                         continue;
442                 for (ml = op->orm_modlist; ml; ml=ml->sml_next ) {
443                         if ( ml->sml_desc == vi->vi_ad )
444                                 break;
445                 }
446                 if ( !ml )
447                         continue;
448                 for (i=0; !BER_BVISNULL( &ml->sml_values[i] ); i++) {
449                         ptr = strchr(ml->sml_values[i].bv_val, '{' );
450                         if ( !ptr ) {
451                                 Debug(LDAP_DEBUG_TRACE, "weight missing from attribute %s\n",
452                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
453                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
454                                         "weight missing from attribute" );
455                                 return rs->sr_err;
456                         }
457                         strtol( ptr+1, &end, 0 );
458                         if ( *end != '}' ) {
459                                 Debug(LDAP_DEBUG_TRACE, "weight is misformatted in %s\n",
460                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
461                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
462                                         "weight is misformatted" );
463                                 return rs->sr_err;
464                         }
465                 }
466         }
467         return SLAP_CB_CONTINUE;
468 }
469
470 static int
471 valsort_destroy(
472         BackendDB *be
473 )
474 {
475         slap_overinst *on = (slap_overinst *)be->bd_info;
476         valsort_info *vi = on->on_bi.bi_private, *next;
477
478         for (; vi; vi = next) {
479                 next = vi->vi_next;
480                 ch_free( vi->vi_dn.bv_val );
481                 ch_free( vi );
482         }
483
484         return 0;
485 }
486
487 static int
488 valsort_parseCtrl(
489         Operation *op,
490         SlapReply *rs,
491         LDAPControl *ctrl )
492 {
493         if ( ctrl->ldctl_value.bv_len ) {
494                 rs->sr_text = "valSort control value not empty";
495                 return LDAP_PROTOCOL_ERROR;
496         }
497         op->o_ctrlflag[valsort_cid] = ctrl->ldctl_iscritical ?
498                 SLAP_CONTROL_CRITICAL : SLAP_CONTROL_NONCRITICAL;
499
500         return LDAP_SUCCESS;
501 }
502
503 static slap_overinst valsort;
504
505 int valsort_init()
506 {
507         int i, rc;
508
509         valsort.on_bi.bi_type = "valsort";
510         valsort.on_bi.bi_db_destroy = valsort_destroy;
511
512         valsort.on_bi.bi_op_add = valsort_add;
513         valsort.on_bi.bi_op_modify = valsort_modify;
514
515         valsort.on_response = valsort_response;
516
517         valsort.on_bi.bi_cf_ocs = valsort_cfocs;
518
519         rc = register_supported_control( LDAP_CONTROL_VALSORT,
520                 SLAP_CTRL_SEARCH | SLAP_CTRL_HIDE, NULL, valsort_parseCtrl,
521                 &valsort_cid );
522         if ( rc != LDAP_SUCCESS ) {
523                 fprintf( stderr, "Failed to register control %d\n", rc );
524                 return rc;
525         }
526
527         syn_numericString = syn_find( "1.3.6.1.4.1.1466.115.121.1.36" );
528
529         rc = config_register_schema( valsort_cfats, valsort_cfocs );
530         if ( rc ) return rc;
531
532         return overlay_register(&valsort);
533 }
534
535 #if SLAPD_OVER_VALSORT == SLAPD_MOD_DYNAMIC
536 int init_module( int argc, char *argv[]) {
537         return valsort_init();
538 }
539 #endif
540
541 #endif /* SLAPD_OVER_VALSORT */