]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/rwm.c
consistently map operational attrs as well (ITS#5760); silence warning
[openldap] / servers / slapd / overlays / rwm.c
1 /* rwm.c - rewrite/remap operations */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2003-2009 The OpenLDAP Foundation.
6  * Portions Copyright 2003 Pierangelo Masarati.
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
18 #include "portable.h"
19
20 #ifdef SLAPD_OVER_RWM
21
22 #include <stdio.h>
23
24 #include <ac/string.h>
25
26 #include "slap.h"
27 #include "config.h"
28 #include "lutil.h"
29 #include "rwm.h"
30
31 typedef struct rwm_op_state {
32         ber_tag_t r_tag;
33         struct berval ro_dn;
34         struct berval ro_ndn;
35         struct berval r_dn;
36         struct berval r_ndn;
37         AttributeName *mapped_attrs;
38         OpRequest o_request;
39 } rwm_op_state;
40
41 typedef struct rwm_op_cb {
42         slap_callback cb;
43         rwm_op_state ros;
44 } rwm_op_cb;
45
46 static int
47 rwm_db_destroy( BackendDB *be, ConfigReply *cr );
48
49 static int
50 rwm_send_entry( Operation *op, SlapReply *rs );
51
52 static void
53 rwm_op_rollback( Operation *op, SlapReply *rs, rwm_op_state *ros )
54 {
55         if ( !BER_BVISNULL( &ros->ro_dn ) ) {
56                 op->o_req_dn = ros->ro_dn;
57         }
58         if ( !BER_BVISNULL( &ros->ro_ndn ) ) {
59                 op->o_req_ndn = ros->ro_ndn;
60         }
61
62         if ( !BER_BVISNULL( &ros->r_dn )
63                 && ros->r_dn.bv_val != ros->ro_dn.bv_val )
64         {
65                 assert( ros->r_dn.bv_val != ros->r_ndn.bv_val );
66                 ch_free( ros->r_dn.bv_val );
67                 BER_BVZERO( &ros->r_dn );
68         }
69
70         if ( !BER_BVISNULL( &ros->r_ndn )
71                 && ros->r_ndn.bv_val != ros->ro_ndn.bv_val )
72         {
73                 ch_free( ros->r_ndn.bv_val );
74                 BER_BVZERO( &ros->r_ndn );
75         }
76
77         BER_BVZERO( &ros->ro_dn );
78         BER_BVZERO( &ros->ro_ndn );
79
80         switch( ros->r_tag ) {
81         case LDAP_REQ_COMPARE:
82                 if ( op->orc_ava->aa_value.bv_val != ros->orc_ava->aa_value.bv_val )
83                         op->o_tmpfree( op->orc_ava->aa_value.bv_val, op->o_tmpmemctx );
84                 op->orc_ava = ros->orc_ava;
85                 break;
86         case LDAP_REQ_MODIFY:
87                 slap_mods_free( op->orm_modlist, 1 );
88                 op->orm_modlist = ros->orm_modlist;
89                 break;
90         case LDAP_REQ_MODRDN:
91                 if ( op->orr_newSup != ros->orr_newSup ) {
92                         ch_free( op->orr_newSup->bv_val );
93                         ch_free( op->orr_nnewSup->bv_val );
94                         op->o_tmpfree( op->orr_newSup, op->o_tmpmemctx );
95                         op->o_tmpfree( op->orr_nnewSup, op->o_tmpmemctx );
96                         op->orr_newSup = ros->orr_newSup;
97                         op->orr_nnewSup = ros->orr_nnewSup;
98                 }
99                 if ( op->orr_newrdn.bv_val != ros->orr_newrdn.bv_val ) {
100                         ch_free( op->orr_newrdn.bv_val );
101                         ch_free( op->orr_nnewrdn.bv_val );
102                         op->orr_newrdn = ros->orr_newrdn;
103                         op->orr_nnewrdn = ros->orr_nnewrdn;
104                 }
105                 break;
106         case LDAP_REQ_SEARCH:
107                 ch_free( ros->mapped_attrs );
108                 filter_free_x( op, op->ors_filter, 1 );
109                 ch_free( op->ors_filterstr.bv_val );
110                 op->ors_attrs = ros->ors_attrs;
111                 op->ors_filter = ros->ors_filter;
112                 op->ors_filterstr = ros->ors_filterstr;
113                 break;
114         case LDAP_REQ_EXTENDED:
115                 if ( op->ore_reqdata != ros->ore_reqdata ) {
116                         ber_bvfree( op->ore_reqdata );
117                         op->ore_reqdata = ros->ore_reqdata;
118                 }
119                 break;
120         case LDAP_REQ_BIND:
121                 if ( rs->sr_err == LDAP_SUCCESS ) {
122 #if 0
123                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
124                         /* too late, c_mutex released */
125                         fprintf( stderr, "*** DN: \"%s\" => \"%s\"\n",
126                                 op->o_conn->c_ndn.bv_val,
127                                 op->o_req_ndn.bv_val );
128                         ber_bvreplace( &op->o_conn->c_ndn,
129                                 &op->o_req_ndn );
130                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
131 #endif
132                 }
133                 break;
134         default:        break;
135         }
136 }
137
138 static int
139 rwm_op_cleanup( Operation *op, SlapReply *rs )
140 {
141         slap_callback   *cb = op->o_callback;
142         rwm_op_state *ros = cb->sc_private;
143
144         if ( rs->sr_type == REP_RESULT || rs->sr_type == REP_EXTENDED ||
145                 op->o_abandon || rs->sr_err == SLAPD_ABANDON )
146         {
147                 rwm_op_rollback( op, rs, ros );
148
149                 op->o_callback = op->o_callback->sc_next;
150                 op->o_tmpfree( cb, op->o_tmpmemctx );
151         }
152
153         return SLAP_CB_CONTINUE;
154 }
155
156 static rwm_op_cb *
157 rwm_callback_get( Operation *op, SlapReply *rs )
158 {
159         rwm_op_cb       *roc = NULL;
160
161         roc = op->o_tmpalloc( sizeof( struct rwm_op_cb ), op->o_tmpmemctx );
162         roc->cb.sc_cleanup = rwm_op_cleanup;
163         roc->cb.sc_response = NULL;
164         roc->cb.sc_next = op->o_callback;
165         roc->cb.sc_private = &roc->ros;
166         roc->ros.r_tag = op->o_tag;
167         roc->ros.ro_dn = op->o_req_dn;
168         roc->ros.ro_ndn = op->o_req_ndn;
169         roc->ros.o_request = op->o_request;
170         BER_BVZERO( &roc->ros.r_dn );
171         BER_BVZERO( &roc->ros.r_ndn );
172
173         return roc;
174 }
175
176
177 static int
178 rwm_op_dn_massage( Operation *op, SlapReply *rs, void *cookie,
179         rwm_op_state *ros )
180 {
181         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
182         struct ldaprwmap        *rwmap = 
183                         (struct ldaprwmap *)on->on_bi.bi_private;
184
185         struct berval           dn = BER_BVNULL,
186                                 ndn = BER_BVNULL;
187         int                     rc = 0;
188         dncookie                dc;
189
190         /*
191          * Rewrite the dn if needed
192          */
193         dc.rwmap = rwmap;
194         dc.conn = op->o_conn;
195         dc.rs = rs;
196         dc.ctx = (char *)cookie;
197
198         /* NOTE: in those cases where only the ndn is available,
199          * and the caller sets op->o_req_dn = op->o_req_ndn,
200          * only rewrite the op->o_req_ndn and use it as 
201          * op->o_req_dn as well */
202         ndn = op->o_req_ndn;
203         if ( op->o_req_dn.bv_val != op->o_req_ndn.bv_val ) {
204                 dn = op->o_req_dn;
205                 rc = rwm_dn_massage_pretty_normalize( &dc, &op->o_req_dn, &dn, &ndn );
206         } else {
207                 rc = rwm_dn_massage_normalize( &dc, &op->o_req_ndn, &ndn );
208         }
209
210         if ( rc != LDAP_SUCCESS ) {
211                 return rc;
212         }
213
214         if ( ( op->o_req_dn.bv_val != op->o_req_ndn.bv_val && dn.bv_val == op->o_req_dn.bv_val )
215                         || ndn.bv_val == op->o_req_ndn.bv_val )
216         {
217                 return LDAP_SUCCESS;
218         }
219
220         if ( op->o_req_dn.bv_val != op->o_req_ndn.bv_val ) {
221                 op->o_req_dn = dn;
222                 assert( BER_BVISNULL( &ros->r_dn ) );
223                 ros->r_dn = dn;
224         } else {
225                 op->o_req_dn = ndn;
226         }
227         op->o_req_ndn = ndn;
228         assert( BER_BVISNULL( &ros->r_ndn ) );
229         ros->r_ndn = ndn;
230
231         return LDAP_SUCCESS;
232 }
233
234 static int
235 rwm_op_add( Operation *op, SlapReply *rs )
236 {
237         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
238         struct ldaprwmap        *rwmap = 
239                         (struct ldaprwmap *)on->on_bi.bi_private;
240
241         int                     rc,
242                                 i;
243         Attribute               **ap = NULL;
244         char                    *olddn = op->o_req_dn.bv_val;
245         int                     isupdate;
246
247         rwm_op_cb               *roc = rwm_callback_get( op, rs );
248
249         rc = rwm_op_dn_massage( op, rs, "addDN", &roc->ros );
250         if ( rc != LDAP_SUCCESS ) {
251                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
252                 send_ldap_error( op, rs, rc, "addDN massage error" );
253                 return -1;
254         }
255
256         if ( olddn != op->o_req_dn.bv_val ) {
257                 ber_bvreplace( &op->ora_e->e_name, &op->o_req_dn );
258                 ber_bvreplace( &op->ora_e->e_nname, &op->o_req_ndn );
259         }
260
261         /* Count number of attributes in entry */ 
262         isupdate = be_shadow_update( op );
263         for ( i = 0, ap = &op->oq_add.rs_e->e_attrs; *ap; ) {
264                 Attribute       *a;
265
266                 if ( (*ap)->a_desc == slap_schema.si_ad_objectClass ||
267                                 (*ap)->a_desc == slap_schema.si_ad_structuralObjectClass )
268                 {
269                         int             j, last;
270
271                         last = (*ap)->a_numvals - 1;
272                         for ( j = 0; !BER_BVISNULL( &(*ap)->a_vals[ j ] ); j++ ) {
273                                 struct ldapmapping      *mapping = NULL;
274
275                                 ( void )rwm_mapping( &rwmap->rwm_oc, &(*ap)->a_vals[ j ],
276                                                 &mapping, RWM_MAP );
277                                 if ( mapping == NULL ) {
278                                         if ( rwmap->rwm_at.drop_missing ) {
279                                                 /* FIXME: we allow to remove objectClasses as well;
280                                                  * if the resulting entry is inconsistent, that's
281                                                  * the relayed database's business...
282                                                  */
283                                                 ch_free( (*ap)->a_vals[ j ].bv_val );
284                                                 if ( last > j ) {
285                                                         (*ap)->a_vals[ j ] = (*ap)->a_vals[ last ];
286                                                 }
287                                                 BER_BVZERO( &(*ap)->a_vals[ last ] );
288                                                 (*ap)->a_numvals--;
289                                                 last--;
290                                                 j--;
291                                         }
292
293                                 } else {
294                                         ch_free( (*ap)->a_vals[ j ].bv_val );
295                                         ber_dupbv( &(*ap)->a_vals[ j ], &mapping->m_dst );
296                                 }
297                         }
298
299                 } else if ( !isupdate && !get_relax( op ) && (*ap)->a_desc->ad_type->sat_no_user_mod )
300                 {
301                         goto next_attr;
302
303                 } else {
304                         struct ldapmapping      *mapping = NULL;
305
306                         ( void )rwm_mapping( &rwmap->rwm_at, &(*ap)->a_desc->ad_cname,
307                                         &mapping, RWM_MAP );
308                         if ( mapping == NULL ) {
309                                 if ( rwmap->rwm_at.drop_missing ) {
310                                         goto cleanup_attr;
311                                 }
312                         }
313
314                         if ( (*ap)->a_desc->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName
315                                         || ( mapping != NULL && mapping->m_dst_ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName ) )
316                         {
317                                 /*
318                                  * FIXME: rewrite could fail; in this case
319                                  * the operation should give up, right?
320                                  */
321                                 rc = rwm_dnattr_rewrite( op, rs, "addAttrDN",
322                                                 (*ap)->a_vals,
323                                                 (*ap)->a_nvals ? &(*ap)->a_nvals : NULL );
324                                 if ( rc ) {
325                                         goto cleanup_attr;
326                                 }
327
328                         } else if ( (*ap)->a_desc == slap_schema.si_ad_ref ) {
329                                 rc = rwm_referral_rewrite( op, rs, "referralAttrDN",
330                                                 (*ap)->a_vals,
331                                                 (*ap)->a_nvals ? &(*ap)->a_nvals : NULL );
332                                 if ( rc != LDAP_SUCCESS ) {
333                                         goto cleanup_attr;
334                                 }
335                         }
336                 
337                         if ( mapping != NULL ) {
338                                 assert( mapping->m_dst_ad != NULL );
339                                 (*ap)->a_desc = mapping->m_dst_ad;
340                         }
341                 }
342
343 next_attr:;
344                 ap = &(*ap)->a_next;
345                 continue;
346
347 cleanup_attr:;
348                 /* FIXME: leaking attribute/values? */
349                 a = *ap;
350
351                 *ap = (*ap)->a_next;
352                 attr_free( a );
353         }
354
355         op->o_callback = &roc->cb;
356
357         return SLAP_CB_CONTINUE;
358 }
359
360 static int
361 rwm_conn_init( BackendDB *be, Connection *conn )
362 {
363         slap_overinst           *on = (slap_overinst *) be->bd_info;
364         struct ldaprwmap        *rwmap = 
365                         (struct ldaprwmap *)on->on_bi.bi_private;
366
367         ( void )rewrite_session_init( rwmap->rwm_rw, conn );
368
369         return SLAP_CB_CONTINUE;
370 }
371
372 static int
373 rwm_conn_destroy( BackendDB *be, Connection *conn )
374 {
375         slap_overinst           *on = (slap_overinst *) be->bd_info;
376         struct ldaprwmap        *rwmap = 
377                         (struct ldaprwmap *)on->on_bi.bi_private;
378
379         ( void )rewrite_session_delete( rwmap->rwm_rw, conn );
380
381         return SLAP_CB_CONTINUE;
382 }
383
384 static int
385 rwm_op_bind( Operation *op, SlapReply *rs )
386 {
387         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
388         int                     rc;
389
390         rwm_op_cb               *roc = rwm_callback_get( op, rs );
391
392         rc = rwm_op_dn_massage( op, rs, "bindDN", &roc->ros );
393         if ( rc != LDAP_SUCCESS ) {
394                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
395                 send_ldap_error( op, rs, rc, "bindDN massage error" );
396                 return -1;
397         }
398
399         overlay_callback_after_backover( op, &roc->cb, 1 );
400
401         return SLAP_CB_CONTINUE;
402 }
403
404 static int
405 rwm_op_unbind( Operation *op, SlapReply *rs )
406 {
407         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
408         struct ldaprwmap        *rwmap = 
409                         (struct ldaprwmap *)on->on_bi.bi_private;
410
411         rewrite_session_delete( rwmap->rwm_rw, op->o_conn );
412
413         return SLAP_CB_CONTINUE;
414 }
415
416 static int
417 rwm_op_compare( Operation *op, SlapReply *rs )
418 {
419         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
420         struct ldaprwmap        *rwmap = 
421                         (struct ldaprwmap *)on->on_bi.bi_private;
422
423         int                     rc;
424         struct berval           mapped_vals[2] = { BER_BVNULL, BER_BVNULL };
425
426         rwm_op_cb               *roc = rwm_callback_get( op, rs );
427
428         rc = rwm_op_dn_massage( op, rs, "compareDN", &roc->ros );
429         if ( rc != LDAP_SUCCESS ) {
430                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
431                 send_ldap_error( op, rs, rc, "compareDN massage error" );
432                 return -1;
433         }
434
435         /* if the attribute is an objectClass, try to remap its value */
436         if ( op->orc_ava->aa_desc == slap_schema.si_ad_objectClass
437                         || op->orc_ava->aa_desc == slap_schema.si_ad_structuralObjectClass )
438         {
439                 rwm_map( &rwmap->rwm_oc, &op->orc_ava->aa_value,
440                                 &mapped_vals[0], RWM_MAP );
441                 if ( BER_BVISNULL( &mapped_vals[0] ) || BER_BVISEMPTY( &mapped_vals[0] ) )
442                 {
443                         op->o_bd->bd_info = (BackendInfo *)on->on_info;
444                         send_ldap_error( op, rs, LDAP_OTHER, "compare objectClass map error" );
445                         return -1;
446
447                 } else if ( mapped_vals[0].bv_val != op->orc_ava->aa_value.bv_val ) {
448                         ber_dupbv_x( &op->orc_ava->aa_value, &mapped_vals[0],
449                                 op->o_tmpmemctx );
450                 }
451
452         } else {
453                 struct ldapmapping      *mapping = NULL;
454                 AttributeDescription    *ad = op->orc_ava->aa_desc;
455
456                 ( void )rwm_mapping( &rwmap->rwm_at, &op->orc_ava->aa_desc->ad_cname,
457                                 &mapping, RWM_MAP );
458                 if ( mapping == NULL ) {
459                         if ( rwmap->rwm_at.drop_missing ) {
460                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
461                                 send_ldap_error( op, rs, LDAP_OTHER, "compare attributeType map error" );
462                                 return -1;
463                         }
464
465                 } else {
466                         assert( mapping->m_dst_ad != NULL );
467                         ad = mapping->m_dst_ad;
468                 }
469
470                 if ( op->orc_ava->aa_desc->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName
471                                 || ( mapping != NULL && mapping->m_dst_ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName ) )
472                 {
473                         struct berval   *mapped_valsp[2];
474                         
475                         mapped_valsp[0] = &mapped_vals[0];
476                         mapped_valsp[1] = &mapped_vals[1];
477
478                         mapped_vals[0] = op->orc_ava->aa_value;
479
480                         rc = rwm_dnattr_rewrite( op, rs, "compareAttrDN", NULL, mapped_valsp );
481
482                         if ( rc != LDAP_SUCCESS ) {
483                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
484                                 send_ldap_error( op, rs, rc, "compareAttrDN massage error" );
485                                 return -1;
486                         }
487
488                         if ( mapped_vals[ 0 ].bv_val != op->orc_ava->aa_value.bv_val ) {
489                                 /* NOTE: if we get here, rwm_dnattr_rewrite()
490                                  * already freed the old value, so now 
491                                  * it's invalid */
492                                 ber_dupbv_x( &op->orc_ava->aa_value, &mapped_vals[0],
493                                         op->o_tmpmemctx );
494                                 ber_memfree_x( mapped_vals[ 0 ].bv_val, NULL );
495                         }
496                 }
497                 op->orc_ava->aa_desc = ad;
498         }
499
500         op->o_callback = &roc->cb;
501
502         return SLAP_CB_CONTINUE;
503 }
504
505 static int
506 rwm_op_delete( Operation *op, SlapReply *rs )
507 {
508         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
509         int                     rc;
510
511         rwm_op_cb               *roc = rwm_callback_get( op, rs );
512
513         rc = rwm_op_dn_massage( op, rs, "deleteDN", &roc->ros );
514         if ( rc != LDAP_SUCCESS ) {
515                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
516                 send_ldap_error( op, rs, rc, "deleteDN massage error" );
517                 return -1;
518         }
519
520         op->o_callback = &roc->cb;
521
522         return SLAP_CB_CONTINUE;
523 }
524
525 static int
526 rwm_op_modify( Operation *op, SlapReply *rs )
527 {
528         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
529         struct ldaprwmap        *rwmap = 
530                         (struct ldaprwmap *)on->on_bi.bi_private;
531
532         int                     isupdate;
533         Modifications           **mlp;
534         int                     rc;
535
536         rwm_op_cb               *roc = rwm_callback_get( op, rs );
537
538         rc = rwm_op_dn_massage( op, rs, "modifyDN", &roc->ros );
539         if ( rc != LDAP_SUCCESS ) {
540                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
541                 send_ldap_error( op, rs, rc, "modifyDN massage error" );
542                 return -1;
543         }
544
545         isupdate = be_shadow_update( op );
546         for ( mlp = &op->orm_modlist; *mlp; ) {
547                 int                     is_oc = 0;
548                 Modifications           *ml = *mlp;
549                 struct ldapmapping      *mapping = NULL;
550
551                 /* ml points to a temporary mod until needs duplication */
552                 if ( ml->sml_desc == slap_schema.si_ad_objectClass 
553                                 || ml->sml_desc == slap_schema.si_ad_structuralObjectClass )
554                 {
555                         is_oc = 1;
556
557                 } else if ( !isupdate && !get_relax( op ) && ml->sml_desc->ad_type->sat_no_user_mod  )
558                 {
559                         ml = ch_malloc( sizeof( Modifications ) );
560                         *ml = **mlp;
561                         if ( (*mlp)->sml_values ) {
562                                 ber_bvarray_dup_x( &ml->sml_values, (*mlp)->sml_values, NULL );
563                                 if ( (*mlp)->sml_nvalues ) {
564                                         ber_bvarray_dup_x( &ml->sml_nvalues, (*mlp)->sml_nvalues, NULL );
565                                 }
566                         }
567                         *mlp = ml;
568                         goto next_mod;
569
570                 } else {
571                         int                     drop_missing;
572
573                         drop_missing = rwm_mapping( &rwmap->rwm_at,
574                                         &ml->sml_desc->ad_cname,
575                                         &mapping, RWM_MAP );
576                         if ( drop_missing || ( mapping != NULL && BER_BVISNULL( &mapping->m_dst ) ) )
577                         {
578                                 goto cleanup_mod;
579                         }
580                 }
581
582                 /* duplicate the modlist */
583                 ml = ch_malloc( sizeof( Modifications ));
584                 *ml = **mlp;
585                 *mlp = ml;
586
587                 if ( ml->sml_values != NULL ) {
588                         int i, num;
589                         struct berval *bva;
590
591                         for ( num = 0; !BER_BVISNULL( &ml->sml_values[ num ] ); num++ )
592                                 /* count values */ ;
593
594                         bva = ch_malloc( (num+1) * sizeof( struct berval ));
595                         for (i=0; i<num; i++)
596                                 ber_dupbv( &bva[i], &ml->sml_values[i] );
597                         BER_BVZERO( &bva[i] );
598                         ml->sml_values = bva;
599
600                         if ( ml->sml_nvalues ) {
601                                 bva = ch_malloc( (num+1) * sizeof( struct berval ));
602                                 for (i=0; i<num; i++)
603                                         ber_dupbv( &bva[i], &ml->sml_nvalues[i] );
604                                 BER_BVZERO( &bva[i] );
605                                 ml->sml_nvalues = bva;
606                         }
607
608                         if ( is_oc ) {
609                                 int     last, j;
610
611                                 last = num-1;
612
613                                 for ( j = 0; !BER_BVISNULL( &ml->sml_values[ j ] ); j++ ) {
614                                         struct ldapmapping      *oc_mapping = NULL;
615                 
616                                         ( void )rwm_mapping( &rwmap->rwm_oc, &ml->sml_values[ j ],
617                                                         &oc_mapping, RWM_MAP );
618                                         if ( oc_mapping == NULL ) {
619                                                 if ( rwmap->rwm_at.drop_missing ) {
620                                                         /* FIXME: we allow to remove objectClasses as well;
621                                                          * if the resulting entry is inconsistent, that's
622                                                          * the relayed database's business...
623                                                          */
624                                                         if ( last > j ) {
625                                                                 ch_free( ml->sml_values[ j ].bv_val );
626                                                                 ml->sml_values[ j ] = ml->sml_values[ last ];
627                                                         }
628                                                         BER_BVZERO( &ml->sml_values[ last ] );
629                                                         last--;
630                                                         j--;
631                                                 }
632         
633                                         } else {
634                                                 ch_free( ml->sml_values[ j ].bv_val );
635                                                 ber_dupbv( &ml->sml_values[ j ], &oc_mapping->m_dst );
636                                         }
637                                 }
638
639                         } else {
640                                 if ( ml->sml_desc->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName
641                                                 || ( mapping != NULL && mapping->m_dst_ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName ) )
642                                 {
643                                         rc = rwm_dnattr_rewrite( op, rs, "modifyAttrDN",
644                                                         ml->sml_values,
645                                                         ml->sml_nvalues ? &ml->sml_nvalues : NULL );
646
647                                 } else if ( ml->sml_desc == slap_schema.si_ad_ref ) {
648                                         rc = rwm_referral_rewrite( op, rs,
649                                                         "referralAttrDN",
650                                                         ml->sml_values,
651                                                         ml->sml_nvalues ? &ml->sml_nvalues : NULL );
652                                         if ( rc != LDAP_SUCCESS ) {
653                                                 goto cleanup_mod;
654                                         }
655                                 }
656
657                                 if ( rc != LDAP_SUCCESS ) {
658                                         goto cleanup_mod;
659                                 }
660                         }
661                 }
662
663 next_mod:;
664                 if ( mapping != NULL ) {
665                         /* use new attribute description */
666                         assert( mapping->m_dst_ad != NULL );
667                         ml->sml_desc = mapping->m_dst_ad;
668                 }
669
670                 mlp = &ml->sml_next;
671                 continue;
672
673 cleanup_mod:;
674                 ml = *mlp;
675                 *mlp = (*mlp)->sml_next;
676                 slap_mod_free( &ml->sml_mod, 0 );
677                 free( ml );
678         }
679
680         op->o_callback = &roc->cb;
681
682         return SLAP_CB_CONTINUE;
683 }
684
685 static int
686 rwm_op_modrdn( Operation *op, SlapReply *rs )
687 {
688         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
689         struct ldaprwmap        *rwmap = 
690                         (struct ldaprwmap *)on->on_bi.bi_private;
691         
692         int                     rc;
693         dncookie                dc;
694
695         rwm_op_cb               *roc = rwm_callback_get( op, rs );
696
697         if ( op->orr_newSup ) {
698                 struct berval   nnewSup = BER_BVNULL;
699                 struct berval   newSup = BER_BVNULL;
700
701                 /*
702                  * Rewrite the new superior, if defined and required
703                  */
704                 dc.rwmap = rwmap;
705                 dc.conn = op->o_conn;
706                 dc.rs = rs;
707                 dc.ctx = "newSuperiorDN";
708                 newSup = *op->orr_newSup;
709                 nnewSup = *op->orr_nnewSup;
710                 rc = rwm_dn_massage_pretty_normalize( &dc, op->orr_newSup, &newSup, &nnewSup );
711                 if ( rc != LDAP_SUCCESS ) {
712                         op->o_bd->bd_info = (BackendInfo *)on->on_info;
713                         send_ldap_error( op, rs, rc, "newSuperiorDN massage error" );
714                         return -1;
715                 }
716
717                 if ( op->orr_newSup->bv_val != newSup.bv_val ) {
718                         op->orr_newSup = op->o_tmpalloc( sizeof( struct berval ),
719                                 op->o_tmpmemctx );
720                         op->orr_nnewSup = op->o_tmpalloc( sizeof( struct berval ),
721                                 op->o_tmpmemctx );
722                         *op->orr_newSup = newSup;
723                         *op->orr_nnewSup = nnewSup;
724                 }
725         }
726
727         /*
728          * Rewrite the newRDN, if needed
729          */
730         {
731                 struct berval   newrdn = BER_BVNULL;
732                 struct berval   nnewrdn = BER_BVNULL;
733
734                 dc.rwmap = rwmap;
735                 dc.conn = op->o_conn;
736                 dc.rs = rs;
737                 dc.ctx = "newRDN";
738                 newrdn = op->orr_newrdn;
739                 nnewrdn = op->orr_nnewrdn;
740                 rc = rwm_dn_massage_pretty_normalize( &dc, &op->orr_newrdn, &newrdn, &nnewrdn );
741                 if ( rc != LDAP_SUCCESS ) {
742                         op->o_bd->bd_info = (BackendInfo *)on->on_info;
743                         send_ldap_error( op, rs, rc, "newRDN massage error" );
744                         goto err;
745                 }
746
747                 if ( op->orr_newrdn.bv_val != newrdn.bv_val ) {
748                         op->orr_newrdn = newrdn;
749                         op->orr_nnewrdn = nnewrdn;
750                 }
751         }
752
753         /*
754          * Rewrite the dn, if needed
755          */
756         rc = rwm_op_dn_massage( op, rs, "renameDN", &roc->ros );
757         if ( rc != LDAP_SUCCESS ) {
758                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
759                 send_ldap_error( op, rs, rc, "renameDN massage error" );
760                 goto err;
761         }
762
763         op->o_callback = &roc->cb;
764
765         rc = SLAP_CB_CONTINUE;
766
767         if ( 0 ) {
768 err:;
769                 if ( op->orr_newSup != roc->ros.orr_newSup ) {
770                         ch_free( op->orr_newSup->bv_val );
771                         ch_free( op->orr_nnewSup->bv_val );
772                         op->o_tmpfree( op->orr_newSup, op->o_tmpmemctx );
773                         op->o_tmpfree( op->orr_nnewSup, op->o_tmpmemctx );
774                         op->orr_newSup = roc->ros.orr_newSup;
775                         op->orr_nnewSup = roc->ros.orr_nnewSup;
776                 }
777
778                 if ( op->orr_newrdn.bv_val != roc->ros.orr_newrdn.bv_val ) {
779                         ch_free( op->orr_newrdn.bv_val );
780                         ch_free( op->orr_nnewrdn.bv_val );
781                         op->orr_newrdn = roc->ros.orr_newrdn;
782                         op->orr_nnewrdn = roc->ros.orr_nnewrdn;
783                 }
784         }
785
786         return rc;
787 }
788
789
790 static int
791 rwm_swap_attrs( Operation *op, SlapReply *rs )
792 {
793         slap_callback   *cb = op->o_callback;
794         rwm_op_state *ros = cb->sc_private;
795
796         rs->sr_attrs = ros->ors_attrs;
797
798         /* other overlays might have touched op->ors_attrs, 
799          * so we restore the original version here, otherwise
800          * attribute-mapping might fail */
801         op->ors_attrs = ros->mapped_attrs; 
802         
803         return SLAP_CB_CONTINUE;
804 }
805
806 /*
807  * NOTE: this implementation of get/release entry is probably far from
808  * optimal.  The rationale consists in intercepting the request directed
809  * to the underlying database, in order to rewrite/remap the request,
810  * perform it using the modified data, duplicate the resulting entry
811  * and finally free it when release is called.
812  * This implies that subsequent overlays are not called, as the request
813  * is directly shunted to the underlying database.
814  */
815 static int
816 rwm_entry_release_rw( Operation *op, Entry *e, int rw )
817 {
818         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
819
820         /* can't be ours */
821         if ( ((BackendInfo *)on->on_info->oi_orig)->bi_entry_get_rw == NULL ) {
822                 return SLAP_CB_CONTINUE;
823         }
824
825         /* just free entry if (probably) ours */
826         if ( e->e_private == NULL ) {
827                 entry_free( e );
828                 return LDAP_SUCCESS;
829         }
830
831         return SLAP_CB_CONTINUE;
832 }
833
834 static int
835 rwm_entry_get_rw( Operation *op, struct berval *ndn,
836         ObjectClass *oc, AttributeDescription *at, int rw, Entry **ep )
837 {
838         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
839         struct ldaprwmap        *rwmap = 
840                         (struct ldaprwmap *)on->on_bi.bi_private;
841
842         int                     rc;
843         dncookie                dc;
844
845         BackendDB               db;
846         Operation               op2;
847         SlapReply               rs = { REP_SEARCH };
848
849         rwm_op_state            ros = { 0 };
850
851         if ( ((BackendInfo *)on->on_info->oi_orig)->bi_entry_get_rw == NULL ) {
852                 return SLAP_CB_CONTINUE;
853         }
854
855         /* massage DN */
856         op2.o_tag = LDAP_REQ_SEARCH;
857         op2 = *op;
858         op2.o_req_dn = *ndn;
859         op2.o_req_ndn = *ndn;
860         rc = rwm_op_dn_massage( &op2, &rs, "searchDN", &ros );
861         if ( rc != LDAP_SUCCESS ) {
862                 return LDAP_OTHER;
863         }
864
865         /* map attribute & objectClass */
866         if ( at != NULL ) {
867         }
868
869         if ( oc != NULL ) {
870         }
871
872         /* fetch entry */
873         db = *op->o_bd;
874         op2.o_bd = &db;
875         op2.o_bd->bd_info = (BackendInfo *)on->on_info->oi_orig;
876         op2.ors_attrs = slap_anlist_all_attributes;
877         rc = op2.o_bd->bd_info->bi_entry_get_rw( &op2, &ros.r_ndn, oc, at, rw, ep );
878         if ( rc == LDAP_SUCCESS && *ep != NULL ) {
879                 rs.sr_entry = *ep;
880
881                 /* duplicate & release */
882                 op2.o_bd->bd_info = (BackendInfo *)on;
883                 rc = rwm_send_entry( &op2, &rs );
884                 if ( rc == SLAP_CB_CONTINUE ) {
885                         *ep = rs.sr_entry;
886                         rc = LDAP_SUCCESS;
887                 }
888         }
889
890         if ( ros.r_ndn.bv_val != ndn->bv_val ) {
891                 op->o_tmpfree( ros.r_ndn.bv_val, op->o_tmpmemctx );
892         }
893
894         return rc;
895 }
896
897 static int
898 rwm_op_search( Operation *op, SlapReply *rs )
899 {
900         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
901         struct ldaprwmap        *rwmap = 
902                         (struct ldaprwmap *)on->on_bi.bi_private;
903
904         int                     rc;
905         dncookie                dc;
906
907         struct berval           fstr = BER_BVNULL;
908         Filter                  *f = NULL;
909
910         AttributeName           *an = NULL;
911
912         char                    *text = NULL;
913
914         rwm_op_cb               *roc = rwm_callback_get( op, rs );
915
916         rc = rewrite_session_var_set( rwmap->rwm_rw, op->o_conn,
917                 "searchFilter", op->ors_filterstr.bv_val );
918         if ( rc == LDAP_SUCCESS )
919                 rc = rwm_op_dn_massage( op, rs, "searchDN", &roc->ros );
920         if ( rc != LDAP_SUCCESS ) {
921                 text = "searchDN massage error";
922                 goto error_return;
923         }
924
925         /*
926          * Rewrite the dn if needed
927          */
928         dc.rwmap = rwmap;
929         dc.conn = op->o_conn;
930         dc.rs = rs;
931         dc.ctx = "searchFilterAttrDN";
932
933         rc = rwm_filter_map_rewrite( op, &dc, op->ors_filter, &fstr );
934         if ( rc != LDAP_SUCCESS ) {
935                 text = "searchFilter/searchFilterAttrDN massage error";
936                 goto error_return;
937         }
938
939         f = str2filter_x( op, fstr.bv_val );
940
941         if ( f == NULL ) {
942                 text = "massaged filter parse error";
943                 goto error_return;
944         }
945
946         op->ors_filter = f;
947         op->ors_filterstr = fstr;
948
949         rc = rwm_map_attrnames( &rwmap->rwm_at, &rwmap->rwm_oc,
950                         op->ors_attrs, &an, RWM_MAP );
951         if ( rc != LDAP_SUCCESS ) {
952                 text = "attribute list mapping error";
953                 goto error_return;
954         }
955
956         op->ors_attrs = an;
957         /* store the mapped Attributes for later usage, in
958          * the case that other overlays change op->ors_attrs */
959         roc->ros.mapped_attrs = an;
960         roc->cb.sc_response = rwm_swap_attrs;
961
962         op->o_callback = &roc->cb;
963
964         return SLAP_CB_CONTINUE;
965
966 error_return:;
967         if ( an != NULL ) {
968                 ch_free( an );
969         }
970
971         if ( f != NULL ) {
972                 filter_free_x( op, f, 1 );
973         }
974
975         if ( !BER_BVISNULL( &fstr ) ) {
976                 ch_free( fstr.bv_val );
977         }
978
979         rwm_op_rollback( op, rs, &roc->ros );
980         op->oq_search = roc->ros.oq_search;
981         op->o_tmpfree( roc, op->o_tmpmemctx );
982
983         op->o_bd->bd_info = (BackendInfo *)on->on_info;
984         send_ldap_error( op, rs, rc, text );
985
986         return -1;
987
988 }
989
990 static int
991 rwm_exop_passwd( Operation *op, SlapReply *rs )
992 {
993         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
994         int                     rc;
995         rwm_op_cb *roc;
996
997         struct berval   id = BER_BVNULL,
998                         pwold = BER_BVNULL,
999                         pwnew = BER_BVNULL;
1000         BerElement *ber = NULL;
1001
1002         if ( !BER_BVISNULL( &op->o_req_ndn ) ) {
1003                 return LDAP_SUCCESS;
1004         }
1005
1006         if ( !SLAP_ISGLOBALOVERLAY( op->o_bd ) ) {
1007                 rs->sr_err = LDAP_OTHER;
1008                 return rs->sr_err;
1009         }
1010
1011         rs->sr_err = slap_passwd_parse( op->ore_reqdata, &id,
1012                 &pwold, &pwnew, &rs->sr_text );
1013         if ( rs->sr_err != LDAP_SUCCESS ) {
1014                 return rs->sr_err;
1015         }
1016
1017         if ( !BER_BVISNULL( &id ) ) {
1018                 char idNul = id.bv_val[id.bv_len];
1019                 id.bv_val[id.bv_len] = '\0';
1020                 rs->sr_err = dnPrettyNormal( NULL, &id, &op->o_req_dn,
1021                                 &op->o_req_ndn, op->o_tmpmemctx );
1022                 id.bv_val[id.bv_len] = idNul;
1023                 if ( rs->sr_err != LDAP_SUCCESS ) {
1024                         rs->sr_text = "Invalid DN";
1025                         return rs->sr_err;
1026                 }
1027
1028         } else {
1029                 ber_dupbv_x( &op->o_req_dn, &op->o_dn, op->o_tmpmemctx );
1030                 ber_dupbv_x( &op->o_req_ndn, &op->o_ndn, op->o_tmpmemctx );
1031         }
1032
1033         roc = rwm_callback_get( op, rs );
1034
1035         rc = rwm_op_dn_massage( op, rs, "extendedDN", &roc->ros );
1036         if ( rc != LDAP_SUCCESS ) {
1037                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1038                 send_ldap_error( op, rs, rc, "extendedDN massage error" );
1039                 return -1;
1040         }
1041
1042         ber = ber_alloc_t( LBER_USE_DER );
1043         if ( !ber ) {
1044                 rs->sr_err = LDAP_OTHER;
1045                 rs->sr_text = "No memory";
1046                 return rs->sr_err;
1047         }
1048         ber_printf( ber, "{" );
1049         if ( !BER_BVISNULL( &id )) {
1050                 ber_printf( ber, "tO", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, 
1051                         &op->o_req_dn );
1052         }
1053         if ( !BER_BVISNULL( &pwold )) {
1054                 ber_printf( ber, "tO", LDAP_TAG_EXOP_MODIFY_PASSWD_OLD, &pwold );
1055         }
1056         if ( !BER_BVISNULL( &pwnew )) {
1057                 ber_printf( ber, "tO", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, &pwnew );
1058         }
1059         ber_printf( ber, "N}" );
1060         ber_flatten( ber, &op->ore_reqdata );
1061         ber_free( ber, 1 );
1062
1063         op->o_callback = &roc->cb;
1064
1065         return SLAP_CB_CONTINUE;
1066 }
1067
1068 static struct exop {
1069         struct berval   oid;
1070         BI_op_extended  *extended;
1071 } exop_table[] = {
1072         { BER_BVC(LDAP_EXOP_MODIFY_PASSWD),     rwm_exop_passwd },
1073         { BER_BVNULL, NULL }
1074 };
1075
1076 static int
1077 rwm_extended( Operation *op, SlapReply *rs )
1078 {
1079         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
1080         int                     rc;
1081         rwm_op_cb *roc;
1082
1083         int     i;
1084
1085         for ( i = 0; exop_table[i].extended != NULL; i++ ) {
1086                 if ( bvmatch( &exop_table[i].oid, &op->oq_extended.rs_reqoid ) )
1087                 {
1088                         rc = exop_table[i].extended( op, rs );
1089                         switch ( rc ) {
1090                         case LDAP_SUCCESS:
1091                                 break;
1092
1093                         case SLAP_CB_CONTINUE:
1094                         case SLAPD_ABANDON:
1095                                 return rc;
1096
1097                         default:
1098                                 send_ldap_result( op, rs );
1099                                 return rc;
1100                         }
1101                         break;
1102                 }
1103         }
1104
1105         roc = rwm_callback_get( op, rs );
1106
1107         rc = rwm_op_dn_massage( op, rs, "extendedDN", &roc->ros );
1108         if ( rc != LDAP_SUCCESS ) {
1109                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1110                 send_ldap_error( op, rs, rc, "extendedDN massage error" );
1111                 return -1;
1112         }
1113
1114         /* TODO: rewrite/map extended data ? ... */
1115         op->o_callback = &roc->cb;
1116
1117         return SLAP_CB_CONTINUE;
1118 }
1119
1120 static int
1121 rwm_matched( Operation *op, SlapReply *rs )
1122 {
1123         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
1124         struct ldaprwmap        *rwmap = 
1125                         (struct ldaprwmap *)on->on_bi.bi_private;
1126
1127         struct berval           dn, mdn;
1128         dncookie                dc;
1129         int                     rc;
1130
1131         if ( rs->sr_matched == NULL ) {
1132                 return SLAP_CB_CONTINUE;
1133         }
1134
1135         dc.rwmap = rwmap;
1136         dc.conn = op->o_conn;
1137         dc.rs = rs;
1138         dc.ctx = "matchedDN";
1139         ber_str2bv( rs->sr_matched, 0, 0, &dn );
1140         mdn = dn;
1141         rc = rwm_dn_massage_pretty( &dc, &dn, &mdn );
1142         if ( rc != LDAP_SUCCESS ) {
1143                 rs->sr_err = rc;
1144                 rs->sr_text = "Rewrite error";
1145                 return 1;
1146         }
1147
1148         if ( mdn.bv_val != dn.bv_val ) {
1149                 if ( rs->sr_flags & REP_MATCHED_MUSTBEFREED ) {
1150                         ch_free( (void *)rs->sr_matched );
1151
1152                 } else {
1153                         rs->sr_flags |= REP_MATCHED_MUSTBEFREED;
1154                 }
1155                 rs->sr_matched = mdn.bv_val;
1156         }
1157         
1158         return SLAP_CB_CONTINUE;
1159 }
1160
1161 static int
1162 rwm_attrs( Operation *op, SlapReply *rs, Attribute** a_first, int stripEntryDN )
1163 {
1164         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
1165         struct ldaprwmap        *rwmap = 
1166                         (struct ldaprwmap *)on->on_bi.bi_private;
1167
1168         dncookie                dc;
1169         int                     rc;
1170         Attribute               **ap;
1171         int                     isupdate;
1172         int                     check_duplicate_attrs = 0;
1173
1174         /*
1175          * Rewrite the dn attrs, if needed
1176          */
1177         dc.rwmap = rwmap;
1178         dc.conn = op->o_conn;
1179         dc.rs = NULL; 
1180
1181         /* FIXME: the entries are in the remote mapping form;
1182          * so we need to select those attributes we are willing
1183          * to return, and remap them accordingly */
1184
1185         /* FIXME: in principle, one could map an attribute
1186          * on top of another, which already exists.
1187          * As such, in the end there might exist more than
1188          * one instance of an attribute.
1189          * We should at least check if this occurs, and issue
1190          * an error (because multiple instances of attrs in 
1191          * response are not valid), or merge the values (what
1192          * about duplicate values?) */
1193         isupdate = be_shadow_update( op );
1194         for ( ap = a_first; *ap; ) {
1195                 struct ldapmapping      *mapping = NULL;
1196                 int                     drop_missing;
1197                 int                     last = -1;
1198                 Attribute               *a;
1199
1200                 if ( op->ors_attrs != NULL && 
1201                                 !SLAP_USERATTRS( rs->sr_attr_flags ) &&
1202                                 !ad_inlist( (*ap)->a_desc, op->ors_attrs ) )
1203                 {
1204                         goto cleanup_attr;
1205                 }
1206
1207                 drop_missing = rwm_mapping( &rwmap->rwm_at,
1208                                 &(*ap)->a_desc->ad_cname, &mapping, RWM_REMAP );
1209                 if ( drop_missing || ( mapping != NULL && BER_BVISEMPTY( &mapping->m_dst ) ) )
1210                 {
1211                         goto cleanup_attr;
1212                 }
1213                 if ( mapping != NULL ) {
1214                         assert( mapping->m_dst_ad != NULL );
1215
1216                         /* try to normalize mapped Attributes if the original 
1217                          * AttributeType was not normalized */
1218                         if ( (!(*ap)->a_desc->ad_type->sat_equality || 
1219                                 !(*ap)->a_desc->ad_type->sat_equality->smr_normalize) &&
1220                                 mapping->m_dst_ad->ad_type->sat_equality &&
1221                                 mapping->m_dst_ad->ad_type->sat_equality->smr_normalize )
1222                         {
1223                                 if ((rwmap->rwm_flags & RWM_F_NORMALIZE_MAPPED_ATTRS))
1224                                 {
1225                                         int i = 0;
1226
1227                                         last = (*ap)->a_numvals;
1228                                         if ( last )
1229                                         {
1230                                                 (*ap)->a_nvals = ch_malloc( (last+1) * sizeof(struct berval) );
1231
1232                                                 for ( i = 0; !BER_BVISNULL( &(*ap)->a_vals[i]); i++ ) {
1233                                                         int             rc;
1234                                                         /*
1235                                                          * check that each value is valid per syntax
1236                                                          * and pretty if appropriate
1237                                                          */
1238                                                         rc = mapping->m_dst_ad->ad_type->sat_equality->smr_normalize(
1239                                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1240                                                                 mapping->m_dst_ad->ad_type->sat_syntax,
1241                                                                 mapping->m_dst_ad->ad_type->sat_equality,
1242                                                                 &(*ap)->a_vals[i], &(*ap)->a_nvals[i],
1243                                                                 NULL );
1244
1245                                                         if ( rc != LDAP_SUCCESS ) {
1246                                                                 BER_BVZERO( &(*ap)->a_nvals[i] );
1247                                                         }
1248                                                 }
1249                                                 BER_BVZERO( &(*ap)->a_nvals[i] );
1250                                         }
1251
1252                                 } else {
1253                                         assert( (*ap)->a_nvals == (*ap)->a_vals );
1254                                         (*ap)->a_nvals = NULL;
1255                                         ber_bvarray_dup_x( &(*ap)->a_nvals, (*ap)->a_vals, NULL );
1256                                 }
1257                         }
1258
1259                         /* rewrite the attribute description */
1260                         (*ap)->a_desc = mapping->m_dst_ad;
1261
1262                         /* will need to check for duplicate attrs */
1263                         check_duplicate_attrs++;
1264                 }
1265
1266                 if ( (*ap)->a_desc == slap_schema.si_ad_entryDN ) {
1267                         if ( stripEntryDN ) {
1268                                 /* will be generated by frontend */
1269                                 goto cleanup_attr;
1270                         }
1271                         
1272                 } else if ( !isupdate
1273                         && !get_relax( op )
1274                         && (*ap)->a_desc->ad_type->sat_no_user_mod 
1275                         && (*ap)->a_desc->ad_type != slap_schema.si_at_undefined )
1276                 {
1277                         goto next_attr;
1278                 }
1279
1280                 if ( last == -1 ) { /* not yet counted */ 
1281                         last = (*ap)->a_numvals;
1282                 }
1283
1284                 if ( last == 0 ) {
1285                         /* empty? leave it in place because of attrsonly and vlv */
1286                         goto next_attr;
1287                 }
1288                 last--;
1289
1290                 if ( (*ap)->a_desc == slap_schema.si_ad_objectClass
1291                                 || (*ap)->a_desc == slap_schema.si_ad_structuralObjectClass )
1292                 {
1293                         struct berval   *bv;
1294                         
1295                         for ( bv = (*ap)->a_vals; !BER_BVISNULL( bv ); bv++ ) {
1296                                 struct berval   mapped;
1297
1298                                 rwm_map( &rwmap->rwm_oc, &bv[0], &mapped, RWM_REMAP );
1299                                 if ( BER_BVISNULL( &mapped ) || BER_BVISEMPTY( &mapped ) ) {
1300 remove_oc:;
1301                                         ch_free( bv[0].bv_val );
1302                                         BER_BVZERO( &bv[0] );
1303                                         if ( &(*ap)->a_vals[last] > &bv[0] ) {
1304                                                 bv[0] = (*ap)->a_vals[last];
1305                                                 BER_BVZERO( &(*ap)->a_vals[last] );
1306                                         }
1307                                         last--;
1308                                         bv--;
1309
1310                                 } else if ( mapped.bv_val != bv[0].bv_val
1311                                         && ber_bvstrcasecmp( &mapped, &bv[0] ) != 0 )
1312                                 {
1313                                         int     i;
1314
1315                                         for ( i = 0; !BER_BVISNULL( &(*ap)->a_vals[ i ] ); i++ ) {
1316                                                 if ( &(*ap)->a_vals[ i ] == bv ) {
1317                                                         continue;
1318                                                 }
1319
1320                                                 if ( ber_bvstrcasecmp( &mapped, &(*ap)->a_vals[ i ] ) == 0 ) {
1321                                                         break;
1322                                                 }
1323                                         }
1324
1325                                         if ( !BER_BVISNULL( &(*ap)->a_vals[ i ] ) ) {
1326                                                 goto remove_oc;
1327                                         }
1328
1329                                         /*
1330                                          * FIXME: after LBER_FREEing
1331                                          * the value is replaced by
1332                                          * ch_alloc'ed memory
1333                                          */
1334                                         ber_bvreplace( &bv[0], &mapped );
1335
1336                                         /* FIXME: will need to check
1337                                          * if the structuralObjectClass
1338                                          * changed */
1339                                 }
1340                         }
1341
1342                 /*
1343                  * It is necessary to try to rewrite attributes with
1344                  * dn syntax because they might be used in ACLs as
1345                  * members of groups; since ACLs are applied to the
1346                  * rewritten stuff, no dn-based subject clause could
1347                  * be used at the ldap backend side (see
1348                  * http://www.OpenLDAP.org/faq/data/cache/452.html)
1349                  * The problem can be overcome by moving the dn-based
1350                  * ACLs to the target directory server, and letting
1351                  * everything pass thru the ldap backend. */
1352                 /* FIXME: handle distinguishedName-like syntaxes, like
1353                  * nameAndOptionalUID */
1354                 } else if ( (*ap)->a_desc->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName
1355                                 || ( mapping != NULL && mapping->m_src_ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName ) )
1356                 {
1357                         dc.ctx = "searchAttrDN";
1358                         rc = rwm_dnattr_result_rewrite( &dc, (*ap)->a_vals, (*ap)->a_nvals );
1359                         if ( rc != LDAP_SUCCESS ) {
1360                                 goto cleanup_attr;
1361                         }
1362
1363                 } else if ( (*ap)->a_desc == slap_schema.si_ad_ref ) {
1364                         dc.ctx = "searchAttrDN";
1365                         rc = rwm_referral_result_rewrite( &dc, (*ap)->a_vals );
1366                         if ( rc != LDAP_SUCCESS ) {
1367                                 goto cleanup_attr;
1368                         }
1369                 }
1370
1371
1372 next_attr:;
1373                 ap = &(*ap)->a_next;
1374                 continue;
1375
1376 cleanup_attr:;
1377                 a = *ap;
1378                 *ap = (*ap)->a_next;
1379
1380                 attr_free( a );
1381         }
1382
1383         /* only check if some mapping occurred */
1384         if ( check_duplicate_attrs ) {
1385                 for ( ap = a_first; *ap != NULL; ap = &(*ap)->a_next ) {
1386                         Attribute       **tap;
1387
1388                         for ( tap = &(*ap)->a_next; *tap != NULL; ) {
1389                                 if ( (*tap)->a_desc == (*ap)->a_desc ) {
1390                                         Entry           e = { 0 };
1391                                         Modification    mod = { 0 };
1392                                         const char      *text = NULL;
1393                                         char            textbuf[ SLAP_TEXT_BUFLEN ];
1394                                         Attribute       *next = (*tap)->a_next;
1395
1396                                         BER_BVSTR( &e.e_name, "" );
1397                                         BER_BVSTR( &e.e_nname, "" );
1398                                         e.e_attrs = *ap;
1399                                         mod.sm_op = LDAP_MOD_ADD;
1400                                         mod.sm_desc = (*ap)->a_desc;
1401                                         mod.sm_type = mod.sm_desc->ad_cname;
1402                                         mod.sm_numvals = (*tap)->a_numvals;
1403                                         mod.sm_values = (*tap)->a_vals;
1404                                         if ( (*tap)->a_nvals != (*tap)->a_vals ) {
1405                                                 mod.sm_nvalues = (*tap)->a_nvals;
1406                                         }
1407
1408                                         (void)modify_add_values( &e, &mod,
1409                                                 /* permissive */ 1,
1410                                                 &text, textbuf, sizeof( textbuf ) );
1411
1412                                         /* should not insert new attrs! */
1413                                         assert( e.e_attrs == *ap );
1414
1415                                         attr_free( *tap );
1416                                         *tap = next;
1417
1418                                 } else {
1419                                         tap = &(*tap)->a_next;
1420                                 }
1421                         }
1422                 }
1423         }
1424
1425         return 0;
1426 }
1427
1428 static int
1429 rwm_send_entry( Operation *op, SlapReply *rs )
1430 {
1431         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
1432         struct ldaprwmap        *rwmap = 
1433                         (struct ldaprwmap *)on->on_bi.bi_private;
1434
1435         Entry                   *e = NULL;
1436         slap_mask_t             flags;
1437         struct berval           dn = BER_BVNULL,
1438                                 ndn = BER_BVNULL;
1439         dncookie                dc;
1440         int                     rc;
1441
1442         assert( rs->sr_entry != NULL );
1443
1444         /*
1445          * Rewrite the dn of the result, if needed
1446          */
1447         dc.rwmap = rwmap;
1448         dc.conn = op->o_conn;
1449         dc.rs = NULL; 
1450         dc.ctx = "searchEntryDN";
1451
1452         e = rs->sr_entry;
1453         flags = rs->sr_flags;
1454         if ( !( rs->sr_flags & REP_ENTRY_MODIFIABLE ) ) {
1455                 /* FIXME: all we need to duplicate are:
1456                  * - dn
1457                  * - ndn
1458                  * - attributes that are requested
1459                  * - no values if attrsonly is set
1460                  */
1461
1462                 e = entry_dup( e );
1463                 if ( e == NULL ) {
1464                         rc = LDAP_NO_MEMORY;
1465                         goto fail;
1466                 }
1467
1468                 flags &= ~REP_ENTRY_MUSTRELEASE;
1469                 flags |= ( REP_ENTRY_MODIFIABLE | REP_ENTRY_MUSTBEFREED );
1470         }
1471
1472         /*
1473          * Note: this may fail if the target host(s) schema differs
1474          * from the one known to the meta, and a DN with unknown
1475          * attributes is returned.
1476          */
1477         dn = e->e_name;
1478         ndn = e->e_nname;
1479         rc = rwm_dn_massage_pretty_normalize( &dc, &e->e_name, &dn, &ndn );
1480         if ( rc != LDAP_SUCCESS ) {
1481                 rc = 1;
1482                 goto fail;
1483         }
1484
1485         if ( e->e_name.bv_val != dn.bv_val ) {
1486                 ch_free( e->e_name.bv_val );
1487                 ch_free( e->e_nname.bv_val );
1488
1489                 e->e_name = dn;
1490                 e->e_nname = ndn;
1491         }
1492
1493         /* TODO: map entry attribute types, objectclasses 
1494          * and dn-valued attribute values */
1495
1496         /* FIXME: the entries are in the remote mapping form;
1497          * so we need to select those attributes we are willing
1498          * to return, and remap them accordingly */
1499         (void)rwm_attrs( op, rs, &e->e_attrs, 1 );
1500
1501         if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
1502                 overlay_entry_release_ov( op, rs->sr_entry, 0, on );
1503         }
1504
1505         rs->sr_entry = e;
1506         rs->sr_flags = flags;
1507
1508         return SLAP_CB_CONTINUE;
1509
1510 fail:;
1511         if ( e != NULL && e != rs->sr_entry ) {
1512                 if ( e->e_name.bv_val == dn.bv_val ) {
1513                         BER_BVZERO( &e->e_name );
1514                 }
1515
1516                 if ( e->e_nname.bv_val == ndn.bv_val ) {
1517                         BER_BVZERO( &e->e_nname );
1518                 }
1519
1520                 entry_free( e );
1521         }
1522
1523         if ( !BER_BVISNULL( &dn ) ) {
1524                 ch_free( dn.bv_val );
1525         }
1526
1527         if ( !BER_BVISNULL( &ndn ) ) {
1528                 ch_free( ndn.bv_val );
1529         }
1530
1531         return rc;
1532 }
1533
1534 static int
1535 rwm_operational( Operation *op, SlapReply *rs )
1536 {
1537         /* FIXME: the entries are in the remote mapping form;
1538          * so we need to select those attributes we are willing
1539          * to return, and remap them accordingly */
1540         if ( rs->sr_operational_attrs ) {
1541                 rwm_attrs( op, rs, &rs->sr_operational_attrs, 1 );
1542         }
1543
1544         return SLAP_CB_CONTINUE;
1545 }
1546
1547 #if 0
1548 /* don't use this; it cannot be reverted, and leaves op->o_req_dn
1549  * rewritten for subsequent operations; fine for plain suffixmassage,
1550  * but destroys everything else */
1551 static int
1552 rwm_chk_referrals( Operation *op, SlapReply *rs )
1553 {
1554         slap_overinst           *on = (slap_overinst *) op->o_bd->bd_info;
1555         int                     rc;
1556
1557         rc = rwm_op_dn_massage( op, rs, "referralCheckDN" );
1558         if ( rc != LDAP_SUCCESS ) {
1559                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1560                 send_ldap_error( op, rs, rc, "referralCheckDN massage error" );
1561                 return -1;
1562         }
1563
1564         return SLAP_CB_CONTINUE;
1565 }
1566 #endif
1567
1568 static int
1569 rwm_rw_config(
1570         BackendDB       *be,
1571         const char      *fname,
1572         int             lineno,
1573         int             argc,
1574         char            **argv )
1575 {
1576         slap_overinst           *on = (slap_overinst *) be->bd_info;
1577         struct ldaprwmap        *rwmap = 
1578                         (struct ldaprwmap *)on->on_bi.bi_private;
1579
1580         return rewrite_parse( rwmap->rwm_rw,
1581                                 fname, lineno, argc, argv );
1582
1583         return 0;
1584 }
1585
1586 static int
1587 rwm_suffixmassage_config(
1588         BackendDB       *be,
1589         const char      *fname,
1590         int             lineno,
1591         int             argc,
1592         char            **argv )
1593 {
1594         slap_overinst           *on = (slap_overinst *) be->bd_info;
1595         struct ldaprwmap        *rwmap = 
1596                         (struct ldaprwmap *)on->on_bi.bi_private;
1597
1598         struct berval           bvnc, nvnc, pvnc, brnc, nrnc, prnc;
1599         int                     massaged;
1600         int                     rc;
1601                 
1602         /*
1603          * syntax:
1604          * 
1605          *      suffixmassage [<suffix>] <massaged suffix>
1606          *
1607          * the [<suffix>] field must be defined as a valid suffix
1608          * for the current database;
1609          * the <massaged suffix> shouldn't have already been
1610          * defined as a valid suffix for the current server
1611          */
1612         if ( argc == 2 ) {
1613                 if ( be->be_suffix == NULL ) {
1614                         fprintf( stderr, "%s: line %d: "
1615                                        " \"suffixMassage [<suffix>]"
1616                                        " <massaged suffix>\" without "
1617                                        "<suffix> part requires database "
1618                                        "suffix be defined first.\n",
1619                                 fname, lineno );
1620                         return 1;
1621                 }
1622                 bvnc = be->be_suffix[ 0 ];
1623                 massaged = 1;
1624
1625         } else if ( argc == 3 ) {
1626                 ber_str2bv( argv[ 1 ], 0, 0, &bvnc );
1627                 massaged = 2;
1628
1629         } else  {
1630                 fprintf( stderr, "%s: line %d: syntax is"
1631                                " \"suffixMassage [<suffix>]"
1632                                " <massaged suffix>\"\n",
1633                         fname, lineno );
1634                 return 1;
1635         }
1636
1637         if ( dnPrettyNormal( NULL, &bvnc, &pvnc, &nvnc, NULL ) != LDAP_SUCCESS ) {
1638                 fprintf( stderr, "%s: line %d: suffix DN %s is invalid\n",
1639                         fname, lineno, bvnc.bv_val );
1640                 return 1;
1641         }
1642
1643         ber_str2bv( argv[ massaged ], 0, 0, &brnc );
1644         if ( dnPrettyNormal( NULL, &brnc, &prnc, &nrnc, NULL ) != LDAP_SUCCESS ) {
1645                 fprintf( stderr, "%s: line %d: suffix DN %s is invalid\n",
1646                                 fname, lineno, brnc.bv_val );
1647                 free( nvnc.bv_val );
1648                 free( pvnc.bv_val );
1649                 return 1;
1650         }
1651
1652         /*
1653          * The suffix massaging is emulated 
1654          * by means of the rewrite capabilities
1655          */
1656         rc = rwm_suffix_massage_config( rwmap->rwm_rw,
1657                         &pvnc, &nvnc, &prnc, &nrnc );
1658         free( nvnc.bv_val );
1659         free( pvnc.bv_val );
1660         free( nrnc.bv_val );
1661         free( prnc.bv_val );
1662
1663         return rc;
1664 }
1665
1666 static int
1667 rwm_m_config(
1668         BackendDB       *be,
1669         const char      *fname,
1670         int             lineno,
1671         int             argc,
1672         char            **argv )
1673 {
1674         slap_overinst           *on = (slap_overinst *) be->bd_info;
1675         struct ldaprwmap        *rwmap = 
1676                         (struct ldaprwmap *)on->on_bi.bi_private;
1677
1678         /* objectclass/attribute mapping */
1679         return rwm_map_config( &rwmap->rwm_oc,
1680                         &rwmap->rwm_at,
1681                         fname, lineno, argc, argv );
1682 }
1683
1684 static int
1685 rwm_response( Operation *op, SlapReply *rs )
1686 {
1687         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1688         struct ldaprwmap        *rwmap = 
1689                         (struct ldaprwmap *)on->on_bi.bi_private;
1690
1691         int             rc;
1692
1693         if ( op->o_tag == LDAP_REQ_SEARCH && rs->sr_type == REP_SEARCH ) {
1694                 return rwm_send_entry( op, rs );
1695         }
1696
1697         switch( op->o_tag ) {
1698         case LDAP_REQ_SEARCH:
1699         case LDAP_REQ_BIND:
1700         case LDAP_REQ_ADD:
1701         case LDAP_REQ_DELETE:
1702         case LDAP_REQ_MODRDN:
1703         case LDAP_REQ_MODIFY:
1704         case LDAP_REQ_COMPARE:
1705         case LDAP_REQ_EXTENDED:
1706                 if ( rs->sr_ref ) {
1707                         dncookie                dc;
1708
1709                         /*
1710                          * Rewrite the dn of the referrals, if needed
1711                          */
1712                         dc.rwmap = rwmap;
1713                         dc.conn = op->o_conn;
1714                         dc.rs = NULL; 
1715                         dc.ctx = "referralDN";
1716                         rc = rwm_referral_result_rewrite( &dc, rs->sr_ref );
1717                         if ( rc != LDAP_SUCCESS ) {
1718                                 rc = 1;
1719                                 break;
1720                         }
1721                 }
1722                 rc = rwm_matched( op, rs );
1723                 break;
1724
1725         default:
1726                 rc = SLAP_CB_CONTINUE;
1727                 break;
1728         }
1729
1730         return rc;
1731 }
1732
1733 static int
1734 rwm_db_config(
1735         BackendDB       *be,
1736         const char      *fname,
1737         int             lineno,
1738         int             argc,
1739         char            **argv )
1740 {
1741         slap_overinst           *on = (slap_overinst *) be->bd_info;
1742         struct ldaprwmap        *rwmap = 
1743                         (struct ldaprwmap *)on->on_bi.bi_private;
1744
1745         int             rc = 0;
1746         char            *argv0 = NULL;
1747
1748         if ( strncasecmp( argv[ 0 ], "rwm-", STRLENOF( "rwm-" ) ) == 0 ) {
1749                 argv0 = argv[ 0 ];
1750                 argv[ 0 ] = &argv0[ STRLENOF( "rwm-" ) ];
1751         }
1752
1753         if ( strncasecmp( argv[0], "rewrite", STRLENOF("rewrite") ) == 0 ) {
1754                 rc = rwm_rw_config( be, fname, lineno, argc, argv );
1755
1756         } else if ( strcasecmp( argv[0], "map" ) == 0 ) {
1757                 rc = rwm_m_config( be, fname, lineno, argc, argv );
1758
1759         } else if ( strcasecmp( argv[0], "suffixmassage" ) == 0 ) {
1760                 rc = rwm_suffixmassage_config( be, fname, lineno, argc, argv );
1761
1762         } else if ( strcasecmp( argv[0], "t-f-support" ) == 0 ) {
1763                 if ( argc != 2 ) {
1764                         fprintf( stderr,
1765                 "%s: line %d: \"t-f-support {no|yes|discover}\" needs 1 argument.\n",
1766                                         fname, lineno );
1767                         return( 1 );
1768                 }
1769
1770                 if ( strcasecmp( argv[ 1 ], "no" ) == 0 ) {
1771                         rwmap->rwm_flags &= ~(RWM_F_SUPPORT_T_F_MASK2);
1772
1773                 } else if ( strcasecmp( argv[ 1 ], "yes" ) == 0 ) {
1774                         rwmap->rwm_flags |= RWM_F_SUPPORT_T_F;
1775
1776                 /* TODO: not implemented yet */
1777                 } else if ( strcasecmp( argv[ 1 ], "discover" ) == 0 ) {
1778                         fprintf( stderr,
1779                 "%s: line %d: \"discover\" not supported yet "
1780                 "in \"t-f-support {no|yes|discover}\".\n",
1781                                         fname, lineno );
1782                         return( 1 );
1783 #if 0
1784                         rwmap->rwm_flags |= RWM_F_SUPPORT_T_F_DISCOVER;
1785 #endif
1786
1787                 } else {
1788                         fprintf( stderr,
1789         "%s: line %d: unknown value \"%s\" for \"t-f-support {no|yes|discover}\".\n",
1790                                 fname, lineno, argv[ 1 ] );
1791                         return 1;
1792                 }
1793
1794         } else if ( strcasecmp( argv[0], "normalize-mapped-attrs" ) ==  0 ) {
1795                 if ( argc !=2 ) { 
1796                         fprintf( stderr,
1797                 "%s: line %d: \"normalize-mapped-attrs {no|yes}\" needs 1 argument.\n",
1798                                         fname, lineno );
1799                         return( 1 );
1800                 }
1801
1802                 if ( strcasecmp( argv[ 1 ], "no" ) == 0 ) {
1803                         rwmap->rwm_flags &= ~(RWM_F_NORMALIZE_MAPPED_ATTRS);
1804
1805                 } else if ( strcasecmp( argv[ 1 ], "yes" ) == 0 ) {
1806                         rwmap->rwm_flags |= RWM_F_NORMALIZE_MAPPED_ATTRS;
1807                 }
1808
1809         } else {
1810                 rc = SLAP_CONF_UNKNOWN;
1811         }
1812
1813         if ( argv0 ) {
1814                 argv[ 0 ] = argv0;
1815         }
1816
1817         return rc;
1818 }
1819
1820 /*
1821  * dynamic configuration...
1822  */
1823
1824 enum {
1825         /* rewrite */
1826         RWM_CF_REWRITE = 1,
1827
1828         /* map */
1829         RWM_CF_MAP,
1830         RWM_CF_T_F_SUPPORT,
1831         RWM_CF_NORMALIZE_MAPPED,
1832
1833         RWM_CF_LAST
1834 };
1835
1836 static slap_verbmasks t_f_mode[] = {
1837         { BER_BVC( "true" ),            RWM_F_SUPPORT_T_F },
1838         { BER_BVC( "yes" ),             RWM_F_SUPPORT_T_F },
1839         { BER_BVC( "discover" ),        RWM_F_SUPPORT_T_F_DISCOVER },
1840         { BER_BVC( "false" ),           RWM_F_NONE },
1841         { BER_BVC( "no" ),              RWM_F_NONE },
1842         { BER_BVNULL,                   0 }
1843 };
1844
1845 static ConfigDriver rwm_cf_gen;
1846
1847 static ConfigTable rwmcfg[] = {
1848         { "rwm-rewrite", "rewrite",
1849                 2, 0, STRLENOF("rwm-rewrite"),
1850                 ARG_MAGIC|RWM_CF_REWRITE, rwm_cf_gen,
1851                 "( OLcfgOvAt:16.1 NAME 'olcRwmRewrite' "
1852                         "DESC 'Rewrites strings' "
1853                         "EQUALITY caseIgnoreMatch "
1854                         "SYNTAX OMsDirectoryString "
1855                         "X-ORDERED 'VALUES' )",
1856                 NULL, NULL },
1857
1858         { "rwm-suffixmassage", "[virtual]> <real",
1859                 2, 3, 0, ARG_MAGIC|RWM_CF_REWRITE, rwm_cf_gen,
1860                 NULL, NULL, NULL },
1861                 
1862         { "rwm-t-f-support", "true|false|discover",
1863                 2, 2, 0, ARG_MAGIC|RWM_CF_T_F_SUPPORT, rwm_cf_gen,
1864                 "( OLcfgOvAt:16.2 NAME 'olcRwmTFSupport' "
1865                         "DESC 'Absolute filters support' "
1866                         "SYNTAX OMsDirectoryString "
1867                         "SINGLE-VALUE )",
1868                 NULL, NULL },
1869
1870         { "rwm-map", "{objectClass|attribute}",
1871                 2, 4, 0, ARG_MAGIC|RWM_CF_MAP, rwm_cf_gen,
1872                 "( OLcfgOvAt:16.3 NAME 'olcRwmMap' "
1873                         "DESC 'maps attributes/objectClasses' "
1874                         "SYNTAX OMsDirectoryString "
1875                         "X-ORDERED 'VALUES' )",
1876                 NULL, NULL },
1877
1878         { "rwm-normalize-mapped-attrs", "true|false",
1879                 2, 2, 0, ARG_MAGIC|ARG_ON_OFF|RWM_CF_NORMALIZE_MAPPED, rwm_cf_gen,
1880                 "( OLcfgOvAt:16.4 NAME 'olcRwmNormalizeMapped' "
1881                         "DESC 'Normalize mapped attributes/objectClasses' "
1882                         "SYNTAX OMsBoolean "
1883                         "SINGLE-VALUE )",
1884                 NULL, NULL },
1885
1886         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1887 };
1888
1889 static ConfigOCs rwmocs[] = {
1890         { "( OLcfgOvOc:16.1 "
1891                 "NAME 'olcRwmConfig' "
1892                 "DESC 'Rewrite/remap configuration' "
1893                 "SUP olcOverlayConfig "
1894                 "MAY ( "
1895                         "olcRwmRewrite $ "
1896                         "olcRwmTFSupport $ "
1897                         "olcRwmMap $ "
1898                         "olcRwmNormalizeMapped "
1899                         ") )",
1900                 Cft_Overlay, rwmcfg, NULL, NULL },
1901         { NULL, 0, NULL }
1902 };
1903
1904 static void
1905 slap_rewrite_unparse( BerVarray in, BerVarray *out )
1906 {
1907         int             i;
1908         BerVarray       bva = NULL;
1909         char            ibuf[32], *ptr;
1910         struct berval   idx;
1911
1912         assert( in != NULL );
1913
1914         for ( i = 0; !BER_BVISNULL( &in[i] ); i++ )
1915                 /* count'em */ ;
1916
1917         if ( i == 0 ) {
1918                 return;
1919         }
1920
1921         idx.bv_val = ibuf;
1922
1923         bva = ch_malloc( ( i + 1 ) * sizeof(struct berval) );
1924         BER_BVZERO( &bva[ 0 ] );
1925
1926         for ( i = 0; !BER_BVISNULL( &in[i] ); i++ ) {
1927                 idx.bv_len = snprintf( idx.bv_val, sizeof( ibuf ), "{%d}", i );
1928                 if ( idx.bv_len >= sizeof( ibuf ) ) {
1929                         ber_bvarray_free( bva );
1930                         return;
1931                 }
1932
1933                 bva[i].bv_len = idx.bv_len + in[i].bv_len;
1934                 bva[i].bv_val = ch_malloc( bva[i].bv_len + 1 );
1935                 ptr = lutil_strcopy( bva[i].bv_val, ibuf );
1936                 ptr = lutil_strcopy( ptr, in[i].bv_val );
1937                 *ptr = '\0';
1938                 BER_BVZERO( &bva[ i + 1 ] );
1939         }
1940
1941         *out = bva;
1942 }
1943
1944 static int
1945 rwm_bva_rewrite_add(
1946         struct ldaprwmap        *rwmap,
1947         int                     idx,
1948         char                    **argv )
1949 {
1950         char            *line;
1951         struct berval   bv;
1952
1953         line = ldap_charray2str( argv, "\" \"" );
1954         if ( line != NULL ) {
1955                 int     len = strlen( argv[ 0 ] );
1956
1957                 ber_str2bv( line, 0, 0, &bv );
1958                 AC_MEMCPY( &bv.bv_val[ len ], &bv.bv_val[ len + 1 ],
1959                         bv.bv_len - ( len + 1 ) );
1960                 bv.bv_val[ bv.bv_len - 1 ] = '"';
1961
1962                 if ( idx == -1 ) {
1963                         ber_bvarray_add( &rwmap->rwm_bva_rewrite, &bv );
1964
1965                 } else {
1966                         rwmap->rwm_bva_rewrite[ idx ] = bv;
1967                 }
1968         }
1969
1970         return 0;
1971 }
1972
1973 static int
1974 rwm_info_init( struct rewrite_info ** rwm_rw )
1975 {
1976         char                    *rargv[ 3 ];
1977
1978         *rwm_rw = rewrite_info_init( REWRITE_MODE_USE_DEFAULT );
1979         if ( *rwm_rw == NULL ) {
1980                 return -1;
1981         }
1982
1983         /* this rewriteContext by default must be null;
1984          * rules can be added if required */
1985         rargv[ 0 ] = "rewriteContext";
1986         rargv[ 1 ] = "searchFilter";
1987         rargv[ 2 ] = NULL;
1988         rewrite_parse( *rwm_rw, "<suffix massage>", 1, 2, rargv );
1989
1990         rargv[ 0 ] = "rewriteContext";
1991         rargv[ 1 ] = "default";
1992         rargv[ 2 ] = NULL;
1993         rewrite_parse( *rwm_rw, "<suffix massage>", 2, 2, rargv );
1994
1995         return 0;
1996 }
1997
1998 static int
1999 rwm_cf_gen( ConfigArgs *c )
2000 {
2001         slap_overinst           *on = (slap_overinst *)c->bi;
2002         struct ldaprwmap        *rwmap = 
2003                         (struct ldaprwmap *)on->on_bi.bi_private;
2004
2005         BackendDB               db;
2006         char                    *argv0;
2007         int                     idx0 = 0;
2008         int                     rc = 0;
2009
2010         db = *c->be;
2011         db.bd_info = c->bi;
2012
2013         if ( c->op == SLAP_CONFIG_EMIT ) {
2014                 struct berval   bv = BER_BVNULL;
2015
2016                 switch ( c->type ) {
2017                 case RWM_CF_REWRITE:
2018                         if ( rwmap->rwm_bva_rewrite == NULL ) {
2019                                 rc = 1;
2020
2021                         } else {
2022                                 slap_rewrite_unparse( rwmap->rwm_bva_rewrite, &c->rvalue_vals );
2023                                 if ( !c->rvalue_vals ) {
2024                                         rc = 1;
2025                                 }
2026                         }
2027                         break;
2028
2029                 case RWM_CF_T_F_SUPPORT:
2030                         enum_to_verb( t_f_mode, (rwmap->rwm_flags & RWM_F_SUPPORT_T_F_MASK2), &bv );
2031                         if ( BER_BVISNULL( &bv ) ) {
2032                                 /* there's something wrong... */
2033                                 assert( 0 );
2034                                 rc = 1;
2035
2036                         } else {
2037                                 value_add_one( &c->rvalue_vals, &bv );
2038                         }
2039                         break;
2040
2041                 case RWM_CF_MAP:
2042                         if ( rwmap->rwm_bva_map == NULL ) {
2043                                 rc = 1;
2044
2045                         } else {
2046                                 value_add( &c->rvalue_vals, rwmap->rwm_bva_map );
2047                         }
2048                         break;
2049
2050                 case RWM_CF_NORMALIZE_MAPPED:
2051                         c->value_int = ( rwmap->rwm_flags & RWM_F_NORMALIZE_MAPPED_ATTRS );
2052                         break;
2053
2054                 default:
2055                         assert( 0 );
2056                         rc = 1;
2057                 }
2058
2059                 return rc;
2060
2061         } else if ( c->op == LDAP_MOD_DELETE ) {
2062                 switch ( c->type ) {
2063                 case RWM_CF_REWRITE:
2064                         if ( c->valx >= 0 ) {
2065                                 ConfigArgs ca = { 0 };
2066                                 int i;
2067
2068                                 for ( i = 0; !BER_BVISNULL( &rwmap->rwm_bva_rewrite[ i ] ); i++ )
2069                                         /* count'em */ ;
2070
2071                                 if ( i >= c->valx ) {
2072                                         rc = 1;
2073                                         break;
2074                                 }
2075
2076                                 ber_memfree( rwmap->rwm_bva_rewrite[ c->valx ].bv_val );
2077                                 for ( i = c->valx; !BER_BVISNULL( &rwmap->rwm_bva_rewrite[ i + 1 ] ); i++ )
2078                                 {
2079                                         rwmap->rwm_bva_rewrite[ i ] = rwmap->rwm_bva_rewrite[ i + 1 ];
2080                                 }
2081                                 BER_BVZERO( &rwmap->rwm_bva_rewrite[ i ] );
2082
2083                                 rewrite_info_delete( &rwmap->rwm_rw );
2084                                 assert( rwmap->rwm_rw == NULL );
2085
2086                                 rc = rwm_info_init( &rwmap->rwm_rw );
2087
2088                                 for ( i = 0; !BER_BVISNULL( &rwmap->rwm_bva_rewrite[ i ] ); i++ )
2089                                 {
2090                                         ca.line = rwmap->rwm_bva_rewrite[ i ].bv_val;
2091                                         ca.argc = 0;
2092                                         config_fp_parse_line( &ca );
2093                                         
2094                                         if ( strcasecmp( ca.argv[ 0 ], "suffixmassage" ) == 0 ) {
2095                                                 rc = rwm_suffixmassage_config( &db, c->fname, c->lineno,
2096                                                         ca.argc, ca.argv );
2097
2098                                         } else {
2099                                                 rc = rwm_rw_config( &db, c->fname, c->lineno,
2100                                                         ca.argc, ca.argv );
2101                                         }
2102
2103                                         ch_free( ca.tline );
2104
2105                                         assert( rc == 0 );
2106                                 }
2107
2108                         } else if ( rwmap->rwm_rw != NULL ) {
2109                                 rewrite_info_delete( &rwmap->rwm_rw );
2110                                 assert( rwmap->rwm_rw == NULL );
2111
2112                                 ber_bvarray_free( rwmap->rwm_bva_rewrite );
2113                                 rwmap->rwm_bva_rewrite = NULL;
2114
2115                                 rc = rwm_info_init( &rwmap->rwm_rw );
2116                         }
2117                         break;
2118
2119                 case RWM_CF_T_F_SUPPORT:
2120                         rwmap->rwm_flags &= ~RWM_F_SUPPORT_T_F_MASK2;
2121                         break;
2122
2123                 case RWM_CF_MAP:
2124                         if ( c->valx >= 0 ) {
2125                                 /* single modification is not allowed */
2126                                 rc = 1;
2127
2128                         } else {
2129                                 avl_free( rwmap->rwm_oc.remap, rwm_mapping_dst_free );
2130                                 avl_free( rwmap->rwm_oc.map, rwm_mapping_free );
2131                                 avl_free( rwmap->rwm_at.remap, rwm_mapping_dst_free );
2132                                 avl_free( rwmap->rwm_at.map, rwm_mapping_free );
2133
2134                                 rwmap->rwm_oc.remap = NULL;
2135                                 rwmap->rwm_oc.map = NULL;
2136                                 rwmap->rwm_at.remap = NULL;
2137                                 rwmap->rwm_at.map = NULL;
2138
2139                                 ber_bvarray_free( rwmap->rwm_bva_map );
2140                                 rwmap->rwm_bva_map = NULL;
2141                         }
2142                         break;
2143
2144                 case RWM_CF_NORMALIZE_MAPPED:
2145                         rwmap->rwm_flags &= ~RWM_F_NORMALIZE_MAPPED_ATTRS;
2146                         break;
2147
2148                 default:
2149                         return 1;
2150                 }
2151                 return rc;
2152         }
2153
2154         if ( strncasecmp( c->argv[ 0 ], "olcRwm", STRLENOF( "olcRwm" ) ) == 0 ) {
2155                 idx0 = 1;
2156         }
2157
2158         switch ( c->type ) {
2159         case RWM_CF_REWRITE:
2160                 if ( c->valx >= 0 ) {
2161                         struct rewrite_info *rwm_rw = rwmap->rwm_rw;
2162                         ConfigArgs ca = { 0 };
2163                         int i, last;
2164
2165                         for ( last = 0; !BER_BVISNULL( &rwmap->rwm_bva_rewrite[ last ] ); last++ )
2166                                 /* count'em */ ;
2167
2168                         if ( c->valx > last ) {
2169                                 c->valx = last;
2170                         }
2171
2172                         rwmap->rwm_rw = NULL;
2173                         rc = rwm_info_init( &rwmap->rwm_rw );
2174
2175                         for ( i = 0; i < c->valx; i++ ) {
2176                                 ca.line = rwmap->rwm_bva_rewrite[ i ].bv_val;
2177                                 ca.argc = 0;
2178                                 config_fp_parse_line( &ca );
2179
2180                                 argv0 = ca.argv[ 0 ];
2181                                 ca.argv[ 0 ] += STRLENOF( "rwm-" );
2182                                 
2183                                 if ( strcasecmp( ca.argv[ 0 ], "suffixmassage" ) == 0 ) {
2184                                         rc = rwm_suffixmassage_config( &db, c->fname, c->lineno,
2185                                                 ca.argc, ca.argv );
2186
2187                                 } else {
2188                                         rc = rwm_rw_config( &db, c->fname, c->lineno,
2189                                                 ca.argc, ca.argv );
2190                                 }
2191
2192                                 ca.argv[ 0 ] = argv0;
2193
2194                                 ch_free( ca.tline );
2195
2196                                 assert( rc == 0 );
2197                         }
2198
2199                         argv0 = c->argv[ idx0 ];
2200                         if ( strncasecmp( argv0, "rwm-", STRLENOF( "rwm-" ) ) != 0 ) {
2201                                 return 1;
2202                         }
2203                         c->argv[ idx0 ] += STRLENOF( "rwm-" );
2204                         if ( strcasecmp( c->argv[ idx0 ], "suffixmassage" ) == 0 ) {
2205                                 rc = rwm_suffixmassage_config( &db, c->fname, c->lineno,
2206                                         c->argc - idx0, &c->argv[ idx0 ] );
2207
2208                         } else {
2209                                 rc = rwm_rw_config( &db, c->fname, c->lineno,
2210                                         c->argc - idx0, &c->argv[ idx0 ] );
2211                         }
2212                         c->argv[ idx0 ] = argv0;
2213                         if ( rc != 0 ) {
2214                                 rewrite_info_delete( &rwmap->rwm_rw );
2215                                 assert( rwmap->rwm_rw == NULL );
2216
2217                                 rwmap->rwm_rw = rwm_rw;
2218                                 return 1;
2219                         }
2220
2221                         for ( i = c->valx; !BER_BVISNULL( &rwmap->rwm_bva_rewrite[ i ] ); i++ )
2222                         {
2223                                 ca.line = rwmap->rwm_bva_rewrite[ i ].bv_val;
2224                                 ca.argc = 0;
2225                                 config_fp_parse_line( &ca );
2226                                 
2227                                 argv0 = ca.argv[ 0 ];
2228                                 ca.argv[ 0 ] += STRLENOF( "rwm-" );
2229                                 
2230                                 if ( strcasecmp( ca.argv[ 0 ], "suffixmassage" ) == 0 ) {
2231                                         rc = rwm_suffixmassage_config( &db, c->fname, c->lineno,
2232                                                 ca.argc, ca.argv );
2233
2234                                 } else {
2235                                         rc = rwm_rw_config( &db, c->fname, c->lineno,
2236                                                 ca.argc, ca.argv );
2237                                 }
2238
2239                                 ca.argv[ 0 ] = argv0;
2240
2241                                 ch_free( ca.tline );
2242
2243                                 assert( rc == 0 );
2244                         }
2245
2246                         rwmap->rwm_bva_rewrite = ch_realloc( rwmap->rwm_bva_rewrite,
2247                                 ( last + 2 )*sizeof( struct berval ) );
2248
2249                         for ( i = last - 1; i >= c->valx; i-- )
2250                         {
2251                                 rwmap->rwm_bva_rewrite[ i + 1 ] = rwmap->rwm_bva_rewrite[ i ];
2252                         }
2253
2254                         rwm_bva_rewrite_add( rwmap, c->valx, &c->argv[ idx0 ] );
2255
2256                         rewrite_info_delete( &rwm_rw );
2257                         assert( rwm_rw == NULL );
2258
2259                         break;
2260                 }
2261
2262                 argv0 = c->argv[ idx0 ];
2263                 if ( strncasecmp( argv0, "rwm-", STRLENOF( "rwm-" ) ) != 0 ) {
2264                         return 1;
2265                 }
2266                 c->argv[ idx0 ] += STRLENOF( "rwm-" );
2267                 if ( strcasecmp( c->argv[ idx0 ], "suffixmassage" ) == 0 ) {
2268                         rc = rwm_suffixmassage_config( &db, c->fname, c->lineno,
2269                                 c->argc - idx0, &c->argv[ idx0 ] );
2270
2271                 } else {
2272                         rc = rwm_rw_config( &db, c->fname, c->lineno,
2273                                 c->argc - idx0, &c->argv[ idx0 ] );
2274                 }
2275                 c->argv[ idx0 ] = argv0;
2276                 if ( rc ) {
2277                         return 1;
2278
2279                 } else {
2280                         rwm_bva_rewrite_add( rwmap, -1, &c->argv[ idx0 ] );
2281                 }
2282                 break;
2283
2284         case RWM_CF_T_F_SUPPORT:
2285                 rc = verb_to_mask( c->argv[ 1 ], t_f_mode );
2286                 if ( BER_BVISNULL( &t_f_mode[ rc ].word ) ) {
2287                         return 1;
2288                 }
2289
2290                 rwmap->rwm_flags &= ~RWM_F_SUPPORT_T_F_MASK2;
2291                 rwmap->rwm_flags |= t_f_mode[ rc ].mask;
2292                 rc = 0;
2293                 break;
2294
2295         case RWM_CF_MAP:
2296                 if ( c->valx >= 0 ) {
2297                         return 1;
2298                 }
2299
2300                 argv0 = c->argv[ 0 ];
2301                 c->argv[ 0 ] += STRLENOF( "rwm-" );
2302                 rc = rwm_m_config( &db, c->fname, c->lineno, c->argc, c->argv );
2303                 c->argv[ 0 ] = argv0;
2304                 if ( rc ) {
2305                         return 1;
2306
2307                 } else {
2308                         char            *line;
2309                         struct berval   bv;
2310
2311                         line = ldap_charray2str( &c->argv[ 1 ], " " );
2312                         if ( line != NULL ) {
2313                                 ber_str2bv( line, 0, 0, &bv );
2314                                 ber_bvarray_add( &rwmap->rwm_bva_map, &bv );
2315                         }
2316                 }
2317                 break;
2318
2319         case RWM_CF_NORMALIZE_MAPPED:
2320                 if ( c->value_int ) {
2321                         rwmap->rwm_flags |= RWM_F_NORMALIZE_MAPPED_ATTRS;
2322                 } else {
2323                         rwmap->rwm_flags &= ~RWM_F_NORMALIZE_MAPPED_ATTRS;
2324                 }
2325                 break;
2326
2327         default:
2328                 assert( 0 );
2329                 return 1;
2330         }
2331
2332         return rc;
2333 }
2334
2335 static int
2336 rwm_db_init(
2337         BackendDB       *be,
2338         ConfigReply     *cr )
2339 {
2340         slap_overinst           *on = (slap_overinst *) be->bd_info;
2341         struct ldaprwmap        *rwmap;
2342         int                     rc = 0;
2343
2344         rwmap = (struct ldaprwmap *)ch_calloc( 1, sizeof( struct ldaprwmap ) );
2345
2346         rc = rwm_info_init( &rwmap->rwm_rw );
2347
2348 error_return:;
2349         on->on_bi.bi_private = (void *)rwmap;
2350
2351         if ( rc ) {
2352                 (void)rwm_db_destroy( be, NULL );
2353         }
2354
2355         return rc;
2356 }
2357
2358 static int
2359 rwm_db_destroy(
2360         BackendDB       *be,
2361         ConfigReply     *cr )
2362 {
2363         slap_overinst   *on = (slap_overinst *) be->bd_info;
2364         int             rc = 0;
2365
2366         if ( on->on_bi.bi_private ) {
2367                 struct ldaprwmap        *rwmap = 
2368                         (struct ldaprwmap *)on->on_bi.bi_private;
2369
2370                 if ( rwmap->rwm_rw ) {
2371                         rewrite_info_delete( &rwmap->rwm_rw );
2372                         ber_bvarray_free( rwmap->rwm_bva_rewrite );
2373                 }
2374
2375                 avl_free( rwmap->rwm_oc.remap, rwm_mapping_dst_free );
2376                 avl_free( rwmap->rwm_oc.map, rwm_mapping_free );
2377                 avl_free( rwmap->rwm_at.remap, rwm_mapping_dst_free );
2378                 avl_free( rwmap->rwm_at.map, rwm_mapping_free );
2379                 ber_bvarray_free( rwmap->rwm_bva_map );
2380
2381                 ch_free( rwmap );
2382         }
2383
2384         return rc;
2385 }
2386
2387 static slap_overinst rwm = { { NULL } };
2388
2389 #if SLAPD_OVER_RWM == SLAPD_MOD_DYNAMIC
2390 static
2391 #endif /* SLAPD_OVER_RWM == SLAPD_MOD_DYNAMIC */
2392 int
2393 rwm_initialize( void )
2394 {
2395         int             rc;
2396
2397         /* Make sure we don't exceed the bits reserved for userland */
2398         config_check_userland( RWM_CF_LAST );
2399
2400         memset( &rwm, 0, sizeof( slap_overinst ) );
2401
2402         rwm.on_bi.bi_type = "rwm";
2403         rwm.on_bi.bi_flags =
2404                 SLAPO_BFLAG_SINGLE |
2405                 0;
2406
2407         rwm.on_bi.bi_db_init = rwm_db_init;
2408         rwm.on_bi.bi_db_config = rwm_db_config;
2409         rwm.on_bi.bi_db_destroy = rwm_db_destroy;
2410
2411         rwm.on_bi.bi_op_bind = rwm_op_bind;
2412         rwm.on_bi.bi_op_search = rwm_op_search;
2413         rwm.on_bi.bi_op_compare = rwm_op_compare;
2414         rwm.on_bi.bi_op_modify = rwm_op_modify;
2415         rwm.on_bi.bi_op_modrdn = rwm_op_modrdn;
2416         rwm.on_bi.bi_op_add = rwm_op_add;
2417         rwm.on_bi.bi_op_delete = rwm_op_delete;
2418         rwm.on_bi.bi_op_unbind = rwm_op_unbind;
2419         rwm.on_bi.bi_extended = rwm_extended;
2420 #if 1 /* TODO */
2421         rwm.on_bi.bi_entry_release_rw = rwm_entry_release_rw;
2422         rwm.on_bi.bi_entry_get_rw = rwm_entry_get_rw;
2423 #endif
2424
2425         rwm.on_bi.bi_operational = rwm_operational;
2426         rwm.on_bi.bi_chk_referrals = 0 /* rwm_chk_referrals */ ;
2427
2428         rwm.on_bi.bi_connection_init = rwm_conn_init;
2429         rwm.on_bi.bi_connection_destroy = rwm_conn_destroy;
2430
2431         rwm.on_response = rwm_response;
2432
2433         rwm.on_bi.bi_cf_ocs = rwmocs;
2434
2435         rc = config_register_schema( rwmcfg, rwmocs );
2436         if ( rc ) {
2437                 return rc;
2438         }
2439
2440         return overlay_register( &rwm );
2441 }
2442
2443 #if SLAPD_OVER_RWM == SLAPD_MOD_DYNAMIC
2444 int
2445 init_module( int argc, char *argv[] )
2446 {
2447         return rwm_initialize();
2448 }
2449 #endif /* SLAPD_OVER_RWM == SLAPD_MOD_DYNAMIC */
2450
2451 #endif /* SLAPD_OVER_RWM */