]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/valsort.c
c5a14ffad5051d4820822be4d666bd18c71ea35c
[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 ConfigDriver valsort_cf_func;
55
56 static ConfigTable valsort_cfats[] = {
57         { "valsort-attr", "attribute> <dn> <sort-type", 4, 5, 0, ARG_MAGIC,
58                 valsort_cf_func, "( OLcfgOvAt:5.1 NAME 'olcValSortAttr' "
59                         "DESC 'Sorting rule for attribute under given DN' "
60                         "EQUALITY caseIgnoreMatch "
61                         "SYNTAX OMsDirectoryString )", NULL, NULL },
62         { NULL }
63 };
64
65 static ConfigOCs valsort_cfocs[] = {
66         { "( OLcfgOvOc:5.1 "
67                 "NAME 'olcValSortConfig' "
68                 "DESC 'Value Sorting configuration' "
69                 "SUP olcOverlayConfig "
70                 "MUST olcValSortAttr )",
71                         Cft_Overlay, valsort_cfats },
72         { NULL }
73 };
74
75 static slap_verbmasks sorts[] = {
76         { BER_BVC("alpha-ascend"), VALSORT_ASCEND|VALSORT_ALPHA },
77         { BER_BVC("alpha-descend"), VALSORT_DESCEND|VALSORT_ALPHA },
78         { BER_BVC("numeric-ascend"), VALSORT_ASCEND|VALSORT_NUMERIC },
79         { BER_BVC("numeric-ascend"), VALSORT_DESCEND|VALSORT_NUMERIC },
80         { BER_BVC("weighted"), VALSORT_WEIGHTED },
81         { BER_BVNULL, 0 }
82 };
83
84 static int
85 valsort_cf_func(ConfigArgs *c) {
86         slap_overinst *on = (slap_overinst *)c->bi;
87         valsort_info vitmp, *vi;
88         const char *text = NULL;
89         int i;
90         struct berval bv = BER_BVNULL;
91
92         if ( c->op == SLAP_CONFIG_EMIT ) {
93                 for ( vi = on->on_bi.bi_private; vi; vi = vi->vi_next ) {
94                         struct berval bv2 = BER_BVNULL, bvret;
95                         char *ptr;
96                         int len;
97                         
98                         len = vi->vi_ad->ad_cname.bv_len + 1 + vi->vi_dn.bv_len + 3;
99                         i = vi->vi_sort;
100                         if ( i & VALSORT_WEIGHTED ) {
101                                 enum_to_verb( sorts, VALSORT_WEIGHTED, &bv2 );
102                                 len += bv2.bv_len + 1;
103                                 i ^= VALSORT_WEIGHTED;
104                         }
105                         enum_to_verb( sorts, i, &bv );
106                         len += bv.bv_len;
107                         bvret.bv_val = ch_malloc( len+1 );
108                         bvret.bv_len = len;
109
110                         ptr = lutil_strcopy( bvret.bv_val, vi->vi_ad->ad_cname.bv_val );
111                         *ptr++ = ' ';
112                         *ptr++ = '"';
113                         ptr = lutil_strcopy( ptr, vi->vi_dn.bv_val );
114                         *ptr++ = '"';
115                         if ( vi->vi_sort & VALSORT_WEIGHTED ) {
116                                 *ptr++ = ' ';
117                                 ptr = lutil_strcopy( ptr, bv2.bv_val );
118                         }
119                         if ( !BER_BVISNULL( &bv )) {
120                                 *ptr++ = ' ';
121                                 strcpy( ptr, bv.bv_val );
122                         }
123                         ber_bvarray_add( &c->rvalue_vals, &bvret );
124                 }
125                 i = ( c->rvalue_vals != NULL ) ? 0 : 1;
126                 return i;
127         } else if ( c->op == LDAP_MOD_DELETE ) {
128                 if ( c->valx < 0 ) {
129                         for ( vi = on->on_bi.bi_private; vi; vi = c->be->be_private ) {
130                                 on->on_bi.bi_private = vi->vi_next;
131                                 ch_free( vi->vi_dn.bv_val );
132                                 ch_free( vi );
133                         }
134                 } else {
135                         valsort_info **prev;
136
137                         for (i=0, prev = (valsort_info **)&on->on_bi.bi_private,
138                                 vi = *prev; vi && i<c->valx;
139                                 prev = &vi->vi_next, vi = vi->vi_next, i++ );
140                         (*prev)->vi_next = vi->vi_next;
141                         ch_free( vi->vi_dn.bv_val );
142                         ch_free( vi );
143                 }
144                 return 0;
145         }
146         vitmp.vi_ad = NULL;
147         i = slap_str2ad( c->argv[1], &vitmp.vi_ad, &text );
148         if ( i ) {
149                 sprintf( c->msg, "<%s> %s", c->argv[0], text );
150                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
151                         c->log, c->msg, c->argv[1] );
152                 return(1);
153         }
154         if ( is_at_single_value( vitmp.vi_ad->ad_type )) {
155                 sprintf( c->msg, "<%s> %s is single-valued, ignoring", c->argv[0],
156                         vitmp.vi_ad->ad_cname.bv_val );
157                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
158                         c->log, c->msg, c->argv[1] );
159                 return(0);
160         }
161         ber_str2bv( c->argv[2], 0, 0, &bv );
162         i = dnNormalize( 0, NULL, NULL, &bv, &vitmp.vi_dn, NULL );
163         if ( i ) {
164                 sprintf( c->msg, "<%s> unable to normalize DN", c->argv[0] );
165                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
166                         c->log, c->msg, c->argv[2] );
167                 return(1);
168         }
169         i = verb_to_mask( c->argv[3], sorts );
170         if ( BER_BVISNULL( &sorts[i].word )) {
171                 sprintf( c->msg, "<%s> unrecognized sort type", c->argv[0] );
172                 Debug( LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
173                         c->log, c->msg, c->argv[3] );
174                 return(1);
175         }
176         vitmp.vi_sort = sorts[i].mask;
177         if ( sorts[i].mask == VALSORT_WEIGHTED && c->argc == 5 ) {
178                 i = verb_to_mask( c->argv[4], 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[4] );
183                         return(1);
184                 }
185                 vitmp.vi_sort |= sorts[i].mask;
186         }
187         vi = ch_malloc( sizeof(valsort_info) );
188         *vi = vitmp;
189         vi->vi_next = on->on_bi.bi_private;
190         on->on_bi.bi_private = vi;
191         return 0;
192 }
193
194 /* Use Insertion Sort algorithm on selected values */
195 static void
196 do_sort( Operation *op, Attribute *a, int beg, int num, slap_mask_t sort )
197 {
198         int i, j, gotnvals;
199         struct berval tmp, ntmp, *vals, *nvals;
200
201         gotnvals = (a->a_vals != a->a_nvals );
202
203         nvals = a->a_nvals + beg;
204         if ( gotnvals )
205                 vals = a->a_vals + beg;
206
207         if ( sort & VALSORT_NUMERIC ) {
208                 long *numbers = op->o_tmpalloc( num * sizeof(long), op->o_tmpmemctx ),
209                         idx;
210                 for (i=0; i<num; i++)
211                         numbers[i] = strtol( nvals[i].bv_val, NULL, 0 );
212
213                 for (i=1; i<num; i++) {
214                         idx = numbers[i];
215                         ntmp = nvals[i];
216                         if ( gotnvals ) tmp = vals[i];
217                         j = i;
218                         while ( j>0 ) {
219                                 int cmp = (sort & VALSORT_DESCEND) ? numbers[j-1] < idx :
220                                         numbers[j-1] > idx;
221                                 if ( !cmp ) break;
222                                 numbers[j] = numbers[j-1];
223                                 nvals[j] = nvals[j-1];
224                                 if ( gotnvals ) vals[j] = vals[j-1];
225                                 j--;
226                         }
227                         numbers[j] = idx;
228                         nvals[j] = ntmp;
229                         if ( gotnvals ) vals[j] = tmp;
230                 }
231                 op->o_tmpfree( numbers, op->o_tmpmemctx );
232         } else {
233                 for (i=1; i<num; i++) {
234                         ntmp = nvals[i];
235                         if ( gotnvals ) tmp = vals[i];
236                         j = i;
237                         while ( j>0 ) {
238                                 int cmp = strcmp( nvals[j-1].bv_val, ntmp.bv_val );
239                                 cmp = (sort & VALSORT_DESCEND) ? (cmp < 0) : (cmp > 0);
240                                 if ( !cmp ) break;
241
242                                 nvals[j] = nvals[j-1];
243                                 if ( gotnvals ) vals[j] = vals[j-1];
244                                 j--;
245                         }
246                         nvals[j] = ntmp;
247                         if ( gotnvals ) vals[j] = tmp;
248                 }
249         }
250 }
251
252 static int
253 valsort_response( Operation *op, SlapReply *rs )
254 {
255         slap_overinst *on;
256         valsort_info *vi;
257         Attribute *a;
258
259         /* We only want search responses */
260         if ( rs->sr_type != REP_SEARCH ) return SLAP_CB_CONTINUE;
261
262         on = (slap_overinst *) op->o_bd->bd_info;
263         vi = on->on_bi.bi_private;
264
265         /* And we must have something configured */
266         if ( !vi ) return SLAP_CB_CONTINUE;
267
268         /* Find a rule whose baseDN matches this entry */
269         for (; vi; vi = vi->vi_next ) {
270                 int i, n;
271
272                 if ( !dnIsSuffix( &rs->sr_entry->e_nname, &vi->vi_dn ))
273                         continue;
274
275                 /* Find attr that this rule affects */
276                 a = attr_find( rs->sr_entry->e_attrs, vi->vi_ad );
277                 if ( !a ) continue;
278
279                 if (( rs->sr_flags & ( REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED )) !=
280                         ( REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED )) {
281                         rs->sr_entry = entry_dup( rs->sr_entry );
282                         rs->sr_flags |= REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED;
283                         a = attr_find( rs->sr_entry->e_attrs, vi->vi_ad );
284                 }
285
286                 /* count values */
287                 for ( n = 0; !BER_BVISNULL( &a->a_vals[n] ); n++ );
288
289                 if ( vi->vi_sort & VALSORT_WEIGHTED ) {
290                         int j, gotnvals;
291                         long *index = op->o_tmpalloc( n * sizeof(long), op->o_tmpmemctx );
292
293                         gotnvals = (a->a_vals != a->a_nvals );
294
295                         for (i=0; i<n; i++) {
296                                 char *ptr = strchr( a->a_nvals[i].bv_val, '{' );
297                                 char *end = NULL;
298                                 if ( !ptr ) {
299                                         Debug(LDAP_DEBUG_TRACE, "weights missing from attr %s "
300                                                 "in entry %s\n", vi->vi_ad->ad_cname.bv_val,
301                                                 rs->sr_entry->e_name.bv_val, 0 );
302                                         break;
303                                 }
304                                 index[i] = strtol( ptr+1, &end, 0 );
305                                 if ( *end != '}' ) {
306                                         Debug(LDAP_DEBUG_TRACE, "weights misformatted "
307                                                 "in entry %s\n", 
308                                                 rs->sr_entry->e_name.bv_val, 0, 0 );
309                                         break;
310                                 }
311                                 /* Strip out weights */
312                                 ptr = a->a_nvals[i].bv_val;
313                                 end++;
314                                 for (;*end;)
315                                         *ptr++ = *end++;
316                                 *ptr = '\0';
317                                 a->a_nvals[i].bv_len = ptr - a->a_nvals[i].bv_val;
318
319                                 if ( a->a_vals != a->a_nvals ) {
320                                         ptr = a->a_vals[i].bv_val;
321                                         end = strchr( ptr, '}' ) + 1;
322                                         for (;*end;)
323                                                 *ptr++ = *end++;
324                                         *ptr = '\0';
325                                         a->a_vals[i].bv_len = ptr - a->a_vals[i].bv_val;
326                                 }
327                         }
328                         /* An attr was missing weights here, ignore it */
329                         if ( i<n ) {
330                                 op->o_tmpfree( index, op->o_tmpmemctx );
331                                 continue;
332                         }
333                         /* Insertion sort */
334                         for ( i=1; i<n; i++) {
335                                 long idx = index[i];
336                                 struct berval tmp = a->a_vals[i], ntmp;
337                                 if ( gotnvals ) ntmp = a->a_nvals[i];
338                                 j = i;
339                                 while (( j>0 ) && (index[j-1] > idx )) {
340                                         index[j] = index[j-1];
341                                         a->a_vals[j] = a->a_vals[j-1];
342                                         if ( gotnvals ) a->a_nvals[j] = a->a_nvals[j-1];
343                                         j--;
344                                 }
345                                 index[j] = idx;
346                                 a->a_vals[j] = tmp;
347                                 if ( gotnvals ) a->a_nvals[j] = ntmp;
348                         }
349                         /* Check for secondary sort */
350                         if ( vi->vi_sort ^ VALSORT_WEIGHTED ) {
351                                 for ( i=0; i<n;) {
352                                         for (j=i+1; j<n; j++) {
353                                                 if (index[i] != index[j])
354                                                         break;
355                                         }
356                                         if( j-i > 1 )
357                                                 do_sort( op, a, i, j-i, vi->vi_sort );
358                                         i = j;
359                                 }
360                         }
361                         op->o_tmpfree( index, op->o_tmpmemctx );
362                 } else {
363                         do_sort( op, a, 0, n, vi->vi_sort );
364                 }
365         }
366         return SLAP_CB_CONTINUE;
367 }
368
369 static int
370 valsort_add( Operation *op, SlapReply *rs )
371 {
372         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
373         valsort_info *vi = on->on_bi.bi_private;
374
375         Attribute *a;
376         int i;
377         char *ptr, *end;
378
379         /* See if any weighted sorting applies to this entry */
380         for ( ;vi;vi=vi->vi_next ) {
381                 if ( !dnIsSuffix( &op->o_req_ndn, &vi->vi_dn ))
382                         continue;
383                 if ( !(vi->vi_sort & VALSORT_WEIGHTED ))
384                         continue;
385                 a = attr_find( op->ora_e->e_attrs, vi->vi_ad );
386                 if ( !a )
387                         continue;
388                 for (i=0; !BER_BVISNULL( &a->a_vals[i] ); i++) {
389                         ptr = strchr(a->a_vals[i].bv_val, '{' );
390                         if ( !ptr ) {
391                                 Debug(LDAP_DEBUG_TRACE, "weight missing from attribute %s\n",
392                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
393                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
394                                         "weight missing from attribute" );
395                                 return rs->sr_err;
396                         }
397                         strtol( ptr+1, &end, 0 );
398                         if ( *end != '}' ) {
399                                 Debug(LDAP_DEBUG_TRACE, "weight is misformatted in %s\n",
400                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
401                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
402                                         "weight is misformatted" );
403                                 return rs->sr_err;
404                         }
405                 }
406         }
407         return SLAP_CB_CONTINUE;
408 }
409
410 static int
411 valsort_modify( Operation *op, SlapReply *rs )
412 {
413         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
414         valsort_info *vi = on->on_bi.bi_private;
415
416         Modifications *ml;
417         int i;
418         char *ptr, *end;
419
420         /* See if any weighted sorting applies to this entry */
421         for ( ;vi;vi=vi->vi_next ) {
422                 if ( !dnIsSuffix( &op->o_req_ndn, &vi->vi_dn ))
423                         continue;
424                 if ( !(vi->vi_sort & VALSORT_WEIGHTED ))
425                         continue;
426                 for (ml = op->orm_modlist; ml; ml=ml->sml_next ) {
427                         if ( ml->sml_desc == vi->vi_ad )
428                                 break;
429                 }
430                 if ( !ml )
431                         continue;
432                 for (i=0; !BER_BVISNULL( &ml->sml_values[i] ); i++) {
433                         ptr = strchr(ml->sml_values[i].bv_val, '{' );
434                         if ( !ptr ) {
435                                 Debug(LDAP_DEBUG_TRACE, "weight missing from attribute %s\n",
436                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
437                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
438                                         "weight missing from attribute" );
439                                 return rs->sr_err;
440                         }
441                         strtol( ptr+1, &end, 0 );
442                         if ( *end != '}' ) {
443                                 Debug(LDAP_DEBUG_TRACE, "weight is misformatted in %s\n",
444                                         vi->vi_ad->ad_cname.bv_val, 0, 0);
445                                 send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION,
446                                         "weight is misformatted" );
447                                 return rs->sr_err;
448                         }
449                 }
450         }
451         return SLAP_CB_CONTINUE;
452 }
453
454 static int
455 valsort_destroy(
456         BackendDB *be
457 )
458 {
459         slap_overinst *on = (slap_overinst *)be->bd_info;
460         valsort_info *vi = on->on_bi.bi_private, *next;
461
462         for (; vi; vi = next) {
463                 next = vi->vi_next;
464                 ch_free( vi->vi_dn.bv_val );
465                 ch_free( vi );
466         }
467
468         return 0;
469 }
470
471 static slap_overinst valsort;
472
473 int valsort_init()
474 {
475         int i, rc;
476
477         valsort.on_bi.bi_type = "valsort";
478         valsort.on_bi.bi_db_destroy = valsort_destroy;
479
480         valsort.on_bi.bi_op_add = valsort_add;
481         valsort.on_bi.bi_op_modify = valsort_modify;
482
483         valsort.on_response = valsort_response;
484
485         valsort.on_bi.bi_cf_ocs = valsort_cfocs;
486
487         rc = config_register_schema( valsort_cfats, valsort_cfocs );
488         if ( rc ) return rc;
489
490         return overlay_register(&valsort);
491 }
492
493 #if SLAPD_OVER_VALSORT == SLAPD_MOD_DYNAMIC
494 int init_module( int argc, char *argv[]) {
495         return valsort_init();
496 }
497 #endif
498
499 #endif /* SLAPD_OVER_VALSORT */