]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
More tweaks for delta-mmr
[openldap] / servers / slapd / syncrepl.c
1 /* syncrepl.c -- Replication Engine which uses the LDAP Sync protocol */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2003-2011 The OpenLDAP Foundation.
6  * Portions Copyright 2003 by IBM Corporation.
7  * Portions Copyright 2003-2008 by Howard Chu, Symas Corporation.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in the file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18
19 #include "portable.h"
20
21 #include <stdio.h>
22
23 #include <ac/string.h>
24 #include <ac/socket.h>
25
26 #include "lutil.h"
27 #include "slap.h"
28 #include "lutil_ldap.h"
29
30 #include "config.h"
31
32 #include "ldap_rq.h"
33
34 #ifdef ENABLE_REWRITE
35 #include "rewrite.h"
36 #define SUFFIXM_CTX     "<suffix massage>"
37 #endif
38
39 struct nonpresent_entry {
40         struct berval *npe_name;
41         struct berval *npe_nname;
42         LDAP_LIST_ENTRY(nonpresent_entry) npe_link;
43 };
44
45 typedef struct cookie_state {
46         ldap_pvt_thread_mutex_t cs_mutex;
47         int     cs_num;
48         int cs_age;
49         int cs_ref;
50         struct berval *cs_vals;
51         int *cs_sids;
52         
53         /* pending changes, not yet committed */
54         ldap_pvt_thread_mutex_t cs_pmutex;
55         int     cs_pnum;
56         struct berval *cs_pvals;
57         int *cs_psids;
58 } cookie_state;
59
60 #define SYNCDATA_DEFAULT        0       /* entries are plain LDAP entries */
61 #define SYNCDATA_ACCESSLOG      1       /* entries are accesslog format */
62 #define SYNCDATA_CHANGELOG      2       /* entries are changelog format */
63
64 #define SYNCLOG_LOGGING         0       /* doing a log-based update */
65 #define SYNCLOG_FALLBACK        1       /* doing a full refresh */
66
67 #define RETRYNUM_FOREVER        (-1)    /* retry forever */
68 #define RETRYNUM_TAIL           (-2)    /* end of retrynum array */
69 #define RETRYNUM_VALID(n)       ((n) >= RETRYNUM_FOREVER)       /* valid retrynum */
70 #define RETRYNUM_FINITE(n)      ((n) > RETRYNUM_FOREVER)        /* not forever */
71
72 typedef struct syncinfo_s {
73         struct syncinfo_s       *si_next;
74         BackendDB               *si_be;
75         BackendDB               *si_wbe;
76         struct re_s             *si_re;
77         int                     si_rid;
78         char                    si_ridtxt[ STRLENOF("rid=999") + 1 ];
79         slap_bindconf           si_bindconf;
80         struct berval           si_base;
81         struct berval           si_logbase;
82         struct berval           si_filterstr;
83         Filter                  *si_filter;
84         struct berval           si_logfilterstr;
85         struct berval           si_contextdn;
86         int                     si_scope;
87         int                     si_attrsonly;
88         char                    *si_anfile;
89         AttributeName           *si_anlist;
90         AttributeName           *si_exanlist;
91         char                    **si_attrs;
92         char                    **si_exattrs;
93         int                     si_allattrs;
94         int                     si_allopattrs;
95         int                     si_schemachecking;
96         int                     si_type;        /* the active type */
97         int                     si_ctype;       /* the configured type */
98         time_t                  si_interval;
99         time_t                  *si_retryinterval;
100         int                     *si_retrynum_init;
101         int                     *si_retrynum;
102         struct sync_cookie      si_syncCookie;
103         cookie_state            *si_cookieState;
104         int                     si_cookieAge;
105         int                     si_manageDSAit;
106         int                     si_slimit;
107         int                     si_tlimit;
108         int                     si_refreshDelete;
109         int                     si_refreshPresent;
110         int                     si_refreshDone;
111         int                     si_syncdata;
112         int                     si_logstate;
113         int                     si_got;
114         int                     si_strict_refresh;      /* stop listening during fallback refresh */
115         ber_int_t       si_msgid;
116         Avlnode                 *si_presentlist;
117         LDAP                    *si_ld;
118         Connection              *si_conn;
119         LDAP_LIST_HEAD(np, nonpresent_entry)    si_nonpresentlist;
120 #ifdef ENABLE_REWRITE
121         struct rewrite_info *si_rewrite;
122         struct berval   si_suffixm;
123 #endif
124         ldap_pvt_thread_mutex_t si_mutex;
125 } syncinfo_t;
126
127 static int syncuuid_cmp( const void *, const void * );
128 static int avl_presentlist_insert( syncinfo_t* si, struct berval *syncUUID );
129 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray, struct sync_cookie *, int );
130 static int syncrepl_message_to_op(
131                                         syncinfo_t *, Operation *, LDAPMessage * );
132 static int syncrepl_message_to_entry(
133                                         syncinfo_t *, Operation *, LDAPMessage *,
134                                         Modifications **, Entry **, int );
135 static int syncrepl_entry(
136                                         syncinfo_t *, Operation*, Entry*,
137                                         Modifications**,int, struct berval*,
138                                         struct berval *cookieCSN );
139 static int syncrepl_updateCookie(
140                                         syncinfo_t *, Operation *,
141                                         struct sync_cookie * );
142 static struct berval * slap_uuidstr_from_normalized(
143                                         struct berval *, struct berval *, void * );
144 static int syncrepl_add_glue_ancestors(
145         Operation* op, Entry *e );
146
147 /* delta-mmr overlay handler */
148 static int syncrepl_op_modify( Operation *op, SlapReply *rs );
149
150 /* callback functions */
151 static int dn_callback( Operation *, SlapReply * );
152 static int nonpresent_callback( Operation *, SlapReply * );
153 static int null_callback( Operation *, SlapReply * );
154
155 static AttributeDescription *sync_descs[4];
156
157 /* delta-mmr */
158 static AttributeDescription *ad_reqMod, *ad_reqDN;
159
160 typedef struct logschema {
161         struct berval ls_dn;
162         struct berval ls_req;
163         struct berval ls_mod;
164         struct berval ls_newRdn;
165         struct berval ls_delRdn;
166         struct berval ls_newSup;
167 } logschema;
168
169 static logschema changelog_sc = {
170         BER_BVC("targetDN"),
171         BER_BVC("changeType"),
172         BER_BVC("changes"),
173         BER_BVC("newRDN"),
174         BER_BVC("deleteOldRDN"),
175         BER_BVC("newSuperior")
176 };
177
178 static logschema accesslog_sc = {
179         BER_BVC("reqDN"),
180         BER_BVC("reqType"),
181         BER_BVC("reqMod"),
182         BER_BVC("reqNewRDN"),
183         BER_BVC("reqDeleteOldRDN"),
184         BER_BVC("reqNewSuperior")
185 };
186
187 static const char *
188 syncrepl_state2str( int state )
189 {
190         switch ( state ) {
191         case LDAP_SYNC_PRESENT:
192                 return "PRESENT";
193
194         case LDAP_SYNC_ADD:
195                 return "ADD";
196
197         case LDAP_SYNC_MODIFY:
198                 return "MODIFY";
199
200         case LDAP_SYNC_DELETE:
201                 return "DELETE";
202         }
203
204         return "UNKNOWN";
205 }
206
207 static slap_overinst syncrepl_ov;
208
209 static void
210 init_syncrepl(syncinfo_t *si)
211 {
212         int i, j, k, l, n;
213         char **attrs, **exattrs;
214
215         if ( !syncrepl_ov.on_bi.bi_type ) {
216                 syncrepl_ov.on_bi.bi_type = "syncrepl";
217                 syncrepl_ov.on_bi.bi_op_modify = syncrepl_op_modify;
218                 overlay_register( &syncrepl_ov );
219         }
220
221         /* delta-MMR needs the overlay, nothing else does.
222          * This must happen before accesslog overlay is configured.
223          */
224         if ( si->si_syncdata &&
225                 !overlay_is_inst( si->si_be, syncrepl_ov.on_bi.bi_type )) {
226                 overlay_config( si->si_be, syncrepl_ov.on_bi.bi_type, -1, NULL, NULL );
227                 if ( !ad_reqMod ) {
228                         const char *text;
229                         logschema *ls = &accesslog_sc;
230
231                         slap_bv2ad( &ls->ls_mod, &ad_reqMod, &text );
232                         slap_bv2ad( &ls->ls_dn, &ad_reqDN, &text );
233                 }
234         }
235
236         if ( !sync_descs[0] ) {
237                 sync_descs[0] = slap_schema.si_ad_objectClass;
238                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
239                 sync_descs[2] = slap_schema.si_ad_entryCSN;
240                 sync_descs[3] = NULL;
241         }
242
243         if ( si->si_allattrs && si->si_allopattrs )
244                 attrs = NULL;
245         else
246                 attrs = anlist2attrs( si->si_anlist );
247
248         if ( attrs ) {
249                 if ( si->si_allattrs ) {
250                         i = 0;
251                         while ( attrs[i] ) {
252                                 if ( !is_at_operational( at_find( attrs[i] ) ) ) {
253                                         for ( j = i; attrs[j] != NULL; j++ ) {
254                                                 if ( j == i )
255                                                         ch_free( attrs[i] );
256                                                 attrs[j] = attrs[j+1];
257                                         }
258                                 } else {
259                                         i++;
260                                 }
261                         }
262                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
263                         attrs[i] = ch_strdup("*");
264                         attrs[i + 1] = NULL;
265
266                 } else if ( si->si_allopattrs ) {
267                         i = 0;
268                         while ( attrs[i] ) {
269                                 if ( is_at_operational( at_find( attrs[i] ) ) ) {
270                                         for ( j = i; attrs[j] != NULL; j++ ) {
271                                                 if ( j == i )
272                                                         ch_free( attrs[i] );
273                                                 attrs[j] = attrs[j+1];
274                                         }
275                                 } else {
276                                         i++;
277                                 }
278                         }
279                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
280                         attrs[i] = ch_strdup("+");
281                         attrs[i + 1] = NULL;
282                 }
283
284                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
285                         j = 0;
286                         while ( attrs[j] ) {
287                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
288                                         for ( k = j; attrs[k] != NULL; k++ ) {
289                                                 if ( k == j )
290                                                         ch_free( attrs[k] );
291                                                 attrs[k] = attrs[k+1];
292                                         }
293                                 } else {
294                                         j++;
295                                 }
296                         }
297                 }
298
299                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
300
301                 if ( si->si_allopattrs ) {
302                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ) );
303                 } else {
304                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ) );
305                 }
306
307                 /* Add Attributes */
308                 if ( si->si_allopattrs ) {
309                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
310                 } else {
311                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
312                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
313                         }
314                 }
315                 attrs[ n ] = NULL;
316
317         } else {
318
319                 i = 0;
320                 if ( si->si_allattrs == si->si_allopattrs ) {
321                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
322                         attrs[i++] = ch_strdup( "*" );
323                         attrs[i++] = ch_strdup( "+" );
324                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
325                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
326                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
327                         attrs[i++] = ch_strdup( "*" );
328                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
329                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
330                         }
331                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
332                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
333                         attrs[i++] = ch_strdup( "+" );
334                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
335                 }
336                 attrs[i] = NULL;
337         }
338         
339         si->si_attrs = attrs;
340
341         exattrs = anlist2attrs( si->si_exanlist );
342
343         if ( exattrs ) {
344                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
345
346                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
347                         j = 0;
348                         while ( exattrs[j] != NULL ) {
349                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
350                                         ch_free( exattrs[j] );
351                                         for ( k = j; exattrs[k] != NULL; k++ ) {
352                                                 exattrs[k] = exattrs[k+1];
353                                         }
354                                 } else {
355                                         j++;
356                                 }
357                         }
358                 }
359
360                 for ( i = 0; exattrs[i] != NULL; i++ ) {
361                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
362                                 ObjectClass     *oc;
363                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
364                                         k = 0;
365                                         while ( oc->soc_required[k] ) {
366                                                 if ( !strcmp( exattrs[i],
367                                                          oc->soc_required[k]->sat_cname.bv_val ) ) {
368                                                         ch_free( exattrs[i] );
369                                                         for ( l = i; exattrs[l]; l++ ) {
370                                                                 exattrs[l] = exattrs[l+1];
371                                                         }
372                                                 } else {
373                                                         k++;
374                                                 }
375                                         }
376                                 }
377                         }
378                 }
379
380                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
381
382                 if ( i != n )
383                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *) );
384         }
385
386         si->si_exattrs = exattrs;       
387 }
388
389 static int
390 ldap_sync_search(
391         syncinfo_t *si,
392         void *ctx )
393 {
394         BerElementBuffer berbuf;
395         BerElement *ber = (BerElement *)&berbuf;
396         LDAPControl c[3], *ctrls[4];
397         int rc;
398         int rhint;
399         char *base;
400         char **attrs, *lattrs[8];
401         char *filter;
402         int attrsonly;
403         int scope;
404
405         /* setup LDAP SYNC control */
406         ber_init2( ber, NULL, LBER_USE_DER );
407         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
408
409         /* If we're using a log but we have no state, then fallback to
410          * normal mode for a full refresh.
411          */
412         if ( si->si_syncdata && !si->si_syncCookie.numcsns ) {
413                 si->si_logstate = SYNCLOG_FALLBACK;
414         }
415
416         /* Use the log parameters if we're in log mode */
417         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
418                 logschema *ls;
419                 if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
420                         ls = &accesslog_sc;
421                 else
422                         ls = &changelog_sc;
423                 lattrs[0] = ls->ls_dn.bv_val;
424                 lattrs[1] = ls->ls_req.bv_val;
425                 lattrs[2] = ls->ls_mod.bv_val;
426                 lattrs[3] = ls->ls_newRdn.bv_val;
427                 lattrs[4] = ls->ls_delRdn.bv_val;
428                 lattrs[5] = ls->ls_newSup.bv_val;
429                 lattrs[6] = slap_schema.si_ad_entryCSN->ad_cname.bv_val;
430                 lattrs[7] = NULL;
431
432                 rhint = 0;
433                 base = si->si_logbase.bv_val;
434                 filter = si->si_logfilterstr.bv_val;
435                 attrs = lattrs;
436                 attrsonly = 0;
437                 scope = LDAP_SCOPE_SUBTREE;
438         } else {
439                 rhint = 1;
440                 base = si->si_base.bv_val;
441                 filter = si->si_filterstr.bv_val;
442                 attrs = si->si_attrs;
443                 attrsonly = si->si_attrsonly;
444                 scope = si->si_scope;
445         }
446         if ( si->si_syncdata && si->si_logstate == SYNCLOG_FALLBACK ) {
447                 si->si_type = LDAP_SYNC_REFRESH_ONLY;
448         } else {
449                 si->si_type = si->si_ctype;
450         }
451
452         if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
453         {
454                 ber_printf( ber, "{eOb}",
455                         abs(si->si_type), &si->si_syncCookie.octet_str, rhint );
456         } else {
457                 ber_printf( ber, "{eb}",
458                         abs(si->si_type), rhint );
459         }
460
461         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 ) ) == -1 ) {
462                 ber_free_buf( ber );
463                 return rc;
464         }
465
466         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
467         c[0].ldctl_iscritical = si->si_type < 0;
468         ctrls[0] = &c[0];
469
470         c[1].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
471         BER_BVZERO( &c[1].ldctl_value );
472         c[1].ldctl_iscritical = 1;
473         ctrls[1] = &c[1];
474
475         if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
476                 c[2].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
477                 c[2].ldctl_value = si->si_bindconf.sb_authzId;
478                 c[2].ldctl_iscritical = 1;
479                 ctrls[2] = &c[2];
480                 ctrls[3] = NULL;
481         } else {
482                 ctrls[2] = NULL;
483         }
484
485         rc = ldap_search_ext( si->si_ld, base, scope, filter, attrs, attrsonly,
486                 ctrls, NULL, NULL, si->si_slimit, &si->si_msgid );
487         ber_free_buf( ber );
488         return rc;
489 }
490
491 static int
492 check_syncprov(
493         Operation *op,
494         syncinfo_t *si )
495 {
496         AttributeName at[2];
497         Attribute a = {0};
498         Entry e = {0};
499         SlapReply rs = {REP_SEARCH};
500         int i, j, changed = 0;
501
502         /* Look for contextCSN from syncprov overlay. If
503          * there's no overlay, this will be a no-op. That means
504          * this is a pure consumer, so local changes will not be
505          * allowed, and all changes will already be reflected in
506          * the cookieState.
507          */
508         a.a_desc = slap_schema.si_ad_contextCSN;
509         e.e_attrs = &a;
510         e.e_name = si->si_contextdn;
511         e.e_nname = si->si_contextdn;
512         at[0].an_name = a.a_desc->ad_cname;
513         at[0].an_desc = a.a_desc;
514         BER_BVZERO( &at[1].an_name );
515         rs.sr_entry = &e;
516         rs.sr_flags = REP_ENTRY_MODIFIABLE;
517         rs.sr_attrs = at;
518         op->o_req_dn = e.e_name;
519         op->o_req_ndn = e.e_nname;
520
521         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
522         i = backend_operational( op, &rs );
523         if ( i == LDAP_SUCCESS && a.a_nvals ) {
524                 int num = a.a_numvals;
525                 /* check for differences */
526                 if ( num != si->si_cookieState->cs_num ) {
527                         changed = 1;
528                 } else {
529                         for ( i=0; i<num; i++ ) {
530                                 if ( ber_bvcmp( &a.a_nvals[i],
531                                         &si->si_cookieState->cs_vals[i] )) {
532                                         changed = 1;
533                                         break;
534                                 }
535                         }
536                 }
537                 if ( changed ) {
538                         ber_bvarray_free( si->si_cookieState->cs_vals );
539                         ch_free( si->si_cookieState->cs_sids );
540                         si->si_cookieState->cs_num = num;
541                         si->si_cookieState->cs_vals = a.a_nvals;
542                         si->si_cookieState->cs_sids = slap_parse_csn_sids( a.a_nvals,
543                                 num, NULL );
544                         si->si_cookieState->cs_age++;
545                 } else {
546                         ber_bvarray_free( a.a_nvals );
547                 }
548                 ber_bvarray_free( a.a_vals );
549         }
550         /* See if the cookieState has changed due to anything outside
551          * this particular consumer. That includes other consumers in
552          * the same context, or local changes detected above.
553          */
554         if ( si->si_cookieState->cs_num > 0 && si->si_cookieAge !=
555                 si->si_cookieState->cs_age ) {
556                 if ( !si->si_syncCookie.numcsns ) {
557                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
558                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
559                                 si->si_cookieState->cs_vals, NULL );
560                         changed = 1;
561                 } else {
562                         for (i=0; !BER_BVISNULL( &si->si_syncCookie.ctxcsn[i] ); i++) {
563                                 /* bogus, just dup everything */
564                                 if ( si->si_syncCookie.sids[i] == -1 ) {
565                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
566                                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
567                                                 si->si_cookieState->cs_vals, NULL );
568                                         changed = 1;
569                                         break;
570                                 }
571                                 for (j=0; j<si->si_cookieState->cs_num; j++) {
572                                         if ( si->si_syncCookie.sids[i] !=
573                                                 si->si_cookieState->cs_sids[j] )
574                                                 continue;
575                                         if ( bvmatch( &si->si_syncCookie.ctxcsn[i],
576                                                 &si->si_cookieState->cs_vals[j] ))
577                                                 break;
578                                         ber_bvreplace( &si->si_syncCookie.ctxcsn[i],
579                                                 &si->si_cookieState->cs_vals[j] );
580                                         changed = 1;
581                                         break;
582                                 }
583                         }
584                 }
585         }
586         if ( changed ) {
587                 si->si_cookieAge = si->si_cookieState->cs_age;
588                 ch_free( si->si_syncCookie.octet_str.bv_val );
589                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
590                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
591                         si->si_syncCookie.sid );
592         }
593         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
594         return changed;
595 }
596
597 static int
598 do_syncrep1(
599         Operation *op,
600         syncinfo_t *si )
601 {
602         int     rc;
603         int cmdline_cookie_found = 0;
604
605         struct sync_cookie      *sc = NULL;
606 #ifdef HAVE_TLS
607         void    *ssl;
608 #endif
609
610         rc = slap_client_connect( &si->si_ld, &si->si_bindconf );
611         if ( rc != LDAP_SUCCESS ) {
612                 goto done;
613         }
614         op->o_protocol = LDAP_VERSION3;
615
616         /* Set SSF to strongest of TLS, SASL SSFs */
617         op->o_sasl_ssf = 0;
618         op->o_tls_ssf = 0;
619         op->o_transport_ssf = 0;
620 #ifdef HAVE_TLS
621         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
622                 == LDAP_SUCCESS && ssl != NULL )
623         {
624                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
625         }
626 #endif /* HAVE_TLS */
627         {
628                 ber_len_t ssf; /* ITS#5403, 3864 LDAP_OPT_X_SASL_SSF probably ought
629                                                   to use sasl_ssf_t but currently uses ber_len_t */
630                 if ( ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &ssf )
631                         == LDAP_SUCCESS )
632                         op->o_sasl_ssf = ssf;
633         }
634         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
635                 ?  op->o_sasl_ssf : op->o_tls_ssf;
636
637         ldap_set_option( si->si_ld, LDAP_OPT_TIMELIMIT, &si->si_tlimit );
638
639         rc = LDAP_DEREF_NEVER;  /* actually could allow DEREF_FINDING */
640         ldap_set_option( si->si_ld, LDAP_OPT_DEREF, &rc );
641
642         ldap_set_option( si->si_ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF );
643
644         si->si_syncCookie.rid = si->si_rid;
645
646         /* whenever there are multiple data sources possible, advertise sid */
647         si->si_syncCookie.sid = ( SLAP_MULTIMASTER( si->si_be ) || si->si_be != si->si_wbe ) ?
648                 slap_serverID : -1;
649
650         /* We've just started up, or the remote server hasn't sent us
651          * any meaningful state.
652          */
653         if ( !si->si_syncCookie.ctxcsn ) {
654                 int i;
655
656                 LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
657                         if ( si->si_rid == sc->rid ) {
658                                 cmdline_cookie_found = 1;
659                                 break;
660                         }
661                 }
662
663                 if ( cmdline_cookie_found ) {
664                         /* cookie is supplied in the command line */
665
666                         LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
667
668                         /* ctxcsn wasn't parsed yet, do it now */
669                         slap_parse_sync_cookie( sc, op->o_tmpmemctx );
670                         slap_sync_cookie_free( &si->si_syncCookie, 0 );
671                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
672                         slap_sync_cookie_free( sc, 1 );
673                 } else {
674                         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
675                         if ( !si->si_cookieState->cs_num ) {
676                                 /* get contextCSN shadow replica from database */
677                                 BerVarray csn = NULL;
678                                 void *ctx = op->o_tmpmemctx;
679
680                                 op->o_req_ndn = si->si_contextdn;
681                                 op->o_req_dn = op->o_req_ndn;
682
683                                 /* try to read stored contextCSN */
684                                 op->o_tmpmemctx = NULL;
685                                 backend_attribute( op, NULL, &op->o_req_ndn,
686                                         slap_schema.si_ad_contextCSN, &csn, ACL_READ );
687                                 op->o_tmpmemctx = ctx;
688                                 if ( csn ) {
689                                         si->si_cookieState->cs_vals = csn;
690                                         for (i=0; !BER_BVISNULL( &csn[i] ); i++);
691                                         si->si_cookieState->cs_num = i;
692                                         si->si_cookieState->cs_sids = slap_parse_csn_sids( csn, i, NULL );
693                                 }
694                         }
695                         if ( si->si_cookieState->cs_num ) {
696                                 ber_bvarray_free( si->si_syncCookie.ctxcsn );
697                                 if ( ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
698                                         si->si_cookieState->cs_vals, NULL )) {
699                                         rc = LDAP_NO_MEMORY;
700                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
701                                         goto done;
702                                 }
703                                 si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
704                                 si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num *
705                                         sizeof(int) );
706                                 for ( i=0; i<si->si_syncCookie.numcsns; i++ )
707                                         si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
708                         }
709                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
710                 }
711
712                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
713                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
714                         si->si_syncCookie.sid );
715         } else {
716                 /* ITS#6367: recreate the cookie so it has our SID, not our peer's */
717                 ch_free( si->si_syncCookie.octet_str.bv_val );
718                 BER_BVZERO( &si->si_syncCookie.octet_str );
719                 /* Look for contextCSN from syncprov overlay. */
720                 check_syncprov( op, si );
721                 if ( BER_BVISNULL( &si->si_syncCookie.octet_str ))
722                         slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
723                                 si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
724                                 si->si_syncCookie.sid );
725         }
726
727         si->si_refreshDone = 0;
728
729         rc = ldap_sync_search( si, op->o_tmpmemctx );
730
731         if( rc != LDAP_SUCCESS ) {
732                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s "
733                         "ldap_search_ext: %s (%d)\n",
734                         si->si_ridtxt, ldap_err2string( rc ), rc );
735         }
736
737 done:
738         if ( rc ) {
739                 if ( si->si_ld ) {
740                         ldap_unbind_ext( si->si_ld, NULL, NULL );
741                         si->si_ld = NULL;
742                 }
743         }
744
745         return rc;
746 }
747
748 static int
749 compare_csns( struct sync_cookie *sc1, struct sync_cookie *sc2, int *which )
750 {
751         int i, j, match = 0;
752         const char *text;
753
754         *which = 0;
755
756         if ( sc1->numcsns < sc2->numcsns ) {
757                 *which = sc1->numcsns;
758                 return -1;
759         }
760
761         for (j=0; j<sc2->numcsns; j++) {
762                 for (i=0; i<sc1->numcsns; i++) {
763                         if ( sc1->sids[i] != sc2->sids[j] )
764                                 continue;
765                         value_match( &match, slap_schema.si_ad_entryCSN,
766                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
767                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
768                                 &sc1->ctxcsn[i], &sc2->ctxcsn[j], &text );
769                         if ( match < 0 ) {
770                                 *which = j;
771                                 return match;
772                         }
773                         break;
774                 }
775                 if ( i == sc1->numcsns ) {
776                         /* sc2 has a sid sc1 lacks */
777                         *which = j;
778                         return -1;
779                 }
780         }
781         return match;
782 }
783
784 #define SYNC_PAUSED     -3
785
786 static int
787 do_syncrep2(
788         Operation *op,
789         syncinfo_t *si )
790 {
791         BerElementBuffer berbuf;
792         BerElement      *ber = (BerElement *)&berbuf;
793
794         LDAPMessage     *msg = NULL;
795
796         struct sync_cookie      syncCookie = { NULL };
797         struct sync_cookie      syncCookie_req = { NULL };
798
799         int             rc,
800                         err = LDAP_SUCCESS;
801
802         Modifications   *modlist = NULL;
803
804         int                             m;
805
806         struct timeval *tout_p = NULL;
807         struct timeval tout = { 0, 0 };
808
809         int             refreshDeletes = 0;
810         char empty[6] = "empty";
811
812         if ( slapd_shutdown ) {
813                 rc = -2;
814                 goto done;
815         }
816
817         ber_init2( ber, NULL, LBER_USE_DER );
818         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
819
820         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2 %s\n", si->si_ridtxt, 0, 0 );
821
822         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
823
824         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
825                 tout_p = &tout;
826         } else {
827                 tout_p = NULL;
828         }
829
830         while ( ( rc = ldap_result( si->si_ld, si->si_msgid, LDAP_MSG_ONE,
831                 tout_p, &msg ) ) > 0 )
832         {
833                 int                             match, punlock, syncstate;
834                 struct berval   *retdata, syncUUID, cookie = BER_BVNULL;
835                 char                    *retoid;
836                 LDAPControl             **rctrls = NULL, *rctrlp = NULL;
837                 BerVarray               syncUUIDs;
838                 ber_len_t               len;
839                 ber_tag_t               si_tag;
840                 Entry                   *entry;
841                 struct berval   bdn;
842
843                 if ( slapd_shutdown ) {
844                         rc = -2;
845                         goto done;
846                 }
847                 switch( ldap_msgtype( msg ) ) {
848                 case LDAP_RES_SEARCH_ENTRY:
849                         ldap_get_entry_controls( si->si_ld, msg, &rctrls );
850                         ldap_get_dn_ber( si->si_ld, msg, NULL, &bdn );
851                         if (!bdn.bv_len) {
852                                 bdn.bv_val = empty;
853                                 bdn.bv_len = sizeof(empty)-1;
854                         }
855                         /* we can't work without the control */
856                         if ( rctrls ) {
857                                 LDAPControl **next = NULL;
858                                 /* NOTE: make sure we use the right one;
859                                  * a better approach would be to run thru
860                                  * the whole list and take care of all */
861                                 /* NOTE: since we issue the search request,
862                                  * we should know what controls to expect,
863                                  * and there should be none apart from the
864                                  * sync-related control */
865                                 rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_STATE, rctrls, &next );
866                                 if ( next && ldap_control_find( LDAP_CONTROL_SYNC_STATE, next, NULL ) )
867                                 {
868                                         bdn.bv_val[bdn.bv_len] = '\0';
869                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
870                                                 "got search entry with multiple "
871                                                 "Sync State control (%s)\n", si->si_ridtxt, bdn.bv_val, 0 );
872                                         ldap_controls_free( rctrls );
873                                         rc = -1;
874                                         goto done;
875                                 }
876                         }
877                         if ( rctrlp == NULL ) {
878                                 bdn.bv_val[bdn.bv_len] = '\0';
879                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
880                                         "got search entry without "
881                                         "Sync State control (%s)\n", si->si_ridtxt, bdn.bv_val, 0 );
882                                 rc = -1;
883                                 goto done;
884                         }
885                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
886                         if ( ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID )
887                                         == LBER_ERROR ) {
888                                 bdn.bv_val[bdn.bv_len] = '\0';
889                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s malformed message (%s)\n",
890                                         si->si_ridtxt, bdn.bv_val, 0 );
891                                 ldap_controls_free( rctrls );
892                                 rc = -1;
893                                 goto done;
894                         }
895                         /* FIXME: what if syncUUID is NULL or empty?
896                          * (happens with back-sql...) */
897                         if ( BER_BVISEMPTY( &syncUUID ) ) {
898                                 bdn.bv_val[bdn.bv_len] = '\0';
899                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
900                                         "got empty syncUUID with LDAP_SYNC_%s (%s)\n",
901                                         si->si_ridtxt,
902                                         syncrepl_state2str( syncstate ), bdn.bv_val );
903                                 ldap_controls_free( rctrls );
904                                 rc = -1;
905                                 goto done;
906                         }
907                         punlock = -1;
908                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
909                                 ber_scanf( ber, /*"{"*/ "m}", &cookie );
910
911                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
912                                         si->si_ridtxt,
913                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
914
915                                 if ( !BER_BVISNULL( &cookie ) ) {
916                                         ch_free( syncCookie.octet_str.bv_val );
917                                         ber_dupbv( &syncCookie.octet_str, &cookie );
918                                 }
919                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
920                                 {
921                                         slap_parse_sync_cookie( &syncCookie, NULL );
922                                         if ( syncCookie.ctxcsn ) {
923                                                 int i, sid = slap_parse_csn_sid( syncCookie.ctxcsn );
924                                                 check_syncprov( op, si );
925                                                 for ( i =0; i<si->si_cookieState->cs_num; i++ ) {
926                                                         if ( si->si_cookieState->cs_sids[i] == sid ) {
927                                                                 if ( ber_bvcmp( syncCookie.ctxcsn, &si->si_cookieState->cs_vals[i] ) <= 0 ) {
928                                                                         bdn.bv_val[bdn.bv_len] = '\0';
929                                                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN too old, ignoring %s (%s)\n",
930                                                                                 si->si_ridtxt, syncCookie.ctxcsn->bv_val, bdn.bv_val );
931                                                                         ldap_controls_free( rctrls );
932                                                                         rc = 0;
933                                                                         goto done;
934                                                                 }
935                                                                 break;
936                                                         }
937                                                 }
938                                                 /* check pending CSNs too */
939                                                 while ( ldap_pvt_thread_mutex_trylock( &si->si_cookieState->cs_pmutex )) {
940                                                         if ( slapd_shutdown ) {
941                                                                 rc = -2;
942                                                                 goto done;
943                                                         }
944                                                         if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
945                                                                 ldap_pvt_thread_yield();
946                                                 }
947                                                 for ( i =0; i<si->si_cookieState->cs_pnum; i++ ) {
948                                                         if ( si->si_cookieState->cs_psids[i] == sid ) {
949                                                                 if ( ber_bvcmp( syncCookie.ctxcsn, &si->si_cookieState->cs_pvals[i] ) <= 0 ) {
950                                                                         bdn.bv_val[bdn.bv_len] = '\0';
951                                                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN pending, ignoring %s (%s)\n",
952                                                                                 si->si_ridtxt, syncCookie.ctxcsn->bv_val, bdn.bv_val );
953                                                                         ldap_controls_free( rctrls );
954                                                                         rc = 0;
955                                                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_pmutex );
956                                                                         goto done;
957                                                                 }
958                                                                 ber_bvreplace( &si->si_cookieState->cs_pvals[i],
959                                                                         syncCookie.ctxcsn );
960                                                                 break;
961                                                         }
962                                                 }
963                                                 /* new SID, add it */
964                                                 if ( i == si->si_cookieState->cs_pnum ) {
965                                                         value_add( &si->si_cookieState->cs_pvals, syncCookie.ctxcsn );
966                                                         si->si_cookieState->cs_pnum++;
967                                                         si->si_cookieState->cs_psids = ch_realloc( si->si_cookieState->cs_psids, si->si_cookieState->cs_pnum * sizeof(int));
968                                                         si->si_cookieState->cs_psids[i] = sid;
969                                                 }
970                                                 assert( punlock < 0 );
971                                                 punlock = i;
972                                         }
973                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
974                                 }
975                         }
976                         rc = 0;
977                         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
978                                 modlist = NULL;
979                                 if ( ( rc = syncrepl_message_to_op( si, op, msg ) ) == LDAP_SUCCESS &&
980                                         syncCookie.ctxcsn )
981                                 {
982                                         rc = syncrepl_updateCookie( si, op, &syncCookie );
983                                 } else switch ( rc ) {
984                                         case LDAP_ALREADY_EXISTS:
985                                         case LDAP_NO_SUCH_OBJECT:
986                                         case LDAP_NO_SUCH_ATTRIBUTE:
987                                         case LDAP_TYPE_OR_VALUE_EXISTS:
988                                                 rc = LDAP_SYNC_REFRESH_REQUIRED;
989                                                 si->si_logstate = SYNCLOG_FALLBACK;
990                                                 ldap_abandon_ext( si->si_ld, si->si_msgid, NULL, NULL );
991                                                 bdn.bv_val[bdn.bv_len] = '\0';
992                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s delta-sync lost sync on (%s), switching to REFRESH\n",
993                                                         si->si_ridtxt, bdn.bv_val, 0 );
994                                                 if (si->si_strict_refresh) {
995                                                         slap_suspend_listeners();
996                                                         connections_drop();
997                                                 }
998                                                 break;
999                                         default:
1000                                                 break;
1001                                 }
1002                         } else if ( ( rc = syncrepl_message_to_entry( si, op, msg,
1003                                 &modlist, &entry, syncstate ) ) == LDAP_SUCCESS )
1004                         {
1005                                 if ( ( rc = syncrepl_entry( si, op, entry, &modlist,
1006                                         syncstate, &syncUUID, syncCookie.ctxcsn ) ) == LDAP_SUCCESS &&
1007                                         syncCookie.ctxcsn )
1008                                 {
1009                                         rc = syncrepl_updateCookie( si, op, &syncCookie );
1010                                 }
1011                         }
1012                         if ( punlock >= 0 ) {
1013                                 /* on failure, revert pending CSN */
1014                                 if ( rc != LDAP_SUCCESS ) {
1015                                         int i;
1016                                         for ( i = 0; i<si->si_cookieState->cs_num; i++ ) {
1017                                                 if ( si->si_cookieState->cs_sids[i] == si->si_cookieState->cs_psids[punlock] ) {
1018                                                         ber_bvreplace( &si->si_cookieState->cs_pvals[punlock],
1019                                                                 &si->si_cookieState->cs_vals[i] );
1020                                                         break;
1021                                                 }
1022                                         }
1023                                         if ( i == si->si_cookieState->cs_num )
1024                                                 si->si_cookieState->cs_pvals[punlock].bv_val[0] = '\0';
1025                                 }
1026                                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_pmutex );
1027                         }
1028                         ldap_controls_free( rctrls );
1029                         if ( modlist ) {
1030                                 slap_mods_free( modlist, 1 );
1031                         }
1032                         if ( rc )
1033                                 goto done;
1034                         break;
1035
1036                 case LDAP_RES_SEARCH_REFERENCE:
1037                         Debug( LDAP_DEBUG_ANY,
1038                                 "do_syncrep2: %s reference received error\n",
1039                                 si->si_ridtxt, 0, 0 );
1040                         break;
1041
1042                 case LDAP_RES_SEARCH_RESULT:
1043                         Debug( LDAP_DEBUG_SYNC,
1044                                 "do_syncrep2: %s LDAP_RES_SEARCH_RESULT\n",
1045                                 si->si_ridtxt, 0, 0 );
1046                         err = LDAP_OTHER; /* FIXME check parse result properly */
1047                         ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
1048                                 &rctrls, 0 );
1049 #ifdef LDAP_X_SYNC_REFRESH_REQUIRED
1050                         if ( err == LDAP_X_SYNC_REFRESH_REQUIRED ) {
1051                                 /* map old result code to registered code */
1052                                 err = LDAP_SYNC_REFRESH_REQUIRED;
1053                         }
1054 #endif
1055                         if ( err == LDAP_SYNC_REFRESH_REQUIRED ) {
1056                                 if ( si->si_logstate == SYNCLOG_LOGGING ) {
1057                                         si->si_logstate = SYNCLOG_FALLBACK;
1058                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s delta-sync lost sync, switching to REFRESH\n",
1059                                                 si->si_ridtxt, 0, 0 );
1060                                         if (si->si_strict_refresh) {
1061                                                 slap_suspend_listeners();
1062                                                 connections_drop();
1063                                         }
1064                                 }
1065                                 rc = err;
1066                                 goto done;
1067                         }
1068                         if ( err ) {
1069                                 Debug( LDAP_DEBUG_ANY,
1070                                         "do_syncrep2: %s LDAP_RES_SEARCH_RESULT (%d) %s\n",
1071                                         si->si_ridtxt, err, ldap_err2string( err ) );
1072                         }
1073                         if ( rctrls ) {
1074                                 LDAPControl **next = NULL;
1075                                 /* NOTE: make sure we use the right one;
1076                                  * a better approach would be to run thru
1077                                  * the whole list and take care of all */
1078                                 /* NOTE: since we issue the search request,
1079                                  * we should know what controls to expect,
1080                                  * and there should be none apart from the
1081                                  * sync-related control */
1082                                 rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_DONE, rctrls, &next );
1083                                 if ( next && ldap_control_find( LDAP_CONTROL_SYNC_DONE, next, NULL ) )
1084                                 {
1085                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1086                                                 "got search result with multiple "
1087                                                 "Sync State control\n", si->si_ridtxt, 0, 0 );
1088                                         ldap_controls_free( rctrls );
1089                                         rc = -1;
1090                                         goto done;
1091                                 }
1092                         }
1093                         if ( rctrlp ) {
1094                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
1095
1096                                 ber_scanf( ber, "{" /*"}"*/);
1097                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
1098                                         ber_scanf( ber, "m", &cookie );
1099
1100                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1101                                                 si->si_ridtxt, 
1102                                                 BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1103
1104                                         if ( !BER_BVISNULL( &cookie ) ) {
1105                                                 ch_free( syncCookie.octet_str.bv_val );
1106                                                 ber_dupbv( &syncCookie.octet_str, &cookie);
1107                                         }
1108                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1109                                         {
1110                                                 slap_parse_sync_cookie( &syncCookie, NULL );
1111                                                 op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1112                                         }
1113                                 }
1114                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
1115                                 {
1116                                         ber_scanf( ber, "b", &refreshDeletes );
1117                                 }
1118                                 ber_scanf( ber, /*"{"*/ "}" );
1119                         }
1120                         if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
1121                                 slap_sync_cookie_free( &syncCookie_req, 0 );
1122                                 slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
1123                         }
1124                         if ( !syncCookie.ctxcsn ) {
1125                                 match = 1;
1126                         } else if ( !syncCookie_req.ctxcsn ) {
1127                                 match = -1;
1128                                 m = 0;
1129                         } else {
1130                                 match = compare_csns( &syncCookie_req, &syncCookie, &m );
1131                         }
1132                         if ( rctrls ) {
1133                                 ldap_controls_free( rctrls );
1134                         }
1135                         if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
1136                                 /* FIXME : different error behaviors according to
1137                                  *      1) err code : LDAP_BUSY ...
1138                                  *      2) on err policy : stop service, stop sync, retry
1139                                  */
1140                                 if ( refreshDeletes == 0 && match < 0 &&
1141                                         err == LDAP_SUCCESS &&
1142                                         syncCookie_req.numcsns == syncCookie.numcsns )
1143                                 {
1144                                         syncrepl_del_nonpresent( op, si, NULL,
1145                                                 &syncCookie, m );
1146                                 } else {
1147                                         avl_free( si->si_presentlist, ch_free );
1148                                         si->si_presentlist = NULL;
1149                                 }
1150                         }
1151                         if ( syncCookie.ctxcsn && match < 0 && err == LDAP_SUCCESS )
1152                         {
1153                                 rc = syncrepl_updateCookie( si, op, &syncCookie );
1154                         }
1155                         if ( err == LDAP_SUCCESS
1156                                 && si->si_logstate == SYNCLOG_FALLBACK ) {
1157                                 si->si_logstate = SYNCLOG_LOGGING;
1158                                 rc = LDAP_SYNC_REFRESH_REQUIRED;
1159                                 slap_resume_listeners();
1160                         } else {
1161                                 rc = -2;
1162                         }
1163                         goto done;
1164
1165                 case LDAP_RES_INTERMEDIATE:
1166                         retoid = NULL;
1167                         retdata = NULL;
1168                         rc = ldap_parse_intermediate( si->si_ld, msg,
1169                                 &retoid, &retdata, NULL, 0 );
1170                         if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
1171                                 ber_init2( ber, retdata, LBER_USE_DER );
1172
1173                                 switch ( si_tag = ber_peek_tag( ber, &len ) ) {
1174                                 ber_tag_t tag;
1175                                 case LDAP_TAG_SYNC_NEW_COOKIE:
1176                                         Debug( LDAP_DEBUG_SYNC,
1177                                                 "do_syncrep2: %s %s - %s\n", 
1178                                                 si->si_ridtxt,
1179                                                 "LDAP_RES_INTERMEDIATE", 
1180                                                 "NEW_COOKIE" );
1181                                         ber_scanf( ber, "tm", &tag, &cookie );
1182                                         Debug( LDAP_DEBUG_SYNC,
1183                                                 "do_syncrep2: %s NEW_COOKIE: %s\n",
1184                                                 si->si_ridtxt,
1185                                                 cookie.bv_val, 0);
1186                                         if ( !BER_BVISNULL( &cookie ) ) {
1187                                                 ch_free( syncCookie.octet_str.bv_val );
1188                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
1189                                         }
1190                                         if (!BER_BVISNULL( &syncCookie.octet_str ) ) {
1191                                                 slap_parse_sync_cookie( &syncCookie, NULL );
1192                                                 op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1193                                         }
1194                                         break;
1195                                 case LDAP_TAG_SYNC_REFRESH_DELETE:
1196                                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
1197                                         Debug( LDAP_DEBUG_SYNC,
1198                                                 "do_syncrep2: %s %s - %s\n", 
1199                                                 si->si_ridtxt,
1200                                                 "LDAP_RES_INTERMEDIATE", 
1201                                                 si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
1202                                                 "REFRESH_PRESENT" : "REFRESH_DELETE" );
1203                                         if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
1204                                                 si->si_refreshDelete = 1;
1205                                         } else {
1206                                                 si->si_refreshPresent = 1;
1207                                         }
1208                                         ber_scanf( ber, "t{" /*"}"*/, &tag );
1209                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
1210                                         {
1211                                                 ber_scanf( ber, "m", &cookie );
1212
1213                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1214                                                         si->si_ridtxt, 
1215                                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1216
1217                                                 if ( !BER_BVISNULL( &cookie ) ) {
1218                                                         ch_free( syncCookie.octet_str.bv_val );
1219                                                         ber_dupbv( &syncCookie.octet_str, &cookie );
1220                                                 }
1221                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1222                                                 {
1223                                                         slap_parse_sync_cookie( &syncCookie, NULL );
1224                                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1225                                                 }
1226                                         }
1227                                         /* Defaults to TRUE */
1228                                         if ( ber_peek_tag( ber, &len ) ==
1229                                                 LDAP_TAG_REFRESHDONE )
1230                                         {
1231                                                 ber_scanf( ber, "b", &si->si_refreshDone );
1232                                         } else
1233                                         {
1234                                                 si->si_refreshDone = 1;
1235                                         }
1236                                         ber_scanf( ber, /*"{"*/ "}" );
1237                                         break;
1238                                 case LDAP_TAG_SYNC_ID_SET:
1239                                         Debug( LDAP_DEBUG_SYNC,
1240                                                 "do_syncrep2: %s %s - %s\n", 
1241                                                 si->si_ridtxt,
1242                                                 "LDAP_RES_INTERMEDIATE", 
1243                                                 "SYNC_ID_SET" );
1244                                         ber_scanf( ber, "t{" /*"}"*/, &tag );
1245                                         if ( ber_peek_tag( ber, &len ) ==
1246                                                 LDAP_TAG_SYNC_COOKIE )
1247                                         {
1248                                                 ber_scanf( ber, "m", &cookie );
1249
1250                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1251                                                         si->si_ridtxt,
1252                                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1253
1254                                                 if ( !BER_BVISNULL( &cookie ) ) {
1255                                                         ch_free( syncCookie.octet_str.bv_val );
1256                                                         ber_dupbv( &syncCookie.octet_str, &cookie );
1257                                                 }
1258                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1259                                                 {
1260                                                         slap_parse_sync_cookie( &syncCookie, NULL );
1261                                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1262                                                         compare_csns( &syncCookie_req, &syncCookie, &m );
1263                                                 }
1264                                         }
1265                                         if ( ber_peek_tag( ber, &len ) ==
1266                                                 LDAP_TAG_REFRESHDELETES )
1267                                         {
1268                                                 ber_scanf( ber, "b", &refreshDeletes );
1269                                         }
1270                                         syncUUIDs = NULL;
1271                                         ber_scanf( ber, "[W]", &syncUUIDs );
1272                                         ber_scanf( ber, /*"{"*/ "}" );
1273                                         if ( refreshDeletes ) {
1274                                                 syncrepl_del_nonpresent( op, si, syncUUIDs,
1275                                                         &syncCookie, m );
1276                                                 ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
1277                                         } else {
1278                                                 int i;
1279                                                 for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
1280                                                         (void)avl_presentlist_insert( si, &syncUUIDs[i] );
1281                                                         slap_sl_free( syncUUIDs[i].bv_val, op->o_tmpmemctx );
1282                                                 }
1283                                                 slap_sl_free( syncUUIDs, op->o_tmpmemctx );
1284                                         }
1285                                         slap_sync_cookie_free( &syncCookie, 0 );
1286                                         break;
1287                                 default:
1288                                         Debug( LDAP_DEBUG_ANY,
1289                                                 "do_syncrep2: %s unknown syncinfo tag (%ld)\n",
1290                                                 si->si_ridtxt, (long) si_tag, 0 );
1291                                         ldap_memfree( retoid );
1292                                         ber_bvfree( retdata );
1293                                         continue;
1294                                 }
1295
1296                                 if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
1297                                         slap_sync_cookie_free( &syncCookie_req, 0 );
1298                                         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
1299                                 }
1300                                 if ( !syncCookie.ctxcsn ) {
1301                                         match = 1;
1302                                 } else if ( !syncCookie_req.ctxcsn ) {
1303                                         match = -1;
1304                                         m = 0;
1305                                 } else {
1306                                         match = compare_csns( &syncCookie_req, &syncCookie, &m );
1307                                 }
1308
1309                                 if ( match < 0 ) {
1310                                         if ( si->si_refreshPresent == 1 &&
1311                                                 si_tag != LDAP_TAG_SYNC_NEW_COOKIE &&
1312                                                 syncCookie_req.numcsns == syncCookie.numcsns ) {
1313                                                 syncrepl_del_nonpresent( op, si, NULL,
1314                                                         &syncCookie, m );
1315                                         }
1316
1317                                         if ( syncCookie.ctxcsn )
1318                                         {
1319                                                 rc = syncrepl_updateCookie( si, op, &syncCookie);
1320                                         }
1321                                 } 
1322
1323                                 ldap_memfree( retoid );
1324                                 ber_bvfree( retdata );
1325
1326                         } else {
1327                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1328                                         "unknown intermediate response (%d)\n",
1329                                         si->si_ridtxt, rc, 0 );
1330                                 ldap_memfree( retoid );
1331                                 ber_bvfree( retdata );
1332                         }
1333                         break;
1334
1335                 default:
1336                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1337                                 "unknown message (0x%02lx)\n",
1338                                 si->si_ridtxt,
1339                                 (unsigned long)ldap_msgtype( msg ), 0 );
1340                         break;
1341
1342                 }
1343                 if ( !BER_BVISNULL( &syncCookie.octet_str ) ) {
1344                         slap_sync_cookie_free( &syncCookie_req, 0 );
1345                         slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
1346                         slap_sync_cookie_free( &syncCookie, 0 );
1347                 }
1348                 ldap_msgfree( msg );
1349                 msg = NULL;
1350                 if ( ldap_pvt_thread_pool_pausing( &connection_pool )) {
1351                         slap_sync_cookie_free( &syncCookie, 0 );
1352                         slap_sync_cookie_free( &syncCookie_req, 0 );
1353                         return SYNC_PAUSED;
1354                 }
1355         }
1356
1357         if ( rc == -1 ) {
1358                 rc = LDAP_OTHER;
1359                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
1360                 err = rc;
1361         }
1362
1363 done:
1364         if ( err != LDAP_SUCCESS ) {
1365                 Debug( LDAP_DEBUG_ANY,
1366                         "do_syncrep2: %s (%d) %s\n",
1367                         si->si_ridtxt, err, ldap_err2string( err ) );
1368         }
1369
1370         slap_sync_cookie_free( &syncCookie, 0 );
1371         slap_sync_cookie_free( &syncCookie_req, 0 );
1372
1373         if ( msg ) ldap_msgfree( msg );
1374
1375         if ( rc && rc != LDAP_SYNC_REFRESH_REQUIRED && si->si_ld ) {
1376                 if ( si->si_conn ) {
1377                         connection_client_stop( si->si_conn );
1378                         si->si_conn = NULL;
1379                 }
1380                 ldap_unbind_ext( si->si_ld, NULL, NULL );
1381                 si->si_ld = NULL;
1382         }
1383
1384         return rc;
1385 }
1386
1387 static void *
1388 do_syncrepl(
1389         void    *ctx,
1390         void    *arg )
1391 {
1392         struct re_s* rtask = arg;
1393         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
1394         Connection conn = {0};
1395         OperationBuffer opbuf;
1396         Operation *op;
1397         int rc = LDAP_SUCCESS;
1398         int dostop = 0;
1399         ber_socket_t s;
1400         int i, defer = 1, fail = 0, freeinfo = 0;
1401         Backend *be;
1402
1403         if ( si == NULL )
1404                 return NULL;
1405         if ( slapd_shutdown )
1406                 return NULL;
1407
1408         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl %s\n", si->si_ridtxt, 0, 0 );
1409
1410         /* Don't get stuck here while a pause is initiated */
1411         while ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
1412                 if ( slapd_shutdown )
1413                         return NULL;
1414                 if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1415                         ldap_pvt_thread_yield();
1416         }
1417
1418         if ( si->si_ctype < 1 ) {
1419                 goto deleted;
1420         }
1421
1422         switch( abs( si->si_type ) ) {
1423         case LDAP_SYNC_REFRESH_ONLY:
1424         case LDAP_SYNC_REFRESH_AND_PERSIST:
1425                 break;
1426         default:
1427                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1428                 return NULL;
1429         }
1430
1431         if ( slapd_shutdown ) {
1432                 if ( si->si_ld ) {
1433                         if ( si->si_conn ) {
1434                                 connection_client_stop( si->si_conn );
1435                                 si->si_conn = NULL;
1436                         }
1437                         ldap_unbind_ext( si->si_ld, NULL, NULL );
1438                         si->si_ld = NULL;
1439                 }
1440                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1441                 return NULL;
1442         }
1443
1444         connection_fake_init( &conn, &opbuf, ctx );
1445         op = &opbuf.ob_op;
1446         /* o_connids must be unique for slap_graduate_commit_csn */
1447         op->o_connid = SLAPD_SYNC_RID2SYNCCONN(si->si_rid);
1448
1449         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1450         be = si->si_be;
1451
1452         /* Coordinate contextCSN updates with any syncprov overlays
1453          * in use. This may be complicated by the use of the glue
1454          * overlay.
1455          *
1456          * Typically there is a single syncprov mastering the entire
1457          * glued tree. In that case, our contextCSN updates should
1458          * go to the master DB. But if there is no syncprov on the
1459          * master DB, then nothing special is needed here.
1460          *
1461          * Alternatively, there may be individual syncprov overlays
1462          * on each glued branch. In that case, each syncprov only
1463          * knows about changes within its own branch. And so our
1464          * contextCSN updates should only go to the local DB.
1465          */
1466         if ( !si->si_wbe ) {
1467                 if ( SLAP_GLUE_SUBORDINATE( be ) && !overlay_is_inst( be, "syncprov" )) {
1468                         BackendDB * top_be = select_backend( &be->be_nsuffix[0], 1 );
1469                         if ( overlay_is_inst( top_be, "syncprov" ))
1470                                 si->si_wbe = top_be;
1471                         else
1472                                 si->si_wbe = be;
1473                 } else {
1474                         si->si_wbe = be;
1475                 }
1476                 if ( SLAP_SYNC_SUBENTRY( si->si_wbe )) {
1477                         build_new_dn( &si->si_contextdn, &si->si_wbe->be_nsuffix[0],
1478                                 (struct berval *)&slap_ldapsync_cn_bv, NULL );
1479                 } else {
1480                         si->si_contextdn = si->si_wbe->be_nsuffix[0];
1481                 }
1482         }
1483         if ( !si->si_schemachecking )
1484                 op->o_no_schema_check = 1;
1485
1486         /* Establish session, do search */
1487         if ( !si->si_ld ) {
1488                 si->si_refreshDelete = 0;
1489                 si->si_refreshPresent = 0;
1490
1491                 if ( si->si_presentlist ) {
1492                     avl_free( si->si_presentlist, ch_free );
1493                     si->si_presentlist = NULL;
1494                 }
1495
1496                 /* use main DB when retrieving contextCSN */
1497                 op->o_bd = si->si_wbe;
1498                 op->o_dn = op->o_bd->be_rootdn;
1499                 op->o_ndn = op->o_bd->be_rootndn;
1500                 rc = do_syncrep1( op, si );
1501         }
1502
1503 reload:
1504         /* Process results */
1505         if ( rc == LDAP_SUCCESS ) {
1506                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1507
1508                 /* use current DB */
1509                 op->o_bd = be;
1510                 op->o_dn = op->o_bd->be_rootdn;
1511                 op->o_ndn = op->o_bd->be_rootndn;
1512                 rc = do_syncrep2( op, si );
1513                 if ( rc == LDAP_SYNC_REFRESH_REQUIRED ) {
1514                         rc = ldap_sync_search( si, op->o_tmpmemctx );
1515                         goto reload;
1516                 }
1517
1518 deleted:
1519                 /* We got deleted while running on cn=config */
1520                 if ( si->si_ctype < 1 ) {
1521                         if ( si->si_ctype == -1 ) {
1522                                 si->si_ctype = 0;
1523                                 freeinfo = 1;
1524                         }
1525                         if ( si->si_conn )
1526                                 dostop = 1;
1527                         rc = -1;
1528                 }
1529
1530                 if ( rc != SYNC_PAUSED ) {
1531                         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1532                                 /* If we succeeded, enable the connection for further listening.
1533                                  * If we failed, tear down the connection and reschedule.
1534                                  */
1535                                 if ( rc == LDAP_SUCCESS ) {
1536                                         if ( si->si_conn ) {
1537                                                 connection_client_enable( si->si_conn );
1538                                         } else {
1539                                                 si->si_conn = connection_client_setup( s, do_syncrepl, arg );
1540                                         } 
1541                                 } else if ( si->si_conn ) {
1542                                         dostop = 1;
1543                                 }
1544                         } else {
1545                                 if ( rc == -2 ) rc = 0;
1546                         }
1547                 }
1548         }
1549
1550         /* At this point, we have 5 cases:
1551          * 1) for any hard failure, give up and remove this task
1552          * 2) for ServerDown, reschedule this task to run later
1553          * 3) for threadpool pause, reschedule to run immediately
1554          * 4) for Refresh and Success, reschedule to run
1555          * 5) for Persist and Success, reschedule to defer
1556          */
1557         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1558
1559         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask ) ) {
1560                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1561         }
1562
1563         if ( dostop ) {
1564                 connection_client_stop( si->si_conn );
1565                 si->si_conn = NULL;
1566         }
1567
1568         if ( rc == SYNC_PAUSED ) {
1569                 rtask->interval.tv_sec = 0;
1570                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1571                 rtask->interval.tv_sec = si->si_interval;
1572                 rc = 0;
1573         } else if ( rc == LDAP_SUCCESS ) {
1574                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1575                         defer = 0;
1576                 }
1577                 rtask->interval.tv_sec = si->si_interval;
1578                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1579                 if ( si->si_retrynum ) {
1580                         for ( i = 0; si->si_retrynum_init[i] != RETRYNUM_TAIL; i++ ) {
1581                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1582                         }
1583                         si->si_retrynum[i] = RETRYNUM_TAIL;
1584                 }
1585         } else {
1586                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1587                         if ( si->si_retrynum[i] == RETRYNUM_FOREVER || si->si_retrynum[i] == RETRYNUM_TAIL )
1588                                 break;
1589                 }
1590
1591                 if ( si->si_ctype < 1
1592                         || !si->si_retrynum || si->si_retrynum[i] == RETRYNUM_TAIL ) {
1593                         if ( si->si_re ) {
1594                                 ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1595                                 si->si_re = NULL;
1596                         }
1597                         fail = RETRYNUM_TAIL;
1598                 } else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1599                         if ( si->si_retrynum[i] > 0 )
1600                                 si->si_retrynum[i]--;
1601                         fail = si->si_retrynum[i];
1602                         rtask->interval.tv_sec = si->si_retryinterval[i];
1603                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1604                         slap_wake_listener();
1605                 }
1606         }
1607
1608         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1609         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1610
1611         if ( rc ) {
1612                 if ( fail == RETRYNUM_TAIL ) {
1613                         Debug( LDAP_DEBUG_ANY,
1614                                 "do_syncrepl: %s rc %d quitting\n",
1615                                 si->si_ridtxt, rc, 0 );
1616                 } else if ( fail > 0 ) {
1617                         Debug( LDAP_DEBUG_ANY,
1618                                 "do_syncrepl: %s rc %d retrying (%d retries left)\n",
1619                                 si->si_ridtxt, rc, fail );
1620                 } else {
1621                         Debug( LDAP_DEBUG_ANY,
1622                                 "do_syncrepl: %s rc %d retrying\n",
1623                                 si->si_ridtxt, rc, 0 );
1624                 }
1625         }
1626
1627         /* Do final delete cleanup */
1628         if ( freeinfo ) {
1629                 syncinfo_free( si, 0 );
1630         }
1631         return NULL;
1632 }
1633
1634 #ifdef ENABLE_REWRITE
1635 static int
1636 syncrepl_rewrite_dn(
1637         syncinfo_t *si,
1638         struct berval *dn,
1639         struct berval *sdn )
1640 {
1641         char nul;
1642         int rc;
1643
1644         nul = dn->bv_val[dn->bv_len];
1645         dn->bv_val[dn->bv_len] = 0;
1646         rc = rewrite( si->si_rewrite, SUFFIXM_CTX, dn->bv_val, &sdn->bv_val );
1647         dn->bv_val[dn->bv_len] = nul;
1648
1649         if ( sdn->bv_val == dn->bv_val )
1650                 sdn->bv_val = NULL;
1651         else if ( rc == REWRITE_REGEXEC_OK && sdn->bv_val )
1652                 sdn->bv_len = strlen( sdn->bv_val );
1653         return rc;
1654 }
1655 #define REWRITE_VAL(si, ad, bv, bv2)    \
1656         BER_BVZERO( &bv2 );     \
1657         if ( si->si_rewrite && ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName) \
1658                 syncrepl_rewrite_dn( si, &bv, &bv2); \
1659         if ( BER_BVISNULL( &bv2 ))  \
1660                 ber_dupbv( &bv2, &bv )
1661 #define REWRITE_DN(si, bv, bv2, dn, ndn) \
1662         BER_BVZERO( &bv2 );     \
1663         if (si->si_rewrite) \
1664                 syncrepl_rewrite_dn(si, &bv, &bv2); \
1665         rc = dnPrettyNormal( NULL, bv2.bv_val ? &bv2 : &bv, &dn, &ndn, op->o_tmpmemctx ); \
1666         ch_free(bv2.bv_val)
1667 #else
1668 #define REWRITE_VAL(si, ad, bv, bv2)    ber_dupbv(&bv2, &bv)
1669 #define REWRITE_DN(si, bv, bv2, dn, ndn) \
1670         rc = dnPrettyNormal( NULL, &bv, &dn, &ndn, op->o_tmpmemctx )
1671 #endif
1672
1673
1674 static slap_verbmasks modops[] = {
1675         { BER_BVC("add"), LDAP_REQ_ADD },
1676         { BER_BVC("delete"), LDAP_REQ_DELETE },
1677         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1678         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1679         { BER_BVNULL, 0 }
1680 };
1681
1682 static int
1683 syncrepl_accesslog_mods(
1684         syncinfo_t *si,
1685         struct berval *vals,
1686         struct Modifications **modres
1687 )
1688 {
1689         char *colon;
1690         const char *text;
1691         AttributeDescription *ad;
1692         struct berval bv, bv2;
1693         short op;
1694         Modifications *mod = NULL, *modlist = NULL, **modtail;
1695         int i, rc = 0;
1696
1697         modtail = &modlist;
1698
1699         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1700                 ad = NULL;
1701                 bv = vals[i];
1702
1703                 colon = ber_bvchr( &bv, ':' );
1704                 if ( !colon ) {
1705                         /* Invalid */
1706                         continue;
1707                 }
1708
1709                 bv.bv_len = colon - bv.bv_val;
1710                 if ( slap_bv2ad( &bv, &ad, &text ) ) {
1711                         /* Invalid */
1712                         Debug( LDAP_DEBUG_ANY, "syncrepl_accesslog_mods: %s "
1713                                 "Invalid attribute %s, %s\n",
1714                                 si->si_ridtxt, bv.bv_val, text );
1715                         slap_mods_free( modlist, 1 );
1716                         modlist = NULL;
1717                         rc = -1;
1718                         break;
1719                 }
1720
1721                 /* Ignore dynamically generated attrs */
1722                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1723                         continue;
1724                 }
1725
1726                 /* Ignore excluded attrs */
1727                 if ( ldap_charray_inlist( si->si_exattrs,
1728                         ad->ad_type->sat_cname.bv_val ) )
1729                 {
1730                         continue;
1731                 }
1732
1733                 switch(colon[1]) {
1734                 case '+':       op = LDAP_MOD_ADD; break;
1735                 case '-':       op = LDAP_MOD_DELETE; break;
1736                 case '=':       op = LDAP_MOD_REPLACE; break;
1737                 case '#':       op = LDAP_MOD_INCREMENT; break;
1738                 default:        continue;
1739                 }
1740
1741                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1742                         mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
1743                         mod->sml_flags = 0;
1744                         mod->sml_op = op;
1745                         mod->sml_next = NULL;
1746                         mod->sml_desc = ad;
1747                         mod->sml_type = ad->ad_cname;
1748                         mod->sml_values = NULL;
1749                         mod->sml_nvalues = NULL;
1750                         mod->sml_numvals = 0;
1751
1752                         *modtail = mod;
1753                         modtail = &mod->sml_next;
1754                 }
1755                 if ( colon[2] == ' ' ) {
1756                         bv.bv_val = colon + 3;
1757                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1758                         REWRITE_VAL( si, ad, bv, bv2 );
1759                         ber_bvarray_add( &mod->sml_values, &bv2 );
1760                         mod->sml_numvals++;
1761                 }
1762         }
1763         *modres = modlist;
1764         return rc;
1765 }
1766
1767 static int
1768 syncrepl_changelog_mods(
1769         syncinfo_t *si,
1770         struct berval *vals,
1771         struct Modifications **modres
1772 )
1773 {
1774         return -1;      /* FIXME */
1775 }
1776
1777 typedef struct OpExtraSync {
1778         OpExtra oe;
1779         syncinfo_t *oe_si;
1780 } OpExtraSync;
1781
1782 /* Copy the original modlist, split Replace ops into Delete/Add,
1783  * and drop mod opattrs since this modification is in the past.
1784  */
1785 static Modifications *mods_dup( Operation *op, Modifications *modlist )
1786 {
1787         Modifications *mod, *modnew = NULL, *modtail = NULL;
1788         int size;
1789         for ( ; modlist; modlist = modlist->sml_next ) {
1790                 if ( modlist->sml_desc == slap_schema.si_ad_modifiersName ||
1791                         modlist->sml_desc == slap_schema.si_ad_modifyTimestamp ||
1792                         modlist->sml_desc == slap_schema.si_ad_entryCSN )
1793                         continue;
1794                 if ( modlist->sml_op == LDAP_MOD_REPLACE ) {
1795                         mod = op->o_tmpalloc( sizeof(Modifications), op->o_tmpmemctx );
1796                         mod->sml_desc = modlist->sml_desc;
1797                         mod->sml_values = NULL;
1798                         mod->sml_nvalues = NULL;
1799                         mod->sml_op = LDAP_MOD_DELETE;
1800                         mod->sml_numvals = 0;
1801                         mod->sml_flags = 0;
1802                         if ( !modnew )
1803                                 modnew = mod;
1804                         if ( modtail )
1805                                 modtail->sml_next = mod;
1806                         modtail = mod;
1807                 }
1808                 if ( modlist->sml_numvals ) {
1809                         size = (modlist->sml_numvals+1) * sizeof(struct berval);
1810                         if ( modlist->sml_nvalues ) size *= 2;
1811                 } else {
1812                         size = 0;
1813                 }
1814                 size += sizeof(Modifications);
1815                 mod = op->o_tmpalloc( size, op->o_tmpmemctx );
1816                 if ( !modnew )
1817                         modnew = mod;
1818                 if ( modtail )
1819                         modtail->sml_next = mod;
1820                 modtail = mod;
1821                 mod->sml_desc = modlist->sml_desc;
1822                 mod->sml_numvals = modlist->sml_numvals;
1823                 mod->sml_flags = 0;
1824                 if ( modlist->sml_numvals ) {
1825                         int i;
1826                         mod->sml_values = (BerVarray)(mod+1);
1827                         for (i=0; i<mod->sml_numvals; i++)
1828                                 mod->sml_values[i] = modlist->sml_values[i];
1829                         if ( modlist->sml_nvalues ) {
1830                                 mod->sml_nvalues = mod->sml_values + mod->sml_numvals + 1;
1831                                 for (i=0; i<mod->sml_numvals; i++)
1832                                         mod->sml_nvalues[i] = modlist->sml_nvalues[i];
1833                         }
1834                 }
1835                 if ( modlist->sml_op == LDAP_MOD_REPLACE )
1836                         mod->sml_op = LDAP_MOD_ADD;
1837                 else
1838                         mod->sml_op = modlist->sml_op;
1839                 mod->sml_next = NULL;
1840         }
1841         return modnew;
1842 }
1843
1844 typedef struct resolve_ctxt {
1845         syncinfo_t *rx_si;
1846         Modifications *rx_mods;
1847 } resolve_ctxt;
1848
1849 static void
1850 compare_vals( Modifications *m1, Modifications *m2 )
1851 {
1852         int i, j;
1853         struct berval *bv1, *bv2;
1854
1855         if ( m2->sml_nvalues ) {
1856                 bv2 = m2->sml_nvalues;
1857                 bv1 = m1->sml_nvalues;
1858         } else {
1859                 bv2 = m2->sml_values;
1860                 bv1 = m1->sml_values;
1861         }
1862         for ( j=0; j<m2->sml_numvals; j++ ) {
1863                 for ( i=0; i<m1->sml_numvals; i++ ) {
1864                         if ( !ber_bvcmp( &bv1[i], &bv2[j] )) {
1865                                 int k;
1866                                 for ( k=i; k<m1->sml_numvals-1; k++ ) {
1867                                         m1->sml_values[k] = m1->sml_values[k+1];
1868                                         if ( m1->sml_nvalues )
1869                                                 m1->sml_nvalues[k] = m1->sml_nvalues[k+1];
1870                                 }
1871                                 m1->sml_numvals--;
1872                                 i--;
1873                         }
1874                 }
1875         }
1876 }
1877
1878 static int
1879 syncrepl_resolve_cb( Operation *op, SlapReply *rs )
1880 {
1881         if ( rs->sr_type == REP_SEARCH ) {
1882                 resolve_ctxt *rx = op->o_callback->sc_private;
1883                 Attribute *a = attr_find( rs->sr_entry->e_attrs, ad_reqMod );
1884                 if ( a ) {
1885                         Modifications *oldmods, *newmods, *m1, *m2, **prev;
1886                         oldmods = rx->rx_mods;
1887                         syncrepl_accesslog_mods( rx->rx_si, a->a_vals, &newmods );
1888                         for ( m2 = newmods; m2; m2=m2->sml_next ) {
1889                                 for ( prev = &oldmods, m1 = *prev; m1; m1 = *prev ) {
1890                                         if ( m1->sml_desc != m2->sml_desc ) {
1891                                                 prev = &m1->sml_next;
1892                                                 continue;
1893                                         }
1894                                         if ( m2->sml_op == LDAP_MOD_DELETE ||
1895                                                 m2->sml_op == LDAP_MOD_REPLACE ) {
1896                                                 int numvals = m2->sml_numvals;
1897                                                 if ( m2->sml_op == LDAP_MOD_REPLACE )
1898                                                         numvals = 0;
1899                                                 /* New delete All cancels everything */
1900                                                 if ( numvals == 0 ) {
1901 drop:
1902                                                         *prev = m1->sml_next;
1903                                                         op->o_tmpfree( m1, op->o_tmpmemctx );
1904                                                         continue;
1905                                                 }
1906                                                 if ( m1->sml_op == LDAP_MOD_DELETE ) {
1907                                                         if ( m1->sml_numvals == 0 ) {
1908                                                                 /* turn this to SOFTDEL later */
1909                                                                 m1->sml_flags = SLAP_MOD_INTERNAL;
1910                                                         } else {
1911                                                                 compare_vals( m1, m2 );
1912                                                                 if ( !m1->sml_numvals )
1913                                                                         goto drop;
1914                                                         }
1915                                                 } else if ( m1->sml_op == LDAP_MOD_ADD ) {
1916                                                         compare_vals( m1, m2 );
1917                                                         if ( !m1->sml_numvals )
1918                                                                 goto drop;
1919                                                 }
1920                                         }
1921
1922                                         if ( m2->sml_op == LDAP_MOD_ADD ||
1923                                                 m2->sml_op == LDAP_MOD_REPLACE ) {
1924                                                 if ( m1->sml_op == LDAP_MOD_DELETE ) {
1925                                                         if ( !m1->sml_numvals ) goto drop;
1926                                                         compare_vals( m1, m2 );
1927                                                         if ( !m1->sml_numvals )
1928                                                                 goto drop;
1929                                                 }
1930                                                 if ( m2->sml_desc->ad_type->sat_atype.at_single_value )
1931                                                         goto drop;
1932                                                 compare_vals( m1, m2 );
1933                                                 if ( !m1->sml_numvals )
1934                                                         goto drop;
1935                                         }
1936                                         prev = &m1->sml_next;
1937                                 }
1938                         }
1939                         slap_mods_free( newmods, 1 );
1940                 }
1941         }
1942         return LDAP_SUCCESS;
1943 }
1944
1945 typedef struct modify_ctxt {
1946         Modifications *mx_orig;
1947         Modifications *mx_free;
1948 } modify_ctxt;
1949
1950 static int
1951 syncrepl_modify_cb( Operation *op, SlapReply *rs )
1952 {
1953         slap_callback *sc = op->o_callback;
1954         modify_ctxt *mx = sc->sc_private;
1955         Modifications *ml;
1956
1957         op->o_callback = sc->sc_next;
1958         op->o_tmpfree( sc, op->o_tmpmemctx );
1959
1960         op->orm_no_opattrs = 0;
1961         op->orm_modlist = mx->mx_orig;
1962         for ( ml = mx->mx_free; ml; ml = mx->mx_free ) {
1963                 mx->mx_free = ml->sml_next;
1964                 op->o_tmpfree( ml, op->o_tmpmemctx );
1965         }
1966         return SLAP_CB_CONTINUE;
1967 }
1968
1969 static int
1970 syncrepl_op_modify( Operation *op, SlapReply *rs )
1971 {
1972         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1973         OpExtra *oex;
1974         syncinfo_t *si;
1975         Entry *e;
1976         int rc, match = 0;
1977         Modifications *mod, *newlist;
1978
1979         LDAP_SLIST_FOREACH( oex, &op->o_extra, oe_next ) {
1980                 if ( oex->oe_key == (void *)syncrepl_message_to_op )
1981                         break;
1982         }
1983         if ( !oex )
1984                 return SLAP_CB_CONTINUE;
1985
1986         si = ((OpExtraSync *)oex)->oe_si;
1987
1988         /* Check if entryCSN in modlist is newer than entryCSN in entry.
1989          * We do it here because the op has been serialized by accesslog
1990          * by the time we get here. If the CSN is new enough, just do the
1991          * mod. If not, we need to resolve conflicts.
1992          */
1993
1994         for ( mod = op->orm_modlist; mod; mod=mod->sml_next ) {
1995                 if ( mod->sml_desc == slap_schema.si_ad_entryCSN ) break;
1996         }
1997         /* FIXME: what should we do if entryCSN is missing from the mod? */
1998         if ( !mod )
1999                 return SLAP_CB_CONTINUE;
2000
2001         rc = overlay_entry_get_ov( op, &op->o_req_ndn, NULL, NULL, 0, &e, on );
2002         if ( rc == 0 ) {
2003                 Attribute *a;
2004                 const char *text;
2005                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryCSN );
2006                 value_match( &match, slap_schema.si_ad_entryCSN,
2007                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
2008                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
2009                         &mod->sml_nvalues[0], &a->a_nvals[0], &text );
2010                 overlay_entry_release_ov( op, e, 0, on );
2011         }
2012         /* mod is newer, let it go */
2013         if ( match > 0 ) {
2014                 for ( mod = op->orm_modlist; mod; mod=mod->sml_next ) {
2015                         if ( mod->sml_op == LDAP_MOD_DELETE )
2016                                 mod->sml_op = SLAP_MOD_SOFTDEL;
2017                 }
2018                 return SLAP_CB_CONTINUE;
2019         }
2020         /* equal? Should never happen */
2021         if ( match == 0 )
2022                 return LDAP_SUCCESS;
2023
2024         /* mod is older: resolve conflicts...
2025          * 1. Save/copy original modlist. Split Replace to Del/Add.
2026          * 2. Find all mods to this reqDN newer than the mod stamp.
2027          * 3. Resolve any mods in this request that affect attributes
2028          *    touched by newer mods.
2029          *    old         new
2030          *    delete all  delete all  drop
2031          *    delete all  delete X    SOFTDEL
2032          *    delete X    delete all  drop
2033          *    delete X    delete X    drop
2034          *    delete X    delete Y    OK
2035          *    delete all  add X       drop
2036          *    delete X    add X       drop
2037          *    delete X    add Y       OK
2038          *    add X       delete all  drop
2039          *    add X       delete X    drop
2040          *    add X       add X       drop
2041          *    add X       add Y       if SV, drop else OK
2042          *
2043          * 4. Swap original modlist back in response callback so
2044          *    that accesslog logs the original mod.
2045          */
2046
2047         newlist = mods_dup( op, op->orm_modlist );
2048
2049         {
2050                 Operation op2 = *op;
2051                 AttributeName an[2];
2052                 const char *text;
2053                 slap_callback cb;
2054                 struct berval bv;
2055                 char *ptr;
2056                 int size, rc;
2057                 SlapReply rs1 = {0};
2058                 resolve_ctxt rx = { si, newlist };
2059
2060                 op2.o_tag = LDAP_REQ_SEARCH;
2061                 op2.ors_scope = LDAP_SCOPE_SUBTREE;
2062                 op2.ors_deref = LDAP_DEREF_NEVER;
2063                 op2.o_req_dn = si->si_logbase;
2064                 op2.o_req_ndn = si->si_logbase;
2065                 op2.ors_tlimit = SLAP_NO_LIMIT;
2066                 op2.ors_slimit = SLAP_NO_LIMIT;
2067                 op2.ors_limit = NULL;
2068                 memset( an, 0, sizeof(an));
2069                 an[0].an_desc = ad_reqMod;
2070                 an[0].an_name = ad_reqMod->ad_cname;
2071                 op2.ors_attrs = an;
2072                 op2.ors_attrsonly = 0;
2073
2074                 bv = mod->sml_nvalues[0];
2075
2076                 size = sizeof("(&(entryCSN>=)(reqDN=))");
2077                 size += bv.bv_len + op->o_req_ndn.bv_len + si->si_logfilterstr.bv_len;
2078                 op2.ors_filterstr.bv_val = op->o_tmpalloc( size, op->o_tmpmemctx );
2079                 op2.ors_filterstr.bv_len = sprintf(op2.ors_filterstr.bv_val,
2080                         "(&(entryCSN>=%s)(reqDN=%s)%s)",
2081                         bv.bv_val, op->o_req_ndn.bv_val, si->si_logfilterstr.bv_val );
2082                 op2.ors_filter = str2filter_x( op, op2.ors_filterstr.bv_val );
2083
2084                 op2.o_callback = &cb;
2085                 cb.sc_response = syncrepl_resolve_cb;
2086                 cb.sc_private = &rx;
2087                 op2.o_bd = select_backend( &op2.o_req_ndn, 1 );
2088                 op2.o_bd->be_search( &op2, &rs1 );
2089                 newlist = rx.rx_mods;
2090         }
2091
2092         {
2093                 slap_callback *sc = op->o_tmpalloc( sizeof(slap_callback) +
2094                         sizeof(modify_ctxt), op->o_tmpmemctx );
2095                 modify_ctxt *mx = (modify_ctxt *)(sc+1);
2096                 Modifications *ml;
2097
2098                 sc->sc_response = syncrepl_modify_cb;
2099                 sc->sc_private = mx;
2100                 sc->sc_next = op->o_callback;
2101                 op->o_callback = sc;
2102                 op->orm_no_opattrs = 1;
2103                 mx->mx_orig = op->orm_modlist;
2104                 mx->mx_free = newlist;
2105                 for ( ml = newlist; ml; ml=ml->sml_next ) {
2106                         if ( ml->sml_flags == SLAP_MOD_INTERNAL ) {
2107                                 ml->sml_flags = 0;
2108                                 ml->sml_op = SLAP_MOD_SOFTDEL;
2109                         }
2110                 }
2111                 op->orm_modlist = newlist;
2112                 op->o_csn = mod->sml_nvalues[0];
2113         }
2114         return SLAP_CB_CONTINUE;
2115 }
2116
2117 static int
2118 syncrepl_message_to_op(
2119         syncinfo_t      *si,
2120         Operation       *op,
2121         LDAPMessage     *msg
2122 )
2123 {
2124         BerElement      *ber = NULL;
2125         Modifications   *modlist = NULL;
2126         logschema *ls;
2127         SlapReply rs = { REP_RESULT };
2128         slap_callback cb = { NULL, null_callback, NULL, NULL };
2129
2130         const char      *text;
2131         char txtbuf[SLAP_TEXT_BUFLEN];
2132         size_t textlen = sizeof txtbuf;
2133
2134         struct berval   bdn, dn = BER_BVNULL, ndn;
2135         struct berval   bv, bv2, *bvals = NULL;
2136         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
2137                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
2138                 psup = BER_BVNULL, nsup = BER_BVNULL;
2139         int             rc, deleteOldRdn = 0, freeReqDn = 0;
2140         int             do_graduate = 0;
2141
2142         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
2143                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
2144                         "Message type should be entry (%d)",
2145                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
2146                 return -1;
2147         }
2148
2149         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
2150                 ls = &accesslog_sc;
2151         else
2152                 ls = &changelog_sc;
2153
2154         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
2155
2156         if ( rc != LDAP_SUCCESS ) {
2157                 Debug( LDAP_DEBUG_ANY,
2158                         "syncrepl_message_to_op: %s dn get failed (%d)",
2159                         si->si_ridtxt, rc, 0 );
2160                 return rc;
2161         }
2162
2163         op->o_tag = LBER_DEFAULT;
2164         op->o_bd = si->si_wbe;
2165
2166         if ( BER_BVISEMPTY( &bdn )) {
2167                 Debug( LDAP_DEBUG_ANY,
2168                         "syncrepl_message_to_op: %s got empty dn",
2169                         si->si_ridtxt, 0, 0 );
2170                 return LDAP_OTHER;
2171         }
2172
2173         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ) )
2174                 == LDAP_SUCCESS ) {
2175                 if ( bv.bv_val == NULL )
2176                         break;
2177
2178                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn ) ) {
2179                         bdn = bvals[0];
2180                         REWRITE_DN( si, bdn, bv2, dn, ndn );
2181                         if ( rc != LDAP_SUCCESS ) {
2182                                 Debug( LDAP_DEBUG_ANY,
2183                                         "syncrepl_message_to_op: %s "
2184                                         "dn \"%s\" normalization failed (%d)",
2185                                         si->si_ridtxt, bdn.bv_val, rc );
2186                                 rc = -1;
2187                                 ch_free( bvals );
2188                                 goto done;
2189                         }
2190                         ber_dupbv( &op->o_req_dn, &dn );
2191                         ber_dupbv( &op->o_req_ndn, &ndn );
2192                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
2193                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
2194                         freeReqDn = 1;
2195                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req ) ) {
2196                         int i = verb_to_mask( bvals[0].bv_val, modops );
2197                         if ( i < 0 ) {
2198                                 Debug( LDAP_DEBUG_ANY,
2199                                         "syncrepl_message_to_op: %s unknown op %s",
2200                                         si->si_ridtxt, bvals[0].bv_val, 0 );
2201                                 ch_free( bvals );
2202                                 rc = -1;
2203                                 goto done;
2204                         }
2205                         op->o_tag = modops[i].mask;
2206                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod ) ) {
2207                         /* Parse attribute into modlist */
2208                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG ) {
2209                                 rc = syncrepl_accesslog_mods( si, bvals, &modlist );
2210                         } else {
2211                                 rc = syncrepl_changelog_mods( si, bvals, &modlist );
2212                         }
2213                         if ( rc ) goto done;
2214                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn ) ) {
2215                         rdn = bvals[0];
2216                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn ) ) {
2217                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ) ) {
2218                                 deleteOldRdn = 1;
2219                         }
2220                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup ) ) {
2221                         sup = bvals[0];
2222                 } else if ( !ber_bvstrcasecmp( &bv,
2223                         &slap_schema.si_ad_entryCSN->ad_cname ) )
2224                 {
2225                         slap_queue_csn( op, bvals );
2226                         do_graduate = 1;
2227                 }
2228                 ch_free( bvals );
2229         }
2230
2231         /* If we didn't get a mod type or a target DN, bail out */
2232         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn ) ) {
2233                 rc = -1;
2234                 goto done;
2235         }
2236
2237         op->o_callback = &cb;
2238         slap_op_time( &op->o_time, &op->o_tincr );
2239
2240         switch( op->o_tag ) {
2241         case LDAP_REQ_ADD:
2242         case LDAP_REQ_MODIFY:
2243                 /* If we didn't get required data, bail */
2244                 if ( !modlist ) goto done;
2245
2246                 rc = slap_mods_check( op, modlist, &text, txtbuf, textlen, NULL );
2247
2248                 if ( rc != LDAP_SUCCESS ) {
2249                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
2250                                 "mods check (%s)\n",
2251                                 si->si_ridtxt, text, 0 );
2252                         goto done;
2253                 }
2254
2255                 if ( op->o_tag == LDAP_REQ_ADD ) {
2256                         Entry *e = entry_alloc();
2257                         op->ora_e = e;
2258                         op->ora_e->e_name = op->o_req_dn;
2259                         op->ora_e->e_nname = op->o_req_ndn;
2260                         freeReqDn = 0;
2261                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
2262                         if( rc != LDAP_SUCCESS ) {
2263                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
2264                                 "mods2entry (%s)\n",
2265                                         si->si_ridtxt, text, 0 );
2266                         } else {
2267                                 rc = op->o_bd->be_add( op, &rs );
2268                                 Debug( LDAP_DEBUG_SYNC,
2269                                         "syncrepl_message_to_op: %s be_add %s (%d)\n", 
2270                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2271                                 do_graduate = 0;
2272                         }
2273                         if ( e == op->ora_e )
2274                                 be_entry_release_w( op, op->ora_e );
2275                 } else {
2276                         OpExtraSync oes;
2277                         op->orm_modlist = modlist;
2278                         op->o_bd = si->si_wbe;
2279                         /* delta-mmr needs additional checks in syncrepl_op_modify */
2280                         if ( SLAP_MULTIMASTER( op->o_bd )) {
2281                                 oes.oe.oe_key = (void *)syncrepl_message_to_op;
2282                                 oes.oe_si = si;
2283                                 LDAP_SLIST_INSERT_HEAD( &op->o_extra, &oes.oe, oe_next );
2284                         }
2285                         rc = op->o_bd->be_modify( op, &rs );
2286                         if ( SLAP_MULTIMASTER( op->o_bd )) {
2287                                 LDAP_SLIST_REMOVE( &op->o_extra, &oes.oe, OpExtra, oe_next );
2288                         }
2289                         modlist = op->orm_modlist;
2290                         Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
2291                                 "syncrepl_message_to_op: %s be_modify %s (%d)\n", 
2292                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
2293                         op->o_bd = si->si_be;
2294                         do_graduate = 0;
2295                 }
2296                 break;
2297         case LDAP_REQ_MODRDN:
2298                 if ( BER_BVISNULL( &rdn ) ) goto done;
2299
2300                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ) ) {
2301                         goto done;
2302                 }
2303                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ) ) {
2304                         goto done;
2305                 }
2306                 if ( !BER_BVISNULL( &sup ) ) {
2307                         REWRITE_DN( si, sup, bv2, psup, nsup );
2308                         if ( rc )
2309                                 goto done;
2310                         op->orr_newSup = &psup;
2311                         op->orr_nnewSup = &nsup;
2312                 } else {
2313                         op->orr_newSup = NULL;
2314                         op->orr_nnewSup = NULL;
2315                 }
2316                 op->orr_newrdn = prdn;
2317                 op->orr_nnewrdn = nrdn;
2318                 op->orr_deleteoldrdn = deleteOldRdn;
2319                 op->orr_modlist = NULL;
2320                 if ( slap_modrdn2mods( op, &rs ) ) {
2321                         goto done;
2322                 }
2323
2324                 /* Append modlist for operational attrs */
2325                 {
2326                         Modifications *m;
2327
2328                         for ( m = op->orr_modlist; m->sml_next; m = m->sml_next )
2329                                 ;
2330                         m->sml_next = modlist;
2331                         modlist = NULL;
2332                 }
2333                 rc = op->o_bd->be_modrdn( op, &rs );
2334                 slap_mods_free( op->orr_modlist, 1 );
2335                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
2336                         "syncrepl_message_to_op: %s be_modrdn %s (%d)\n", 
2337                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2338                 do_graduate = 0;
2339                 break;
2340         case LDAP_REQ_DELETE:
2341                 rc = op->o_bd->be_delete( op, &rs );
2342                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
2343                         "syncrepl_message_to_op: %s be_delete %s (%d)\n", 
2344                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2345                 do_graduate = 0;
2346                 break;
2347         }
2348 done:
2349         if ( do_graduate )
2350                 slap_graduate_commit_csn( op );
2351         op->o_bd = si->si_be;
2352         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2353         BER_BVZERO( &op->o_csn );
2354         if ( modlist ) {
2355                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
2356         }
2357         if ( !BER_BVISNULL( &rdn ) ) {
2358                 if ( !BER_BVISNULL( &nsup ) ) {
2359                         ch_free( nsup.bv_val );
2360                 }
2361                 if ( !BER_BVISNULL( &psup ) ) {
2362                         ch_free( psup.bv_val );
2363                 }
2364                 if ( !BER_BVISNULL( &nrdn ) ) {
2365                         ch_free( nrdn.bv_val );
2366                 }
2367                 if ( !BER_BVISNULL( &prdn ) ) {
2368                         ch_free( prdn.bv_val );
2369                 }
2370         }
2371         if ( freeReqDn ) {
2372                 ch_free( op->o_req_ndn.bv_val );
2373                 ch_free( op->o_req_dn.bv_val );
2374         }
2375         ber_free( ber, 0 );
2376         return rc;
2377 }
2378
2379 static int
2380 syncrepl_message_to_entry(
2381         syncinfo_t      *si,
2382         Operation       *op,
2383         LDAPMessage     *msg,
2384         Modifications   **modlist,
2385         Entry                   **entry,
2386         int             syncstate
2387 )
2388 {
2389         Entry           *e = NULL;
2390         BerElement      *ber = NULL;
2391         Modifications   tmp;
2392         Modifications   *mod;
2393         Modifications   **modtail = modlist;
2394
2395         const char      *text;
2396         char txtbuf[SLAP_TEXT_BUFLEN];
2397         size_t textlen = sizeof txtbuf;
2398
2399         struct berval   bdn = BER_BVNULL, dn, ndn, bv2;
2400         int             rc, is_ctx;
2401
2402         *modlist = NULL;
2403
2404         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
2405                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s "
2406                         "Message type should be entry (%d)",
2407                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
2408                 return -1;
2409         }
2410
2411         op->o_tag = LDAP_REQ_ADD;
2412
2413         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
2414         if ( rc != LDAP_SUCCESS ) {
2415                 Debug( LDAP_DEBUG_ANY,
2416                         "syncrepl_message_to_entry: %s dn get failed (%d)",
2417                         si->si_ridtxt, rc, 0 );
2418                 return rc;
2419         }
2420
2421         if ( BER_BVISEMPTY( &bdn ) && !BER_BVISEMPTY( &op->o_bd->be_nsuffix[0] ) ) {
2422                 Debug( LDAP_DEBUG_ANY,
2423                         "syncrepl_message_to_entry: %s got empty dn",
2424                         si->si_ridtxt, 0, 0 );
2425                 return LDAP_OTHER;
2426         }
2427
2428         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
2429                 /* NOTE: this could be done even before decoding the DN,
2430                  * although encoding errors wouldn't be detected */
2431                 rc = LDAP_SUCCESS;
2432                 goto done;
2433         }
2434
2435         if ( entry == NULL ) {
2436                 return -1;
2437         }
2438
2439         REWRITE_DN( si, bdn, bv2, dn, ndn );
2440         if ( rc != LDAP_SUCCESS ) {
2441                 /* One of the things that could happen is that the schema
2442                  * is not lined-up; this could result in unknown attributes.
2443                  * A value non conformant to the syntax should be unlikely,
2444                  * except when replicating between different versions
2445                  * of the software, or when syntax validation bugs are fixed
2446                  */
2447                 Debug( LDAP_DEBUG_ANY,
2448                         "syncrepl_message_to_entry: "
2449                         "%s dn \"%s\" normalization failed (%d)",
2450                         si->si_ridtxt, bdn.bv_val, rc );
2451                 return rc;
2452         }
2453
2454         ber_dupbv( &op->o_req_dn, &dn );
2455         ber_dupbv( &op->o_req_ndn, &ndn );
2456         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
2457         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
2458
2459         is_ctx = dn_match( &op->o_req_ndn, &op->o_bd->be_nsuffix[0] );
2460
2461         e = entry_alloc();
2462         e->e_name = op->o_req_dn;
2463         e->e_nname = op->o_req_ndn;
2464
2465         while ( ber_remaining( ber ) ) {
2466                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
2467                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
2468                 {
2469                         break;
2470                 }
2471
2472                 /* Drop all updates to the contextCSN of the context entry
2473                  * (ITS#4622, etc.)
2474                  */
2475                 if ( is_ctx && !strcasecmp( tmp.sml_type.bv_val,
2476                         slap_schema.si_ad_contextCSN->ad_cname.bv_val )) {
2477                         ber_bvarray_free( tmp.sml_values );
2478                         continue;
2479                 }
2480
2481                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ) );
2482
2483                 mod->sml_op = LDAP_MOD_REPLACE;
2484                 mod->sml_flags = 0;
2485                 mod->sml_next = NULL;
2486                 mod->sml_desc = NULL;
2487                 mod->sml_type = tmp.sml_type;
2488                 mod->sml_values = tmp.sml_values;
2489                 mod->sml_nvalues = NULL;
2490                 mod->sml_numvals = 0;   /* slap_mods_check will set this */
2491
2492 #ifdef ENABLE_REWRITE
2493                 if (si->si_rewrite) {
2494                         AttributeDescription *ad = NULL;
2495                         slap_bv2ad( &tmp.sml_type, &ad, &text );
2496                         if ( ad ) {
2497                                 mod->sml_desc = ad;
2498                                 mod->sml_type = ad->ad_cname;
2499                                 if ( ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName ) {
2500                                         int i;
2501                                         for ( i = 0; tmp.sml_values[i].bv_val; i++ ) {
2502                                                 syncrepl_rewrite_dn( si, &tmp.sml_values[i], &bv2);
2503                                                 if ( !BER_BVISNULL( &bv2 )) {
2504                                                         ber_memfree( tmp.sml_values[i].bv_val );
2505                                                         tmp.sml_values[i] = bv2;
2506                                                 }
2507                                         }
2508                                 }
2509                         }
2510                 }
2511 #endif
2512                 *modtail = mod;
2513                 modtail = &mod->sml_next;
2514         }
2515
2516         if ( *modlist == NULL ) {
2517                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s no attributes\n",
2518                         si->si_ridtxt, 0, 0 );
2519                 rc = -1;
2520                 goto done;
2521         }
2522
2523         rc = slap_mods_check( op, *modlist, &text, txtbuf, textlen, NULL );
2524
2525         if ( rc != LDAP_SUCCESS ) {
2526                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods check (%s)\n",
2527                         si->si_ridtxt, text, 0 );
2528                 goto done;
2529         }
2530
2531         /* Strip out dynamically generated attrs */
2532         for ( modtail = modlist; *modtail ; ) {
2533                 mod = *modtail;
2534                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
2535                         *modtail = mod->sml_next;
2536                         slap_mod_free( &mod->sml_mod, 0 );
2537                         ch_free( mod );
2538                 } else {
2539                         modtail = &mod->sml_next;
2540                 }
2541         }
2542
2543         /* Strip out attrs in exattrs list */
2544         for ( modtail = modlist; *modtail ; ) {
2545                 mod = *modtail;
2546                 if ( ldap_charray_inlist( si->si_exattrs,
2547                         mod->sml_desc->ad_type->sat_cname.bv_val ) )
2548                 {
2549                         *modtail = mod->sml_next;
2550                         slap_mod_free( &mod->sml_mod, 0 );
2551                         ch_free( mod );
2552                 } else {
2553                         modtail = &mod->sml_next;
2554                 }
2555         }
2556
2557         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
2558         if( rc != LDAP_SUCCESS ) {
2559                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods2entry (%s)\n",
2560                         si->si_ridtxt, text, 0 );
2561         }
2562
2563 done:
2564         ber_free( ber, 0 );
2565         if ( rc != LDAP_SUCCESS ) {
2566                 if ( e ) {
2567                         entry_free( e );
2568                         e = NULL;
2569                 }
2570         }
2571         if ( entry )
2572                 *entry = e;
2573
2574         return rc;
2575 }
2576
2577 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
2578
2579 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
2580  * entry if a previous refresh was interrupted before sending us a new
2581  * context state. We try to compare the new entry to the existing entry
2582  * and ignore the new entry if they are the same.
2583  *
2584  * Also, we may get an update where the entryDN has changed, due to
2585  * a ModDn on the provider. We detect this as well, so we can issue
2586  * the corresponding operation locally.
2587  *
2588  * In the case of a modify, we get a list of all the attributes
2589  * in the original entry. Rather than deleting the entry and re-adding it,
2590  * we issue a Modify request that deletes all the attributes and adds all
2591  * the new ones. This avoids the issue of trying to delete/add a non-leaf
2592  * entry.
2593  *
2594  * We otherwise distinguish ModDN from Modify; in the case of
2595  * a ModDN we just use the CSN, modifyTimestamp and modifiersName
2596  * operational attributes from the entry, and do a regular ModDN.
2597  */
2598 typedef struct dninfo {
2599         Entry *new_entry;
2600         struct berval dn;
2601         struct berval ndn;
2602         struct berval nnewSup;
2603         int renamed;    /* Was an existing entry renamed? */
2604         int delOldRDN;  /* Was old RDN deleted? */
2605         Modifications **modlist;        /* the modlist we received */
2606         Modifications *mods;    /* the modlist we compared */
2607         Attribute *oldNattr;    /* old naming attr */
2608         AttributeDescription *oldDesc;  /* for renames */
2609         AttributeDescription *newDesc;  /* for renames */
2610 } dninfo;
2611
2612 /* return 1 if inserted, 0 otherwise */
2613 static int
2614 avl_presentlist_insert(
2615         syncinfo_t* si,
2616         struct berval *syncUUID )
2617 {
2618         struct berval *syncuuid_bv = ch_malloc( sizeof( struct berval ) + syncUUID->bv_len + 1 );
2619
2620         syncuuid_bv->bv_len = syncUUID->bv_len;
2621         syncuuid_bv->bv_val = (char *)&syncuuid_bv[1];
2622         AC_MEMCPY( syncuuid_bv->bv_val, syncUUID->bv_val, syncUUID->bv_len );
2623         syncuuid_bv->bv_val[ syncuuid_bv->bv_len ] = '\0';
2624
2625         if ( avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
2626                 syncuuid_cmp, avl_dup_error ) )
2627         {
2628                 ch_free( syncuuid_bv );
2629                 return 0;
2630         }
2631
2632         return 1;
2633 }
2634
2635 static int
2636 syncrepl_entry(
2637         syncinfo_t* si,
2638         Operation *op,
2639         Entry* entry,
2640         Modifications** modlist,
2641         int syncstate,
2642         struct berval* syncUUID,
2643         struct berval* syncCSN )
2644 {
2645         Backend *be = op->o_bd;
2646         slap_callback   cb = { NULL, NULL, NULL, NULL };
2647         int syncuuid_inserted = 0;
2648         struct berval   syncUUID_strrep = BER_BVNULL;
2649
2650         SlapReply       rs_search = {REP_RESULT};
2651         Filter f = {0};
2652         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2653         int rc = LDAP_SUCCESS;
2654
2655         struct berval pdn = BER_BVNULL;
2656         dninfo dni = {0};
2657         int     retry = 1;
2658         int     freecsn = 1;
2659
2660         Debug( LDAP_DEBUG_SYNC,
2661                 "syncrepl_entry: %s LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_%s)\n",
2662                 si->si_ridtxt, syncrepl_state2str( syncstate ), 0 );
2663
2664         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ) ) {
2665                 if ( !si->si_refreshPresent && !si->si_refreshDone ) {
2666                         syncuuid_inserted = avl_presentlist_insert( si, syncUUID );
2667                 }
2668         }
2669
2670         if ( syncstate == LDAP_SYNC_PRESENT ) {
2671                 return 0;
2672         } else if ( syncstate != LDAP_SYNC_DELETE ) {
2673                 if ( entry == NULL ) {
2674                         return 0;
2675                 }
2676         }
2677
2678         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
2679         if ( syncstate != LDAP_SYNC_DELETE ) {
2680                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
2681
2682                 if ( a == NULL ) {
2683                         /* add if missing */
2684                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
2685                                 &syncUUID_strrep, syncUUID );
2686
2687                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
2688                         /* replace only if necessary */
2689                         if ( a->a_nvals != a->a_vals ) {
2690                                 ber_memfree( a->a_nvals[0].bv_val );
2691                                 ber_dupbv( &a->a_nvals[0], syncUUID );
2692                         }
2693                         ber_memfree( a->a_vals[0].bv_val );
2694                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
2695                 }
2696         }
2697
2698         f.f_choice = LDAP_FILTER_EQUALITY;
2699         f.f_ava = &ava;
2700         ava.aa_desc = slap_schema.si_ad_entryUUID;
2701         ava.aa_value = *syncUUID;
2702
2703         if ( syncuuid_inserted ) {
2704                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s inserted UUID %s\n",
2705                         si->si_ridtxt, syncUUID_strrep.bv_val, 0 );
2706         }
2707         op->ors_filter = &f;
2708
2709         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
2710         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
2711                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
2712         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
2713         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
2714                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
2715         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
2716         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
2717
2718         op->o_tag = LDAP_REQ_SEARCH;
2719         op->ors_scope = LDAP_SCOPE_SUBTREE;
2720         op->ors_deref = LDAP_DEREF_NEVER;
2721
2722         /* get the entry for this UUID */
2723 #ifdef ENABLE_REWRITE
2724         if ( si->si_rewrite ) {
2725                 op->o_req_dn = si->si_suffixm;
2726                 op->o_req_ndn = si->si_suffixm;
2727         } else
2728 #endif
2729         {
2730                 op->o_req_dn = si->si_base;
2731                 op->o_req_ndn = si->si_base;
2732         }
2733
2734         op->o_time = slap_get_time();
2735         op->ors_tlimit = SLAP_NO_LIMIT;
2736         op->ors_slimit = 1;
2737         op->ors_limit = NULL;
2738
2739         op->ors_attrs = slap_anlist_all_attributes;
2740         op->ors_attrsonly = 0;
2741
2742         /* set callback function */
2743         op->o_callback = &cb;
2744         cb.sc_response = dn_callback;
2745         cb.sc_private = &dni;
2746         dni.new_entry = entry;
2747         dni.modlist = modlist;
2748
2749         rc = be->be_search( op, &rs_search );
2750         Debug( LDAP_DEBUG_SYNC,
2751                         "syncrepl_entry: %s be_search (%d)\n", 
2752                         si->si_ridtxt, rc, 0 );
2753
2754         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
2755                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2756         }
2757
2758         cb.sc_response = null_callback;
2759         cb.sc_private = si;
2760
2761         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
2762                 Debug( LDAP_DEBUG_SYNC,
2763                                 "syncrepl_entry: %s %s\n",
2764                                 si->si_ridtxt, entry->e_name.bv_val, 0 );
2765         } else {
2766                 Debug( LDAP_DEBUG_SYNC,
2767                                 "syncrepl_entry: %s %s\n",
2768                                 si->si_ridtxt, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
2769         }
2770
2771         assert( BER_BVISNULL( &op->o_csn ) );
2772         if ( syncCSN ) {
2773                 slap_queue_csn( op, syncCSN );
2774         }
2775
2776         slap_op_time( &op->o_time, &op->o_tincr );
2777         switch ( syncstate ) {
2778         case LDAP_SYNC_ADD:
2779         case LDAP_SYNC_MODIFY:
2780                 if ( BER_BVISNULL( &op->o_csn ))
2781                 {
2782
2783                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
2784                         if ( a ) {
2785                                 /* FIXME: op->o_csn is assumed to be
2786                                  * on the thread's slab; this needs
2787                                  * to be cleared ASAP.
2788                                  * What happens if already present?
2789                                  */
2790                                 assert( BER_BVISNULL( &op->o_csn ) );
2791                                 op->o_csn = a->a_vals[0];
2792                                 freecsn = 0;
2793                         }
2794                 }
2795 retry_add:;
2796                 if ( BER_BVISNULL( &dni.dn ) ) {
2797                         SlapReply       rs_add = {REP_RESULT};
2798
2799                         op->o_req_dn = entry->e_name;
2800                         op->o_req_ndn = entry->e_nname;
2801                         op->o_tag = LDAP_REQ_ADD;
2802                         op->ora_e = entry;
2803                         op->o_bd = si->si_wbe;
2804
2805                         rc = op->o_bd->be_add( op, &rs_add );
2806                         Debug( LDAP_DEBUG_SYNC,
2807                                         "syncrepl_entry: %s be_add %s (%d)\n", 
2808                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2809                         switch ( rs_add.sr_err ) {
2810                         case LDAP_SUCCESS:
2811                                 if ( op->ora_e == entry ) {
2812                                         be_entry_release_w( op, entry );
2813                                 }
2814                                 entry = NULL;
2815                                 break;
2816
2817                         case LDAP_REFERRAL:
2818                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
2819                          * only if the suffix entry is not present */
2820                         case LDAP_NO_SUCH_OBJECT:
2821                                 rc = syncrepl_add_glue( op, entry );
2822                                 entry = NULL;
2823                                 break;
2824
2825                         /* if an entry was added via syncrepl_add_glue(),
2826                          * it likely has no entryUUID, so the previous
2827                          * be_search() doesn't find it.  In this case,
2828                          * give syncrepl a chance to modify it. Also
2829                          * allow for entries that were recreated with the
2830                          * same DN but a different entryUUID.
2831                          */
2832                         case LDAP_ALREADY_EXISTS:
2833                                 if ( retry ) {
2834                                         Operation       op2 = *op;
2835                                         SlapReply       rs2 = { REP_RESULT };
2836                                         slap_callback   cb2 = { 0 };
2837
2838                                         op2.o_bd = be;
2839                                         op2.o_tag = LDAP_REQ_SEARCH;
2840                                         op2.o_req_dn = entry->e_name;
2841                                         op2.o_req_ndn = entry->e_nname;
2842                                         op2.ors_scope = LDAP_SCOPE_BASE;
2843                                         op2.ors_deref = LDAP_DEREF_NEVER;
2844                                         op2.ors_attrs = slap_anlist_all_attributes;
2845                                         op2.ors_attrsonly = 0;
2846                                         op2.ors_limit = NULL;
2847                                         op2.ors_slimit = 1;
2848                                         op2.ors_tlimit = SLAP_NO_LIMIT;
2849
2850                                         f.f_choice = LDAP_FILTER_PRESENT;
2851                                         f.f_desc = slap_schema.si_ad_objectClass;
2852                                         op2.ors_filter = &f;
2853                                         op2.ors_filterstr = generic_filterstr;
2854
2855                                         op2.o_callback = &cb2;
2856                                         cb2.sc_response = dn_callback;
2857                                         cb2.sc_private = &dni;
2858
2859                                         rc = be->be_search( &op2, &rs2 );
2860                                         if ( rc ) goto done;
2861
2862                                         retry = 0;
2863                                         slap_op_time( &op->o_time, &op->o_tincr );
2864                                         goto retry_add;
2865                                 }
2866                                 /* FALLTHRU */
2867
2868                         default:
2869                                 Debug( LDAP_DEBUG_ANY,
2870                                         "syncrepl_entry: %s be_add %s failed (%d)\n",
2871                                         si->si_ridtxt, op->o_req_dn.bv_val, rs_add.sr_err );
2872                                 break;
2873                         }
2874                         syncCSN = NULL;
2875                         op->o_bd = be;
2876                         goto done;
2877                 }
2878                 /* FALLTHRU */
2879                 op->o_req_dn = dni.dn;
2880                 op->o_req_ndn = dni.ndn;
2881                 if ( dni.renamed ) {
2882                         struct berval noldp, newp;
2883                         Modifications *mod, **modtail, **ml, *m2;
2884                         int i, got_replace = 0, just_rename = 0;
2885                         SlapReply rs_modify = {REP_RESULT};
2886
2887                         op->o_tag = LDAP_REQ_MODRDN;
2888                         dnRdn( &entry->e_name, &op->orr_newrdn );
2889                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
2890
2891                         if ( !BER_BVISNULL( &dni.nnewSup )) {
2892                                 dnParent( &entry->e_name, &newp );
2893                                 op->orr_newSup = &newp;
2894                                 op->orr_nnewSup = &dni.nnewSup;
2895                         } else {
2896                                 op->orr_newSup = NULL;
2897                                 op->orr_nnewSup = NULL;
2898                         }
2899                         op->orr_deleteoldrdn = dni.delOldRDN;
2900                         op->orr_modlist = NULL;
2901                         if ( ( rc = slap_modrdn2mods( op, &rs_modify ) ) ) {
2902                                 goto done;
2903                         }
2904
2905                         /* Drop the RDN-related mods from this op, because their
2906                          * equivalents were just setup by slap_modrdn2mods.
2907                          *
2908                          * If delOldRDN is TRUE then we should see a delete modop
2909                          * for oldDesc. We might see a replace instead.
2910                          *  delete with no values: therefore newDesc != oldDesc.
2911                          *   if oldNattr had only one value, then Drop this op.
2912                          *  delete with 1 value: can only be the oldRDN value. Drop op.
2913                          *  delete with N values: Drop oldRDN value, keep remainder.
2914                          *  replace with 1 value: if oldNattr had only one value and
2915                          *     newDesc == oldDesc, Drop this op.
2916                          * Any other cases must be left intact.
2917                          *
2918                          * We should also see an add modop for newDesc. (But not if
2919                          * we got a replace modop due to delOldRDN.) If it has
2920                          * multiple values, we'll have to drop the new RDN value.
2921                          */
2922                         modtail = &op->orr_modlist;
2923                         if ( dni.delOldRDN ) {
2924                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2925                                         if ( (*ml)->sml_desc == dni.oldDesc ) {
2926                                                 mod = *ml;
2927                                                 if ( mod->sml_op == LDAP_MOD_REPLACE &&
2928                                                         dni.oldDesc != dni.newDesc ) {
2929                                                         /* This Replace is due to other Mods.
2930                                                          * Just let it ride.
2931                                                          */
2932                                                         continue;
2933                                                 }
2934                                                 if ( mod->sml_numvals <= 1 &&
2935                                                         dni.oldNattr->a_numvals == 1 &&
2936                                                         ( mod->sml_op == LDAP_MOD_DELETE ||
2937                                                           mod->sml_op == LDAP_MOD_REPLACE )) {
2938                                                         if ( mod->sml_op == LDAP_MOD_REPLACE )
2939                                                                 got_replace = 1;
2940                                                         /* Drop this op */
2941                                                         *ml = mod->sml_next;
2942                                                         mod->sml_next = NULL;
2943                                                         slap_mods_free( mod, 1 );
2944                                                         break;
2945                                                 }
2946                                                 if ( mod->sml_op != LDAP_MOD_DELETE || mod->sml_numvals == 0 )
2947                                                         continue;
2948                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2949                                                         if ( m2->sml_desc == dni.oldDesc &&
2950                                                                 m2->sml_op == LDAP_MOD_DELETE ) break;
2951                                                 }
2952                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
2953                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2954                                                                 mod->sml_numvals--;
2955                                                                 ch_free( mod->sml_values[i].bv_val );
2956                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2957                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2958                                                                 if ( mod->sml_nvalues ) {
2959                                                                         ch_free( mod->sml_nvalues[i].bv_val );
2960                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
2961                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
2962                                                                 }
2963                                                                 break;
2964                                                         }
2965                                                 }
2966                                                 if ( !mod->sml_numvals ) {
2967                                                         /* Drop this op */
2968                                                         *ml = mod->sml_next;
2969                                                         mod->sml_next = NULL;
2970                                                         slap_mods_free( mod, 1 );
2971                                                 }
2972                                                 break;
2973                                         }
2974                                 }
2975                         }
2976                         if ( !got_replace ) {
2977                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2978                                         if ( (*ml)->sml_desc == dni.newDesc ) {
2979                                                 mod = *ml;
2980                                                 if ( mod->sml_op != LDAP_MOD_ADD )
2981                                                         continue;
2982                                                 if ( mod->sml_numvals == 1 ) {
2983                                                         /* Drop this op */
2984                                                         *ml = mod->sml_next;
2985                                                         mod->sml_next = NULL;
2986                                                         slap_mods_free( mod, 1 );
2987                                                         break;
2988                                                 }
2989                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2990                                                         if ( m2->sml_desc == dni.oldDesc &&
2991                                                                 m2->sml_op == SLAP_MOD_SOFTADD ) break;
2992                                                 }
2993                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
2994                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2995                                                                 mod->sml_numvals--;
2996                                                                 ch_free( mod->sml_values[i].bv_val );
2997                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2998                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2999                                                                 if ( mod->sml_nvalues ) {
3000                                                                         ch_free( mod->sml_nvalues[i].bv_val );
3001                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
3002                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
3003                                                                 }
3004                                                                 break;
3005                                                         }
3006                                                 }
3007                                                 break;
3008                                         }
3009                                 }
3010                         }
3011
3012                         /* RDNs must be NUL-terminated for back-ldap */
3013                         noldp = op->orr_newrdn;
3014                         ber_dupbv_x( &op->orr_newrdn, &noldp, op->o_tmpmemctx );
3015                         noldp = op->orr_nnewrdn;
3016                         ber_dupbv_x( &op->orr_nnewrdn, &noldp, op->o_tmpmemctx );
3017
3018                         /* Setup opattrs too */
3019                         {
3020                                 static AttributeDescription *nullattr = NULL;
3021                                 static AttributeDescription **const opattrs[] = {
3022                                         &slap_schema.si_ad_entryCSN,
3023                                         &slap_schema.si_ad_modifiersName,
3024                                         &slap_schema.si_ad_modifyTimestamp,
3025                                         &nullattr
3026                                 };
3027                                 AttributeDescription *opattr;
3028                                 int i;
3029
3030                                 modtail = &m2;
3031                                 /* pull mod off incoming modlist */
3032                                 for ( i = 0; (opattr = *opattrs[i]) != NULL; i++ ) {
3033                                         for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next )
3034                                         {
3035                                                 if ( (*ml)->sml_desc == opattr ) {
3036                                                         mod = *ml;
3037                                                         *ml = mod->sml_next;
3038                                                         mod->sml_next = NULL;
3039                                                         *modtail = mod;
3040                                                         modtail = &mod->sml_next;
3041                                                         break;
3042                                                 }
3043                                         }
3044                                 }
3045                                 /* If there are still Modifications left, put the opattrs
3046                                  * back, and let be_modify run. Otherwise, append the opattrs
3047                                  * to the orr_modlist.
3048                                  */
3049                                 if ( dni.mods ) {
3050                                         mod = dni.mods;
3051                                         /* don't set a CSN for the rename op */
3052                                         if ( syncCSN )
3053                                                 slap_graduate_commit_csn( op );
3054                                 } else {
3055                                         mod = op->orr_modlist;
3056                                         just_rename = 1;
3057                                 }
3058                                 for ( ; mod->sml_next; mod=mod->sml_next );
3059                                 mod->sml_next = m2;
3060                         }
3061                         op->o_bd = si->si_wbe;
3062 retry_modrdn:;
3063                         rs_reinit( &rs_modify, REP_RESULT );
3064                         rc = op->o_bd->be_modrdn( op, &rs_modify );
3065
3066                         /* NOTE: noSuchObject should result because the new superior
3067                          * has not been added yet (ITS#6472) */
3068                         if ( rc == LDAP_NO_SUCH_OBJECT && !BER_BVISNULL( op->orr_nnewSup )) {
3069                                 Operation op2 = *op;
3070                                 rc = syncrepl_add_glue_ancestors( &op2, entry );
3071                                 if ( rc == LDAP_SUCCESS ) {
3072                                         goto retry_modrdn;
3073                                 }
3074                         }
3075                 
3076                         op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
3077                         op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
3078
3079                         slap_mods_free( op->orr_modlist, 1 );
3080                         Debug( LDAP_DEBUG_SYNC,
3081                                         "syncrepl_entry: %s be_modrdn %s (%d)\n", 
3082                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
3083                         op->o_bd = be;
3084                         /* Renamed entries may still have other mods so just fallthru */
3085                         op->o_req_dn = entry->e_name;
3086                         op->o_req_ndn = entry->e_nname;
3087                         /* Use CSN on the modify */
3088                         if ( just_rename )
3089                                 syncCSN = NULL;
3090                         else if ( syncCSN )
3091                                 slap_queue_csn( op, syncCSN );
3092                 }
3093                 if ( dni.mods ) {
3094                         SlapReply rs_modify = {REP_RESULT};
3095
3096                         op->o_tag = LDAP_REQ_MODIFY;
3097                         op->orm_modlist = dni.mods;
3098                         op->orm_no_opattrs = 1;
3099                         op->o_bd = si->si_wbe;
3100
3101                         rc = op->o_bd->be_modify( op, &rs_modify );
3102                         slap_mods_free( op->orm_modlist, 1 );
3103                         op->orm_no_opattrs = 0;
3104                         Debug( LDAP_DEBUG_SYNC,
3105                                         "syncrepl_entry: %s be_modify %s (%d)\n", 
3106                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
3107                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
3108                                 Debug( LDAP_DEBUG_ANY,
3109                                         "syncrepl_entry: %s be_modify failed (%d)\n",
3110                                         si->si_ridtxt, rs_modify.sr_err, 0 );
3111                         }
3112                         syncCSN = NULL;
3113                         op->o_bd = be;
3114                 } else if ( !dni.renamed ) {
3115                         Debug( LDAP_DEBUG_SYNC,
3116                                         "syncrepl_entry: %s entry unchanged, ignored (%s)\n", 
3117                                         si->si_ridtxt, op->o_req_dn.bv_val, 0 );
3118                         if ( syncCSN ) {
3119                                 slap_graduate_commit_csn( op );
3120                                 syncCSN = NULL;
3121                         }
3122                 }
3123                 goto done;
3124         case LDAP_SYNC_DELETE :
3125                 if ( !BER_BVISNULL( &dni.dn ) ) {
3126                         SlapReply       rs_delete = {REP_RESULT};
3127                         op->o_req_dn = dni.dn;
3128                         op->o_req_ndn = dni.ndn;
3129                         op->o_tag = LDAP_REQ_DELETE;
3130                         op->o_bd = si->si_wbe;
3131                         rc = op->o_bd->be_delete( op, &rs_delete );
3132                         Debug( LDAP_DEBUG_SYNC,
3133                                         "syncrepl_entry: %s be_delete %s (%d)\n", 
3134                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
3135
3136                         while ( rs_delete.sr_err == LDAP_SUCCESS
3137                                 && op->o_delete_glue_parent ) {
3138                                 op->o_delete_glue_parent = 0;
3139                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
3140                                         slap_callback cb = { NULL };
3141                                         cb.sc_response = slap_null_cb;
3142                                         dnParent( &op->o_req_ndn, &pdn );
3143                                         op->o_req_dn = pdn;
3144                                         op->o_req_ndn = pdn;
3145                                         op->o_callback = &cb;
3146                                         rs_reinit( &rs_delete, REP_RESULT );
3147                                         op->o_bd->be_delete( op, &rs_delete );
3148                                 } else {
3149                                         break;
3150                                 }
3151                         }
3152                         syncCSN = NULL;
3153                         op->o_bd = be;
3154                 }
3155                 goto done;
3156
3157         default :
3158                 Debug( LDAP_DEBUG_ANY,
3159                         "syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
3160                 goto done;
3161         }
3162
3163 done:
3164         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
3165                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
3166                 BER_BVZERO( &syncUUID_strrep );
3167         }
3168         if ( !BER_BVISNULL( &dni.ndn ) ) {
3169                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
3170         }
3171         if ( !BER_BVISNULL( &dni.dn ) ) {
3172                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
3173         }
3174         if ( entry ) {
3175                 entry_free( entry );
3176         }
3177         if ( syncCSN ) {
3178                 slap_graduate_commit_csn( op );
3179         }
3180         if ( !BER_BVISNULL( &op->o_csn ) && freecsn ) {
3181                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3182         }
3183         BER_BVZERO( &op->o_csn );
3184         return rc;
3185 }
3186
3187 static struct berval gcbva[] = {
3188         BER_BVC("top"),
3189         BER_BVC("glue"),
3190         BER_BVNULL
3191 };
3192
3193 #define NP_DELETE_ONE   2
3194
3195 static void
3196 syncrepl_del_nonpresent(
3197         Operation *op,
3198         syncinfo_t *si,
3199         BerVarray uuids,
3200         struct sync_cookie *sc,
3201         int m )
3202 {
3203         Backend* be = op->o_bd;
3204         slap_callback   cb = { NULL };
3205         struct nonpresent_entry *np_list, *np_prev;
3206         int rc;
3207         AttributeName   an[2];
3208
3209         struct berval pdn = BER_BVNULL;
3210         struct berval csn;
3211
3212 #ifdef ENABLE_REWRITE
3213         if ( si->si_rewrite ) {
3214                 op->o_req_dn = si->si_suffixm;
3215                 op->o_req_ndn = si->si_suffixm;
3216         } else
3217 #endif
3218         {
3219                 op->o_req_dn = si->si_base;
3220                 op->o_req_ndn = si->si_base;
3221         }
3222
3223         cb.sc_response = nonpresent_callback;
3224         cb.sc_private = si;
3225
3226         op->o_callback = &cb;
3227         op->o_tag = LDAP_REQ_SEARCH;
3228         op->ors_scope = si->si_scope;
3229         op->ors_deref = LDAP_DEREF_NEVER;
3230         op->o_time = slap_get_time();
3231         op->ors_tlimit = SLAP_NO_LIMIT;
3232
3233
3234         if ( uuids ) {
3235                 Filter uf;
3236                 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
3237                 int i;
3238
3239                 op->ors_attrsonly = 1;
3240                 op->ors_attrs = slap_anlist_no_attrs;
3241                 op->ors_limit = NULL;
3242                 op->ors_filter = &uf;
3243
3244                 uf.f_ava = &eq;
3245                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
3246                 uf.f_next = NULL;
3247                 uf.f_choice = LDAP_FILTER_EQUALITY;
3248                 si->si_refreshDelete |= NP_DELETE_ONE;
3249
3250                 for (i=0; uuids[i].bv_val; i++) {
3251                         SlapReply rs_search = {REP_RESULT};
3252
3253                         op->ors_slimit = 1;
3254                         uf.f_av_value = uuids[i];
3255                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
3256                         rc = be->be_search( op, &rs_search );
3257                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
3258                 }
3259                 si->si_refreshDelete ^= NP_DELETE_ONE;
3260         } else {
3261                 Filter *cf, *of;
3262                 Filter mmf[2];
3263                 AttributeAssertion mmaa;
3264                 SlapReply rs_search = {REP_RESULT};
3265
3266                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
3267                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
3268                 an[0].an_desc = slap_schema.si_ad_entryUUID;
3269                 op->ors_attrs = an;
3270                 op->ors_slimit = SLAP_NO_LIMIT;
3271                 op->ors_tlimit = SLAP_NO_LIMIT;
3272                 op->ors_limit = NULL;
3273                 op->ors_attrsonly = 0;
3274                 op->ors_filter = filter_dup( si->si_filter, op->o_tmpmemctx );
3275                 /* In multimaster, updates can continue to arrive while
3276                  * we're searching. Limit the search result to entries
3277                  * older than our newest cookie CSN.
3278                  */
3279                 if ( SLAP_MULTIMASTER( op->o_bd )) {
3280                         Filter *f;
3281                         int i;
3282
3283                         f = mmf;
3284                         f->f_choice = LDAP_FILTER_AND;
3285                         f->f_next = op->ors_filter;
3286                         f->f_and = f+1;
3287                         of = f->f_and;
3288                         f = of;
3289                         f->f_choice = LDAP_FILTER_LE;
3290                         f->f_ava = &mmaa;
3291                         f->f_av_desc = slap_schema.si_ad_entryCSN;
3292                         f->f_next = NULL;
3293                         BER_BVZERO( &f->f_av_value );
3294                         for ( i=0; i<sc->numcsns; i++ ) {
3295                                 if ( ber_bvcmp( &sc->ctxcsn[i], &f->f_av_value ) > 0 )
3296                                         f->f_av_value = sc->ctxcsn[i];
3297                         }
3298                         of = op->ors_filter;
3299                         op->ors_filter = mmf;
3300                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
3301                 } else {
3302                         cf = NULL;
3303                         op->ors_filterstr = si->si_filterstr;
3304                 }
3305                 op->o_nocaching = 1;
3306
3307
3308                 rc = be->be_search( op, &rs_search );
3309                 if ( SLAP_MULTIMASTER( op->o_bd )) {
3310                         op->ors_filter = of;
3311                 }
3312                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter, 1 );
3313                 if ( op->ors_filterstr.bv_val != si->si_filterstr.bv_val ) {
3314                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
3315                 }
3316
3317         }
3318
3319         op->o_nocaching = 0;
3320
3321         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
3322
3323                 if ( sc->ctxcsn && !BER_BVISNULL( &sc->ctxcsn[m] ) ) {
3324                         csn = sc->ctxcsn[m];
3325                 } else {
3326                         csn = si->si_syncCookie.ctxcsn[0];
3327                 }
3328
3329                 op->o_bd = si->si_wbe;
3330                 slap_queue_csn( op, &csn );
3331
3332                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
3333                 while ( np_list != NULL ) {
3334                         SlapReply rs_delete = {REP_RESULT};
3335
3336                         LDAP_LIST_REMOVE( np_list, npe_link );
3337                         np_prev = np_list;
3338                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
3339                         op->o_tag = LDAP_REQ_DELETE;
3340                         op->o_callback = &cb;
3341                         cb.sc_response = null_callback;
3342                         cb.sc_private = si;
3343                         op->o_req_dn = *np_prev->npe_name;
3344                         op->o_req_ndn = *np_prev->npe_nname;
3345                         rc = op->o_bd->be_delete( op, &rs_delete );
3346                         Debug( LDAP_DEBUG_SYNC,
3347                                 "syncrepl_del_nonpresent: %s be_delete %s (%d)\n", 
3348                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
3349
3350                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
3351                                 SlapReply rs_modify = {REP_RESULT};
3352                                 Modifications mod1, mod2;
3353                                 mod1.sml_op = LDAP_MOD_REPLACE;
3354                                 mod1.sml_flags = 0;
3355                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
3356                                 mod1.sml_type = mod1.sml_desc->ad_cname;
3357                                 mod1.sml_numvals = 2;
3358                                 mod1.sml_values = &gcbva[0];
3359                                 mod1.sml_nvalues = NULL;
3360                                 mod1.sml_next = &mod2;
3361
3362                                 mod2.sml_op = LDAP_MOD_REPLACE;
3363                                 mod2.sml_flags = 0;
3364                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
3365                                 mod2.sml_type = mod2.sml_desc->ad_cname;
3366                                 mod2.sml_numvals = 1;
3367                                 mod2.sml_values = &gcbva[1];
3368                                 mod2.sml_nvalues = NULL;
3369                                 mod2.sml_next = NULL;
3370
3371                                 op->o_tag = LDAP_REQ_MODIFY;
3372                                 op->orm_modlist = &mod1;
3373
3374                                 rc = op->o_bd->be_modify( op, &rs_modify );
3375                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
3376                         }
3377
3378                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
3379                                         op->o_delete_glue_parent ) {
3380                                 op->o_delete_glue_parent = 0;
3381                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
3382                                         slap_callback cb = { NULL };
3383                                         cb.sc_response = slap_null_cb;
3384                                         dnParent( &op->o_req_ndn, &pdn );
3385                                         op->o_req_dn = pdn;
3386                                         op->o_req_ndn = pdn;
3387                                         op->o_callback = &cb;
3388                                         rs_reinit( &rs_delete, REP_RESULT );
3389                                         /* give it a root privil ? */
3390                                         op->o_bd->be_delete( op, &rs_delete );
3391                                 } else {
3392                                         break;
3393                                 }
3394                         }
3395
3396                         op->o_delete_glue_parent = 0;
3397
3398                         ber_bvfree( np_prev->npe_name );
3399                         ber_bvfree( np_prev->npe_nname );
3400                         ch_free( np_prev );
3401
3402                         if ( slapd_shutdown ) {
3403                                 break;
3404                         }
3405                 }
3406
3407                 slap_graduate_commit_csn( op );
3408                 op->o_bd = be;
3409
3410                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3411                 BER_BVZERO( &op->o_csn );
3412         }
3413
3414         return;
3415 }
3416
3417 static int
3418 syncrepl_add_glue_ancestors(
3419         Operation* op,
3420         Entry *e )
3421 {
3422         Backend *be = op->o_bd;
3423         slap_callback cb = { NULL };
3424         Attribute       *a;
3425         int     rc = LDAP_SUCCESS;
3426         int suffrdns;
3427         int i;
3428         struct berval dn = BER_BVNULL;
3429         struct berval ndn = BER_BVNULL;
3430         Entry   *glue;
3431         struct berval   ptr, nptr;
3432         char            *comma;
3433
3434         op->o_tag = LDAP_REQ_ADD;
3435         op->o_callback = &cb;
3436         cb.sc_response = null_callback;
3437         cb.sc_private = NULL;
3438
3439         dn = e->e_name;
3440         ndn = e->e_nname;
3441
3442         /* count RDNs in suffix */
3443         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
3444                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
3445                         comma++;
3446                         ptr.bv_len -= comma - ptr.bv_val;
3447                         ptr.bv_val = comma;
3448                         i++;
3449                 }
3450                 suffrdns = i;
3451         } else {
3452                 /* suffix is "" */
3453                 suffrdns = 0;
3454         }
3455
3456         /* Start with BE suffix */
3457         ptr = dn;
3458         for ( i = 0; i < suffrdns; i++ ) {
3459                 comma = ber_bvrchr( &ptr, ',' );
3460                 if ( comma != NULL ) {
3461                         ptr.bv_len = comma - ptr.bv_val;
3462                 } else {
3463                         ptr.bv_len = 0;
3464                         break;
3465                 }
3466         }
3467         
3468         if ( !BER_BVISEMPTY( &ptr ) ) {
3469                 dn.bv_len -= ptr.bv_len + 1;
3470                 dn.bv_val += ptr.bv_len + 1;
3471         }
3472
3473         /* the normalizedDNs are always the same length, no counting
3474          * required.
3475          */
3476         nptr = ndn;
3477         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
3478                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
3479                 ndn.bv_len = be->be_nsuffix[0].bv_len;
3480
3481                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
3482
3483         } else {
3484                 nptr.bv_len = 0;
3485         }
3486
3487         while ( ndn.bv_val > e->e_nname.bv_val ) {
3488                 SlapReply       rs_add = {REP_RESULT};
3489
3490                 glue = entry_alloc();
3491                 ber_dupbv( &glue->e_name, &dn );
3492                 ber_dupbv( &glue->e_nname, &ndn );
3493
3494                 a = attr_alloc( slap_schema.si_ad_objectClass );
3495
3496                 a->a_numvals = 2;
3497                 a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
3498                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
3499                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
3500                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
3501
3502                 a->a_nvals = a->a_vals;
3503
3504                 a->a_next = glue->e_attrs;
3505                 glue->e_attrs = a;
3506
3507                 a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
3508
3509                 a->a_numvals = 1;
3510                 a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
3511                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
3512                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
3513
3514                 a->a_nvals = a->a_vals;
3515
3516                 a->a_next = glue->e_attrs;
3517                 glue->e_attrs = a;
3518
3519                 op->o_req_dn = glue->e_name;
3520                 op->o_req_ndn = glue->e_nname;
3521                 op->ora_e = glue;
3522                 rc = be->be_add ( op, &rs_add );
3523                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
3524                         if ( op->ora_e == glue )
3525                                 be_entry_release_w( op, glue );
3526                 } else {
3527                 /* incl. ALREADY EXIST */
3528                         entry_free( glue );
3529                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
3530                                 entry_free( e );
3531                                 return rc;
3532                         }
3533                 }
3534
3535                 /* Move to next child */
3536                 comma = ber_bvrchr( &ptr, ',' );
3537                 if ( comma == NULL ) {
3538                         break;
3539                 }
3540                 ptr.bv_len = comma - ptr.bv_val;
3541                 
3542                 dn.bv_val = ++comma;
3543                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
3544
3545                 comma = ber_bvrchr( &nptr, ',' );
3546                 assert( comma != NULL );
3547                 nptr.bv_len = comma - nptr.bv_val;
3548
3549                 ndn.bv_val = ++comma;
3550                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
3551         }
3552
3553         return rc;
3554 }
3555
3556 int
3557 syncrepl_add_glue(
3558         Operation* op,
3559         Entry *e )
3560 {
3561         slap_callback cb = { NULL };
3562         int     rc;
3563         Backend *be = op->o_bd;
3564         SlapReply       rs_add = {REP_RESULT};
3565
3566         rc = syncrepl_add_glue_ancestors( op, e );
3567         switch ( rc ) {
3568         case LDAP_SUCCESS:
3569         case LDAP_ALREADY_EXISTS:
3570                 break;
3571
3572         default:
3573                 return rc;
3574         }
3575
3576         op->o_tag = LDAP_REQ_ADD;
3577         op->o_callback = &cb;
3578         cb.sc_response = null_callback;
3579         cb.sc_private = NULL;
3580
3581         op->o_req_dn = e->e_name;
3582         op->o_req_ndn = e->e_nname;
3583         op->ora_e = e;
3584         rc = be->be_add ( op, &rs_add );
3585         if ( rs_add.sr_err == LDAP_SUCCESS ) {
3586                 if ( op->ora_e == e )
3587                         be_entry_release_w( op, e );
3588         } else {
3589                 entry_free( e );
3590         }
3591
3592         return rc;
3593 }
3594
3595 static int
3596 syncrepl_updateCookie(
3597         syncinfo_t *si,
3598         Operation *op,
3599         struct sync_cookie *syncCookie )
3600 {
3601         Backend *be = op->o_bd;
3602         Modifications mod;
3603         struct berval first = BER_BVNULL;
3604 #ifdef CHECK_CSN
3605         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
3606 #endif
3607
3608         int rc, i, j, changed = 0;
3609         ber_len_t len;
3610
3611         slap_callback cb = { NULL };
3612         SlapReply       rs_modify = {REP_RESULT};
3613
3614         mod.sml_op = LDAP_MOD_REPLACE;
3615         mod.sml_desc = slap_schema.si_ad_contextCSN;
3616         mod.sml_type = mod.sml_desc->ad_cname;
3617         mod.sml_flags = SLAP_MOD_INTERNAL;
3618         mod.sml_nvalues = NULL;
3619         mod.sml_next = NULL;
3620
3621         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
3622
3623 #ifdef CHECK_CSN
3624         for ( i=0; i<syncCookie->numcsns; i++ ) {
3625                 assert( !syn->ssyn_validate( syn, syncCookie->ctxcsn+i ));
3626         }
3627         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3628                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
3629         }
3630 #endif
3631
3632         /* clone the cookieState CSNs so we can Replace the whole thing */
3633         mod.sml_numvals = si->si_cookieState->cs_num;
3634         mod.sml_values = op->o_tmpalloc(( mod.sml_numvals+1 )*sizeof(struct berval), op->o_tmpmemctx );
3635         for ( i=0; i<mod.sml_numvals; i++ )
3636                 mod.sml_values[i] = si->si_cookieState->cs_vals[i];
3637         BER_BVZERO( &mod.sml_values[i] );
3638
3639         /* find any CSNs in the syncCookie that are newer than the cookieState */
3640         for ( i=0; i<syncCookie->numcsns; i++ ) {
3641                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
3642                         if ( syncCookie->sids[i] != si->si_cookieState->cs_sids[j] )
3643                                 continue;
3644                         len = syncCookie->ctxcsn[i].bv_len;
3645                         if ( len > si->si_cookieState->cs_vals[j].bv_len )
3646                                 len = si->si_cookieState->cs_vals[j].bv_len;
3647                         if ( memcmp( syncCookie->ctxcsn[i].bv_val,
3648                                 si->si_cookieState->cs_vals[j].bv_val, len ) > 0 ) {
3649                                 mod.sml_values[j] = syncCookie->ctxcsn[i];
3650                                 changed = 1;
3651                                 if ( BER_BVISNULL( &first ) ) {
3652                                         first = syncCookie->ctxcsn[i];
3653
3654                                 } else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
3655                                 {
3656                                         first = syncCookie->ctxcsn[i];
3657                                 }
3658                         }
3659                         break;
3660                 }
3661                 /* there was no match for this SID, it's a new CSN */
3662                 if ( j == si->si_cookieState->cs_num ) {
3663                         mod.sml_values = op->o_tmprealloc( mod.sml_values,
3664                                 ( mod.sml_numvals+2 )*sizeof(struct berval), op->o_tmpmemctx );
3665                         mod.sml_values[mod.sml_numvals++] = syncCookie->ctxcsn[i];
3666                         BER_BVZERO( &mod.sml_values[mod.sml_numvals] );
3667                         if ( BER_BVISNULL( &first ) ) {
3668                                 first = syncCookie->ctxcsn[i];
3669                         } else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
3670                         {
3671                                 first = syncCookie->ctxcsn[i];
3672                         }
3673                         changed = 1;
3674                 }
3675         }
3676         /* Should never happen, ITS#5065 */
3677         if ( BER_BVISNULL( &first ) || !changed ) {
3678                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3679                 op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
3680                 return 0;
3681         }
3682         op->o_bd = si->si_wbe;
3683         slap_queue_csn( op, &first );
3684
3685         op->o_tag = LDAP_REQ_MODIFY;
3686
3687         cb.sc_response = null_callback;
3688         cb.sc_private = si;
3689
3690         op->o_callback = &cb;
3691         op->o_req_dn = si->si_contextdn;
3692         op->o_req_ndn = si->si_contextdn;
3693
3694         /* update contextCSN */
3695         op->o_dont_replicate = 1;
3696
3697         op->orm_modlist = &mod;
3698         op->orm_no_opattrs = 1;
3699         rc = op->o_bd->be_modify( op, &rs_modify );
3700
3701         if ( rs_modify.sr_err == LDAP_NO_SUCH_OBJECT &&
3702                 SLAP_SYNC_SUBENTRY( op->o_bd )) {
3703                 const char      *text;
3704                 char txtbuf[SLAP_TEXT_BUFLEN];
3705                 size_t textlen = sizeof txtbuf;
3706                 Entry *e = slap_create_context_csn_entry( op->o_bd, NULL );
3707                 rs_reinit( &rs_modify, REP_RESULT );
3708                 rc = slap_mods2entry( &mod, &e, 0, 1, &text, txtbuf, textlen);
3709                 op->ora_e = e;
3710                 rc = op->o_bd->be_add( op, &rs_modify );
3711                 if ( e == op->ora_e )
3712                         be_entry_release_w( op, op->ora_e );
3713         }
3714
3715         op->orm_no_opattrs = 0;
3716         op->o_dont_replicate = 0;
3717
3718         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
3719                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
3720                 /* If we replaced any old values */
3721                 for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3722                         if ( mod.sml_values[i].bv_val != si->si_cookieState->cs_vals[i].bv_val )
3723                                         ber_bvreplace( &si->si_cookieState->cs_vals[i],
3724                                                 &mod.sml_values[i] );
3725                 }
3726                 /* Handle any added values */
3727                 if ( i < mod.sml_numvals ) {
3728                         si->si_cookieState->cs_num = mod.sml_numvals;
3729                         value_add( &si->si_cookieState->cs_vals, &mod.sml_values[i] );
3730                         free( si->si_cookieState->cs_sids );
3731                         si->si_cookieState->cs_sids = slap_parse_csn_sids(
3732                                 si->si_cookieState->cs_vals, si->si_cookieState->cs_num, NULL );
3733                 }
3734
3735                 /* Don't just dup the provider's cookie, recreate it */
3736                 si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
3737                 ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn, si->si_cookieState->cs_vals, NULL );
3738                 si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num * sizeof(int) );
3739                 for ( i=0; i<si->si_cookieState->cs_num; i++ )
3740                         si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
3741
3742                 si->si_cookieState->cs_age++;
3743                 si->si_cookieAge = si->si_cookieState->cs_age;
3744         } else {
3745                 Debug( LDAP_DEBUG_ANY,
3746                         "syncrepl_updateCookie: %s be_modify failed (%d)\n",
3747                         si->si_ridtxt, rs_modify.sr_err, 0 );
3748         }
3749         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3750
3751         op->o_bd = be;
3752         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3753         BER_BVZERO( &op->o_csn );
3754         if ( mod.sml_next ) slap_mods_free( mod.sml_next, 1 );
3755         op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
3756
3757 #ifdef CHECK_CSN
3758         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3759                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
3760         }
3761 #endif
3762
3763         return rc;
3764 }
3765
3766 /* Compare the attribute from the old entry to the one in the new
3767  * entry. The Modifications from the new entry will either be left
3768  * in place, or changed to an Add or Delete as needed.
3769  */
3770 static void
3771 attr_cmp( Operation *op, Attribute *old, Attribute *new,
3772         Modifications ***mret, Modifications ***mcur )
3773 {
3774         int i, j;
3775         Modifications *mod, **modtail;
3776
3777         modtail = *mret;
3778
3779         if ( old ) {
3780                 int n, o, nn, no;
3781                 struct berval **adds, **dels;
3782                 /* count old and new */
3783                 for ( o=0; old->a_vals[o].bv_val; o++ ) ;
3784                 for ( n=0; new->a_vals[n].bv_val; n++ ) ;
3785
3786                 /* there MUST be both old and new values */
3787                 assert( o != 0 );
3788                 assert( n != 0 );
3789                 j = 0;
3790
3791                 adds = op->o_tmpalloc( sizeof(struct berval *) * n, op->o_tmpmemctx );
3792                 dels = op->o_tmpalloc( sizeof(struct berval *) * o, op->o_tmpmemctx );
3793
3794                 for ( i=0; i<o; i++ ) dels[i] = &old->a_vals[i];
3795                 for ( i=0; i<n; i++ ) adds[i] = &new->a_vals[i];
3796
3797                 nn = n; no = o;
3798
3799                 for ( i=0; i<o; i++ ) {
3800                         for ( j=0; j<n; j++ ) {
3801                                 if ( !adds[j] )
3802                                         continue;
3803                                 if ( bvmatch( dels[i], adds[j] ) ) {
3804                                         no--;
3805                                         nn--;
3806                                         adds[j] = NULL;
3807                                         dels[i] = NULL;
3808                                         break;
3809                                 }
3810                         }
3811                 }
3812
3813                 /* Don't delete/add an objectClass, always use the replace op.
3814                  * Modify would fail if provider has replaced entry with a new,
3815                  * and the new explicitly includes a superior of a class that was
3816                  * only included implicitly in the old entry.  Ref ITS#5517.
3817                  *
3818                  * Also use replace op if attr has no equality matching rule.
3819                  * (ITS#5781)
3820                  */
3821                 if ( ( nn || ( no > 0 && no < o ) ) &&
3822                         ( old->a_desc == slap_schema.si_ad_objectClass ||
3823                          !old->a_desc->ad_type->sat_equality ) )
3824                 {
3825                         no = o;
3826                 }
3827
3828                 i = j;
3829                 /* all old values were deleted, just use the replace op */
3830                 if ( no == o ) {
3831                         i = j-1;
3832                 } else if ( no ) {
3833                 /* delete some values */
3834                         mod = ch_malloc( sizeof( Modifications ) );
3835                         mod->sml_op = LDAP_MOD_DELETE;
3836                         mod->sml_flags = 0;
3837                         mod->sml_desc = old->a_desc;
3838                         mod->sml_type = mod->sml_desc->ad_cname;
3839                         mod->sml_numvals = no;
3840                         mod->sml_values = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3841                         if ( old->a_vals != old->a_nvals ) {
3842                                 mod->sml_nvalues = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3843                         } else {
3844                                 mod->sml_nvalues = NULL;
3845                         }
3846                         j = 0;
3847                         for ( i = 0; i < o; i++ ) {
3848                                 if ( !dels[i] ) continue;
3849                                 ber_dupbv( &mod->sml_values[j], &old->a_vals[i] );
3850                                 if ( mod->sml_nvalues ) {
3851                                         ber_dupbv( &mod->sml_nvalues[j], &old->a_nvals[i] );
3852                                 }
3853                                 j++;
3854                         }
3855                         BER_BVZERO( &mod->sml_values[j] );
3856                         if ( mod->sml_nvalues ) {
3857                                 BER_BVZERO( &mod->sml_nvalues[j] );
3858                         }
3859                         *modtail = mod;
3860                         modtail = &mod->sml_next;
3861                         i = j;
3862                 }
3863                 op->o_tmpfree( dels, op->o_tmpmemctx );
3864                 /* some values were added */
3865                 if ( nn && no < o ) {
3866                         mod = ch_malloc( sizeof( Modifications ) );
3867                         mod->sml_op = LDAP_MOD_ADD;
3868                         mod->sml_flags = 0;
3869                         mod->sml_desc = old->a_desc;
3870                         mod->sml_type = mod->sml_desc->ad_cname;
3871                         mod->sml_numvals = nn;
3872                         mod->sml_values = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3873                         if ( old->a_vals != old->a_nvals ) {
3874                                 mod->sml_nvalues = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3875                         } else {
3876                                 mod->sml_nvalues = NULL;
3877                         }
3878                         j = 0;
3879                         for ( i = 0; i < n; i++ ) {
3880                                 if ( !adds[i] ) continue;
3881                                 ber_dupbv( &mod->sml_values[j], &new->a_vals[i] );
3882                                 if ( mod->sml_nvalues ) {
3883                                         ber_dupbv( &mod->sml_nvalues[j], &new->a_nvals[i] );
3884                                 }
3885                                 j++;
3886                         }
3887                         BER_BVZERO( &mod->sml_values[j] );
3888                         if ( mod->sml_nvalues ) {
3889                                 BER_BVZERO( &mod->sml_nvalues[j] );
3890                         }
3891                         *modtail = mod;
3892                         modtail = &mod->sml_next;
3893                         i = j;
3894                 }
3895                 op->o_tmpfree( adds, op->o_tmpmemctx );
3896         } else {
3897                 /* new attr, just use the new mod */
3898                 i = 0;
3899                 j = 1;
3900         }
3901         /* advance to next element */
3902         mod = **mcur;
3903         if ( mod ) {
3904                 if ( i != j ) {
3905                         **mcur = mod->sml_next;
3906                         *modtail = mod;
3907                         modtail = &mod->sml_next;
3908                 } else {
3909                         *mcur = &mod->sml_next;
3910                 }
3911         }
3912         *mret = modtail;
3913 }
3914
3915 /* Generate a set of modifications to change the old entry into the
3916  * new one. On input ml is a list of modifications equivalent to
3917  * the new entry. It will be massaged and the result will be stored
3918  * in mods.
3919  */
3920 void syncrepl_diff_entry( Operation *op, Attribute *old, Attribute *new,
3921         Modifications **mods, Modifications **ml, int is_ctx)
3922 {
3923         Modifications **modtail = mods;
3924
3925         /* We assume that attributes are saved in the same order
3926          * in the remote and local databases. So if we walk through
3927          * the attributeDescriptions one by one they should match in
3928          * lock step. If not, look for an add or delete.
3929          */
3930         while ( old && new )
3931         {
3932                 /* If we've seen this before, use its mod now */
3933                 if ( new->a_flags & SLAP_ATTR_IXADD ) {
3934                         attr_cmp( op, NULL, new, &modtail, &ml );
3935                         new = new->a_next;
3936                         continue;
3937                 }
3938                 /* Skip contextCSN */
3939                 if ( is_ctx && old->a_desc ==
3940                         slap_schema.si_ad_contextCSN ) {
3941                         old = old->a_next;
3942                         continue;
3943                 }
3944
3945                 if ( old->a_desc != new->a_desc ) {
3946                         Modifications *mod;
3947                         Attribute *tmp;
3948
3949                         /* If it's just been re-added later,
3950                          * remember that we've seen it.
3951                          */
3952                         tmp = attr_find( new, old->a_desc );
3953                         if ( tmp ) {
3954                                 tmp->a_flags |= SLAP_ATTR_IXADD;
3955                         } else {
3956                                 /* If it's a new attribute, pull it in.
3957                                  */
3958                                 tmp = attr_find( old, new->a_desc );
3959                                 if ( !tmp ) {
3960                                         attr_cmp( op, NULL, new, &modtail, &ml );
3961                                         new = new->a_next;
3962                                         continue;
3963                                 }
3964                                 /* Delete old attr */
3965                                 mod = ch_malloc( sizeof( Modifications ) );
3966                                 mod->sml_op = LDAP_MOD_DELETE;
3967                                 mod->sml_flags = 0;
3968                                 mod->sml_desc = old->a_desc;
3969                                 mod->sml_type = mod->sml_desc->ad_cname;
3970                                 mod->sml_numvals = 0;
3971                                 mod->sml_values = NULL;
3972                                 mod->sml_nvalues = NULL;
3973                                 *modtail = mod;
3974                                 modtail = &mod->sml_next;
3975                         }
3976                         old = old->a_next;
3977                         continue;
3978                 }
3979                 /* kludge - always update modifiersName so that it
3980                  * stays co-located with the other mod opattrs. But only
3981                  * if we know there are other valid mods.
3982                  */
3983                 if ( *mods && ( old->a_desc == slap_schema.si_ad_modifiersName ||
3984                         old->a_desc == slap_schema.si_ad_modifyTimestamp ))
3985                         attr_cmp( op, NULL, new, &modtail, &ml );
3986                 else
3987                         attr_cmp( op, old, new, &modtail, &ml );
3988                 new = new->a_next;
3989                 old = old->a_next;
3990         }
3991         *modtail = *ml;
3992         *ml = NULL;
3993 }
3994
3995 static int
3996 dn_callback(
3997         Operation*      op,
3998         SlapReply*      rs )
3999 {
4000         dninfo *dni = op->o_callback->sc_private;
4001
4002         if ( rs->sr_type == REP_SEARCH ) {
4003                 if ( !BER_BVISNULL( &dni->dn ) ) {
4004                         Debug( LDAP_DEBUG_ANY,
4005                                 "dn_callback : consistency error - "
4006                                 "entryUUID is not unique\n", 0, 0, 0 );
4007                 } else {
4008                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
4009                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
4010                         /* If there is a new entry, see if it differs from the old.
4011                          * We compare the non-normalized values so that cosmetic changes
4012                          * in the provider are always propagated.
4013                          */
4014                         if ( dni->new_entry ) {
4015                                 Attribute *old, *new;
4016                                 struct berval old_rdn, new_rdn;
4017                                 struct berval old_p, new_p;
4018                                 int is_ctx, new_sup = 0;
4019
4020                                 /* If old entry is not a glue entry, make sure new entry
4021                                  * is actually newer than old entry
4022                                  */
4023                                 if ( !is_entry_glue( rs->sr_entry )) {
4024                                         old = attr_find( rs->sr_entry->e_attrs,
4025                                                 slap_schema.si_ad_entryCSN );
4026                                         new = attr_find( dni->new_entry->e_attrs,
4027                                                 slap_schema.si_ad_entryCSN );
4028                                         if ( new && old ) {
4029                                                 int rc;
4030                                                 ber_len_t len = old->a_vals[0].bv_len;
4031                                                 if ( len > new->a_vals[0].bv_len )
4032                                                         len = new->a_vals[0].bv_len;
4033                                                 rc = memcmp( old->a_vals[0].bv_val,
4034                                                         new->a_vals[0].bv_val, len );
4035                                                 if ( rc > 0 ) {
4036                                                         Debug( LDAP_DEBUG_SYNC,
4037                                                                 "dn_callback : new entry is older than ours "
4038                                                                 "%s ours %s, new %s\n",
4039                                                                 rs->sr_entry->e_name.bv_val,
4040                                                                 old->a_vals[0].bv_val,
4041                                                                 new->a_vals[0].bv_val );
4042                                                         return LDAP_SUCCESS;
4043                                                 } else if ( rc == 0 ) {
4044                                                         Debug( LDAP_DEBUG_SYNC,
4045                                                                 "dn_callback : entries have identical CSN "
4046                                                                 "%s %s\n",
4047                                                                 rs->sr_entry->e_name.bv_val,
4048                                                                 old->a_vals[0].bv_val, 0 );
4049                                                         return LDAP_SUCCESS;
4050                                                 }
4051                                         }
4052                                 }
4053
4054                                 is_ctx = dn_match( &rs->sr_entry->e_nname,
4055                                         &op->o_bd->be_nsuffix[0] );
4056
4057                                 /* Did the DN change?
4058                                  * case changes in the parent are ignored,
4059                                  * we only want to know if the RDN was
4060                                  * actually changed.
4061                                  */
4062                                 dnRdn( &rs->sr_entry->e_name, &old_rdn );
4063                                 dnRdn( &dni->new_entry->e_name, &new_rdn );
4064                                 dnParent( &rs->sr_entry->e_nname, &old_p );
4065                                 dnParent( &dni->new_entry->e_nname, &new_p );
4066
4067                                 new_sup = !dn_match( &old_p, &new_p );
4068                                 if ( !dn_match( &old_rdn, &new_rdn ) || new_sup )
4069                                 {
4070                                         struct berval oldRDN, oldVal;
4071                                         AttributeDescription *ad = NULL;
4072                                         int oldpos, newpos;
4073                                         Attribute *a;
4074
4075                                         dni->renamed = 1;
4076                                         if ( new_sup )
4077                                                 dni->nnewSup = new_p;
4078
4079                                         /* See if the oldRDN was deleted */
4080                                         dnRdn( &rs->sr_entry->e_nname, &oldRDN );
4081                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
4082                                         oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
4083                                                 oldRDN.bv_val );
4084                                         oldRDN.bv_len -= oldVal.bv_len + 1;
4085                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
4086                                         dni->oldDesc = ad;
4087                                         for ( oldpos=0, a=rs->sr_entry->e_attrs;
4088                                                 a && a->a_desc != ad; oldpos++, a=a->a_next );
4089                                         dni->oldNattr = a;
4090                                         for ( newpos=0, a=dni->new_entry->e_attrs;
4091                                                 a && a->a_desc != ad; newpos++, a=a->a_next );
4092                                         if ( !a || oldpos != newpos || attr_valfind( a,
4093                                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
4094                                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
4095                                                 SLAP_MR_VALUE_OF_SYNTAX,
4096                                                 &oldVal, NULL, op->o_tmpmemctx ) != LDAP_SUCCESS )
4097                                         {
4098                                                 dni->delOldRDN = 1;
4099                                         }
4100                                         /* Get the newRDN's desc */
4101                                         dnRdn( &dni->new_entry->e_nname, &oldRDN );
4102                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=');
4103                                         oldRDN.bv_len = oldVal.bv_val - oldRDN.bv_val;
4104                                         ad = NULL;
4105                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
4106                                         dni->newDesc = ad;
4107
4108                                         /* A ModDN has happened, but in Refresh mode other
4109                                          * changes may have occurred before we picked it up.
4110                                          * So fallthru to regular Modify processing.
4111                                          */
4112                                 }
4113
4114                                 syncrepl_diff_entry( op, rs->sr_entry->e_attrs,
4115                                         dni->new_entry->e_attrs, &dni->mods, dni->modlist,
4116                                         is_ctx );
4117                         }
4118                 }
4119         } else if ( rs->sr_type == REP_RESULT ) {
4120                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
4121                         Debug( LDAP_DEBUG_ANY,
4122                                 "dn_callback : consistency error - "
4123                                 "entryUUID is not unique\n", 0, 0, 0 );
4124                 }
4125         }
4126
4127         return LDAP_SUCCESS;
4128 }
4129
4130 static int
4131 nonpresent_callback(
4132         Operation*      op,
4133         SlapReply*      rs )
4134 {
4135         syncinfo_t *si = op->o_callback->sc_private;
4136         Attribute *a;
4137         int count = 0;
4138         struct berval* present_uuid = NULL;
4139         struct nonpresent_entry *np_entry;
4140
4141         if ( rs->sr_type == REP_RESULT ) {
4142                 count = avl_free( si->si_presentlist, ch_free );
4143                 si->si_presentlist = NULL;
4144
4145         } else if ( rs->sr_type == REP_SEARCH ) {
4146                 if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
4147                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
4148
4149                         if ( a ) {
4150                                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
4151                                         syncuuid_cmp );
4152                         }
4153
4154                         if ( LogTest( LDAP_DEBUG_SYNC ) ) {
4155                                 char buf[sizeof("rid=999 non")];
4156
4157                                 snprintf( buf, sizeof(buf), "%s %s", si->si_ridtxt,
4158                                         present_uuid ? "" : "non" );
4159
4160                                 Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %spresent UUID %s, dn %s\n",
4161                                         buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
4162                         }
4163
4164                         if ( a == NULL ) return 0;
4165                 }
4166
4167                 if ( present_uuid == NULL ) {
4168                         np_entry = (struct nonpresent_entry *)
4169                                 ch_calloc( 1, sizeof( struct nonpresent_entry ) );
4170                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
4171                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
4172                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
4173
4174                 } else {
4175                         avl_delete( &si->si_presentlist,
4176                                 &a->a_nvals[0], syncuuid_cmp );
4177                         ch_free( present_uuid );
4178                 }
4179         }
4180         return LDAP_SUCCESS;
4181 }
4182
4183 static int
4184 null_callback(
4185         Operation*      op,
4186         SlapReply*      rs )
4187 {
4188         if ( rs->sr_err != LDAP_SUCCESS &&
4189                 rs->sr_err != LDAP_REFERRAL &&
4190                 rs->sr_err != LDAP_ALREADY_EXISTS &&
4191                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
4192                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
4193         {
4194                 Debug( LDAP_DEBUG_ANY,
4195                         "null_callback : error code 0x%x\n",
4196                         rs->sr_err, 0, 0 );
4197         }
4198         return LDAP_SUCCESS;
4199 }
4200
4201 static struct berval *
4202 slap_uuidstr_from_normalized(
4203         struct berval* uuidstr,
4204         struct berval* normalized,
4205         void *ctx )
4206 {
4207 #if 0
4208         struct berval *new;
4209         unsigned char nibble;
4210         int i, d = 0;
4211
4212         if ( normalized == NULL ) return NULL;
4213         if ( normalized->bv_len != 16 ) return NULL;
4214
4215         if ( uuidstr ) {
4216                 new = uuidstr;
4217         } else {
4218                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
4219                 if ( new == NULL ) {
4220                         return NULL;
4221                 }
4222         }
4223
4224         new->bv_len = 36;
4225
4226         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
4227                 if ( new != uuidstr ) {
4228                         slap_sl_free( new, ctx );
4229                 }
4230                 return NULL;
4231         }
4232
4233         for ( i = 0; i < 16; i++ ) {
4234                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
4235                         new->bv_val[(i<<1)+d] = '-';
4236                         d += 1;
4237                 }
4238
4239                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
4240                 if ( nibble < 10 ) {
4241                         new->bv_val[(i<<1)+d] = nibble + '0';
4242                 } else {
4243                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
4244                 }
4245
4246                 nibble = (normalized->bv_val[i]) & 0xF;
4247                 if ( nibble < 10 ) {
4248                         new->bv_val[(i<<1)+d+1] = nibble + '0';
4249                 } else {
4250                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
4251                 }
4252         }
4253
4254         new->bv_val[new->bv_len] = '\0';
4255         return new;
4256 #endif
4257
4258         struct berval   *new;
4259         int             rc = 0;
4260
4261         if ( normalized == NULL ) return NULL;
4262         if ( normalized->bv_len != 16 ) return NULL;
4263
4264         if ( uuidstr ) {
4265                 new = uuidstr;
4266
4267         } else {
4268                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
4269                 if ( new == NULL ) {
4270                         return NULL;
4271                 }
4272         }
4273
4274         new->bv_len = 36;
4275
4276         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
4277                 rc = 1;
4278                 goto done;
4279         }
4280
4281         rc = lutil_uuidstr_from_normalized( normalized->bv_val,
4282                 normalized->bv_len, new->bv_val, new->bv_len + 1 );
4283
4284 done:;
4285         if ( rc == -1 ) {
4286                 if ( new != NULL ) {
4287                         if ( new->bv_val != NULL ) {
4288                                 slap_sl_free( new->bv_val, ctx );
4289                         }
4290
4291                         if ( new != uuidstr ) {
4292                                 slap_sl_free( new, ctx );
4293                         }
4294                 }
4295                 new = NULL;
4296
4297         } else {
4298                 new->bv_len = rc;
4299         }
4300
4301         return new;
4302 }
4303
4304 static int
4305 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
4306 {
4307         const struct berval *uuid1 = v_uuid1;
4308         const struct berval *uuid2 = v_uuid2;
4309         int rc = uuid1->bv_len - uuid2->bv_len;
4310         if ( rc ) return rc;
4311         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
4312 }
4313
4314 void
4315 syncinfo_free( syncinfo_t *sie, int free_all )
4316 {
4317         syncinfo_t *si_next;
4318
4319         Debug( LDAP_DEBUG_TRACE, "syncinfo_free: %s\n",
4320                 sie->si_ridtxt, 0, 0 );
4321
4322         do {
4323                 si_next = sie->si_next;
4324
4325                 if ( sie->si_ld ) {
4326                         if ( sie->si_conn ) {
4327                                 connection_client_stop( sie->si_conn );
4328                                 sie->si_conn = NULL;
4329                         }
4330                         ldap_unbind_ext( sie->si_ld, NULL, NULL );
4331                 }
4332         
4333                 if ( sie->si_re ) {
4334                         struct re_s             *re = sie->si_re;
4335                         sie->si_re = NULL;
4336
4337                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4338                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
4339                                 ldap_pvt_runqueue_stoptask( &slapd_rq, re );
4340                         ldap_pvt_runqueue_remove( &slapd_rq, re );
4341                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4342                 }
4343
4344                 ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
4345
4346                 bindconf_free( &sie->si_bindconf );
4347
4348                 if ( sie->si_filterstr.bv_val ) {
4349                         ch_free( sie->si_filterstr.bv_val );
4350                 }
4351                 if ( sie->si_filter ) {
4352                         filter_free( sie->si_filter );
4353                 }
4354                 if ( sie->si_logfilterstr.bv_val ) {
4355                         ch_free( sie->si_logfilterstr.bv_val );
4356                 }
4357                 if ( sie->si_base.bv_val ) {
4358                         ch_free( sie->si_base.bv_val );
4359                 }
4360                 if ( sie->si_logbase.bv_val ) {
4361                         ch_free( sie->si_logbase.bv_val );
4362                 }
4363                 if ( sie->si_be && SLAP_SYNC_SUBENTRY( sie->si_be )) {
4364                         ch_free( sie->si_contextdn.bv_val );
4365                 }
4366                 if ( sie->si_attrs ) {
4367                         int i = 0;
4368                         while ( sie->si_attrs[i] != NULL ) {
4369                                 ch_free( sie->si_attrs[i] );
4370                                 i++;
4371                         }
4372                         ch_free( sie->si_attrs );
4373                 }
4374                 if ( sie->si_exattrs ) {
4375                         int i = 0;
4376                         while ( sie->si_exattrs[i] != NULL ) {
4377                                 ch_free( sie->si_exattrs[i] );
4378                                 i++;
4379                         }
4380                         ch_free( sie->si_exattrs );
4381                 }
4382                 if ( sie->si_anlist ) {
4383                         int i = 0;
4384                         while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
4385                                 ch_free( sie->si_anlist[i].an_name.bv_val );
4386                                 i++;
4387                         }
4388                         ch_free( sie->si_anlist );
4389                 }
4390                 if ( sie->si_exanlist ) {
4391                         int i = 0;
4392                         while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
4393                                 ch_free( sie->si_exanlist[i].an_name.bv_val );
4394                                 i++;
4395                         }
4396                         ch_free( sie->si_exanlist );
4397                 }
4398                 if ( sie->si_retryinterval ) {
4399                         ch_free( sie->si_retryinterval );
4400                 }
4401                 if ( sie->si_retrynum ) {
4402                         ch_free( sie->si_retrynum );
4403                 }
4404                 if ( sie->si_retrynum_init ) {
4405                         ch_free( sie->si_retrynum_init );
4406                 }
4407                 slap_sync_cookie_free( &sie->si_syncCookie, 0 );
4408                 if ( sie->si_presentlist ) {
4409                     avl_free( sie->si_presentlist, ch_free );
4410                 }
4411                 while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
4412                         struct nonpresent_entry* npe;
4413                         npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
4414                         LDAP_LIST_REMOVE( npe, npe_link );
4415                         if ( npe->npe_name ) {
4416                                 if ( npe->npe_name->bv_val ) {
4417                                         ch_free( npe->npe_name->bv_val );
4418                                 }
4419                                 ch_free( npe->npe_name );
4420                         }
4421                         if ( npe->npe_nname ) {
4422                                 if ( npe->npe_nname->bv_val ) {
4423                                         ch_free( npe->npe_nname->bv_val );
4424                                 }
4425                                 ch_free( npe->npe_nname );
4426                         }
4427                         ch_free( npe );
4428                 }
4429                 if ( sie->si_cookieState ) {
4430                         sie->si_cookieState->cs_ref--;
4431                         if ( !sie->si_cookieState->cs_ref ) {
4432                                 ch_free( sie->si_cookieState->cs_sids );
4433                                 ber_bvarray_free( sie->si_cookieState->cs_vals );
4434                                 ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_mutex );
4435                                 ch_free( sie->si_cookieState->cs_psids );
4436                                 ber_bvarray_free( sie->si_cookieState->cs_pvals );
4437                                 ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_pmutex );
4438                                 ch_free( sie->si_cookieState );
4439                         }
4440                 }
4441 #ifdef ENABLE_REWRITE
4442                 if ( sie->si_rewrite )
4443                         rewrite_info_delete( &sie->si_rewrite );
4444                 if ( sie->si_suffixm.bv_val )
4445                         ch_free( sie->si_suffixm.bv_val );
4446 #endif
4447                 ch_free( sie );
4448                 sie = si_next;
4449         } while ( free_all && si_next );
4450 }
4451
4452 #ifdef ENABLE_REWRITE
4453 static int
4454 config_suffixm( ConfigArgs *c, syncinfo_t *si )
4455 {
4456         char *argvEngine[] = { "rewriteEngine", "on", NULL };
4457         char *argvContext[] = { "rewriteContext", SUFFIXM_CTX, NULL };
4458         char *argvRule[] = { "rewriteRule", NULL, NULL, ":", NULL };
4459         char *vnc, *rnc;
4460         int rc;
4461
4462         if ( si->si_rewrite )
4463                 rewrite_info_delete( &si->si_rewrite );
4464         si->si_rewrite = rewrite_info_init( REWRITE_MODE_USE_DEFAULT );
4465
4466         rc = rewrite_parse( si->si_rewrite, c->fname, c->lineno, 2, argvEngine );
4467         if ( rc != LDAP_SUCCESS )
4468                 return rc;
4469
4470         rc = rewrite_parse( si->si_rewrite, c->fname, c->lineno, 2, argvContext );
4471         if ( rc != LDAP_SUCCESS )
4472                 return rc;
4473
4474         vnc = ch_malloc( si->si_base.bv_len + 6 );
4475         strcpy( vnc, "(.*)" );
4476         lutil_strcopy( lutil_strcopy( vnc+4, si->si_base.bv_val ), "$" );
4477         argvRule[1] = vnc;
4478
4479         rnc = ch_malloc( si->si_suffixm.bv_len + 3 );
4480         strcpy( rnc, "%1" );
4481         strcpy( rnc+2, si->si_suffixm.bv_val );
4482         argvRule[2] = rnc;
4483
4484         rc = rewrite_parse( si->si_rewrite, c->fname, c->lineno, 4, argvRule );
4485         ch_free( vnc );
4486         ch_free( rnc );
4487         return rc;
4488 }
4489 #endif
4490
4491 /* NOTE: used & documented in slapd.conf(5) */
4492 #define IDSTR                   "rid"
4493 #define PROVIDERSTR             "provider"
4494 #define SCHEMASTR               "schemachecking"
4495 #define FILTERSTR               "filter"
4496 #define SEARCHBASESTR           "searchbase"
4497 #define SCOPESTR                "scope"
4498 #define ATTRSONLYSTR            "attrsonly"
4499 #define ATTRSSTR                "attrs"
4500 #define TYPESTR                 "type"
4501 #define INTERVALSTR             "interval"
4502 #define RETRYSTR                "retry"
4503 #define SLIMITSTR               "sizelimit"
4504 #define TLIMITSTR               "timelimit"
4505 #define SYNCDATASTR             "syncdata"
4506 #define LOGBASESTR              "logbase"
4507 #define LOGFILTERSTR    "logfilter"
4508 #define SUFFIXMSTR              "suffixmassage"
4509 #define STRICT_REFRESH  "strictrefresh"
4510
4511 /* FIXME: undocumented */
4512 #define EXATTRSSTR              "exattrs"
4513 #define MANAGEDSAITSTR          "manageDSAit"
4514
4515 /* mandatory */
4516 enum {
4517         GOT_RID                 = 0x00000001U,
4518         GOT_PROVIDER            = 0x00000002U,
4519         GOT_SCHEMACHECKING      = 0x00000004U,
4520         GOT_FILTER              = 0x00000008U,
4521         GOT_SEARCHBASE          = 0x00000010U,
4522         GOT_SCOPE               = 0x00000020U,
4523         GOT_ATTRSONLY           = 0x00000040U,
4524         GOT_ATTRS               = 0x00000080U,
4525         GOT_TYPE                = 0x00000100U,
4526         GOT_INTERVAL            = 0x00000200U,
4527         GOT_RETRY               = 0x00000400U,
4528         GOT_SLIMIT              = 0x00000800U,
4529         GOT_TLIMIT              = 0x00001000U,
4530         GOT_SYNCDATA            = 0x00002000U,
4531         GOT_LOGBASE             = 0x00004000U,
4532         GOT_LOGFILTER           = 0x00008000U,
4533         GOT_EXATTRS             = 0x00010000U,
4534         GOT_MANAGEDSAIT         = 0x00020000U,
4535         GOT_BINDCONF            = 0x00040000U,
4536         GOT_SUFFIXM             = 0x00080000U,
4537
4538 /* check */
4539         GOT_REQUIRED            = (GOT_RID|GOT_PROVIDER|GOT_SEARCHBASE)
4540 };
4541
4542 static slap_verbmasks datamodes[] = {
4543         { BER_BVC("default"), SYNCDATA_DEFAULT },
4544         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
4545         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
4546         { BER_BVNULL, 0 }
4547 };
4548
4549 static int
4550 parse_syncrepl_retry(
4551         ConfigArgs      *c,
4552         char            *arg,
4553         syncinfo_t      *si )
4554 {
4555         char **retry_list;
4556         int j, k, n;
4557         int use_default = 0;
4558
4559         char *val = arg + STRLENOF( RETRYSTR "=" );
4560         if ( strcasecmp( val, "undefined" ) == 0 ) {
4561                 val = "3600 +";
4562                 use_default = 1;
4563         }
4564
4565         retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
4566         retry_list[0] = NULL;
4567
4568         slap_str2clist( &retry_list, val, " ,\t" );
4569
4570         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
4571         n = k / 2;
4572         if ( k % 2 ) {
4573                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4574                         "Error: incomplete syncrepl retry list" );
4575                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4576                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
4577                         ch_free( retry_list[k] );
4578                 }
4579                 ch_free( retry_list );
4580                 return 1;
4581         }
4582         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
4583         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
4584         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
4585         for ( j = 0; j < n; j++ ) {
4586                 unsigned long   t;
4587                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
4588                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4589                                 "Error: invalid retry interval \"%s\" (#%d)",
4590                                 retry_list[j*2], j );
4591                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4592                         /* do some cleanup */
4593                         return 1;
4594                 }
4595                 si->si_retryinterval[j] = (time_t)t;
4596                 if ( *retry_list[j*2+1] == '+' ) {
4597                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
4598                         si->si_retrynum[j] = RETRYNUM_FOREVER;
4599                         j++;
4600                         break;
4601                 } else {
4602                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
4603                                         || si->si_retrynum_init[j] <= 0 )
4604                         {
4605                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4606                                         "Error: invalid initial retry number \"%s\" (#%d)",
4607                                         retry_list[j*2+1], j );
4608                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4609                                 /* do some cleanup */
4610                                 return 1;
4611                         }
4612                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
4613                                         || si->si_retrynum[j] <= 0 )
4614                         {
4615                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4616                                         "Error: invalid retry number \"%s\" (#%d)",
4617                                         retry_list[j*2+1], j );
4618                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4619                                 /* do some cleanup */
4620                                 return 1;
4621                         }
4622                 }
4623         }
4624         if ( j < 1 || si->si_retrynum_init[j-1] != RETRYNUM_FOREVER ) {
4625                 Debug( LDAP_DEBUG_CONFIG,
4626                         "%s: syncrepl will eventually stop retrying; the \"retry\" parameter should end with a '+'.\n",
4627                         c->log, 0, 0 );
4628         }
4629
4630         si->si_retrynum_init[j] = RETRYNUM_TAIL;
4631         si->si_retrynum[j] = RETRYNUM_TAIL;
4632         si->si_retryinterval[j] = 0;
4633         
4634         for ( k = 0; retry_list && retry_list[k]; k++ ) {
4635                 ch_free( retry_list[k] );
4636         }
4637         ch_free( retry_list );
4638         if ( !use_default ) {
4639                 si->si_got |= GOT_RETRY;
4640         }
4641
4642         return 0;
4643 }
4644
4645 static int
4646 parse_syncrepl_line(
4647         ConfigArgs      *c,
4648         syncinfo_t      *si )
4649 {
4650         int     i;
4651         char    *val;
4652
4653         for ( i = 1; i < c->argc; i++ ) {
4654                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
4655                                         STRLENOF( IDSTR "=" ) ) )
4656                 {
4657                         int tmp;
4658                         /* '\0' string terminator accounts for '=' */
4659                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
4660                         if ( lutil_atoi( &tmp, val ) != 0 ) {
4661                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4662                                         "Error: parse_syncrepl_line: "
4663                                         "unable to parse syncrepl id \"%s\"", val );
4664                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4665                                 return -1;
4666                         }
4667                         if ( tmp > SLAP_SYNC_RID_MAX || tmp < 0 ) {
4668                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4669                                         "Error: parse_syncrepl_line: "
4670                                         "syncrepl id %d is out of range [0..%d]", tmp, SLAP_SYNC_RID_MAX );
4671                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4672                                 return -1;
4673                         }
4674                         si->si_rid = tmp;
4675                         sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
4676                         si->si_got |= GOT_RID;
4677                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
4678                                         STRLENOF( PROVIDERSTR "=" ) ) )
4679                 {
4680                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
4681                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
4682 #ifdef HAVE_TLS
4683                         if ( ldap_is_ldaps_url( val ))
4684                                 si->si_bindconf.sb_tls_do_init = 1;
4685 #endif
4686                         si->si_got |= GOT_PROVIDER;
4687                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
4688                                         STRLENOF( SCHEMASTR "=" ) ) )
4689                 {
4690                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
4691                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
4692                                 si->si_schemachecking = 1;
4693                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
4694                                 si->si_schemachecking = 0;
4695                         } else {
4696                                 si->si_schemachecking = 1;
4697                         }
4698                         si->si_got |= GOT_SCHEMACHECKING;
4699                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
4700                                         STRLENOF( FILTERSTR "=" ) ) )
4701                 {
4702                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
4703                         if ( si->si_filterstr.bv_val )
4704                                 ch_free( si->si_filterstr.bv_val );
4705                         ber_str2bv( val, 0, 1, &si->si_filterstr );
4706                         si->si_got |= GOT_FILTER;
4707                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
4708                                         STRLENOF( LOGFILTERSTR "=" ) ) )
4709                 {
4710                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
4711                         if ( si->si_logfilterstr.bv_val )
4712                                 ch_free( si->si_logfilterstr.bv_val );
4713                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
4714                         si->si_got |= GOT_LOGFILTER;
4715                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
4716                                         STRLENOF( SEARCHBASESTR "=" ) ) )
4717                 {
4718                         struct berval   bv;
4719                         int             rc;
4720
4721                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
4722                         if ( si->si_base.bv_val ) {
4723                                 ch_free( si->si_base.bv_val );
4724                         }
4725                         ber_str2bv( val, 0, 0, &bv );
4726                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
4727                         if ( rc != LDAP_SUCCESS ) {
4728                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4729                                         "Invalid base DN \"%s\": %d (%s)",
4730                                         val, rc, ldap_err2string( rc ) );
4731                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4732                                 return -1;
4733                         }
4734                         si->si_got |= GOT_SEARCHBASE;
4735 #ifdef ENABLE_REWRITE
4736                 } else if ( !strncasecmp( c->argv[ i ], SUFFIXMSTR "=",
4737                                         STRLENOF( SUFFIXMSTR "=" ) ) )
4738                 {
4739                         struct berval   bv;
4740                         int             rc;
4741
4742                         val = c->argv[ i ] + STRLENOF( SUFFIXMSTR "=" );
4743                         if ( si->si_suffixm.bv_val ) {
4744                                 ch_free( si->si_suffixm.bv_val );
4745                         }
4746                         ber_str2bv( val, 0, 0, &bv );
4747                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_suffixm, NULL );
4748                         if ( rc != LDAP_SUCCESS ) {
4749                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4750                                         "Invalid massage DN \"%s\": %d (%s)",
4751                                         val, rc, ldap_err2string( rc ) );
4752                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4753                                 return -1;
4754                         }
4755                         if ( !be_issubordinate( c->be, &si->si_suffixm )) {
4756                                 ch_free( si->si_suffixm.bv_val );
4757                                 BER_BVZERO( &si->si_suffixm );
4758                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4759                                         "Massage DN \"%s\" is not within the database naming context",
4760                                         val );
4761                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4762                                 return -1;
4763                         }
4764                         si->si_got |= GOT_SUFFIXM;
4765 #endif
4766                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
4767                                         STRLENOF( LOGBASESTR "=" ) ) )
4768                 {
4769                         struct berval   bv;
4770                         int             rc;
4771
4772                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
4773                         if ( si->si_logbase.bv_val ) {
4774                                 ch_free( si->si_logbase.bv_val );
4775                         }
4776                         ber_str2bv( val, 0, 0, &bv );
4777                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
4778                         if ( rc != LDAP_SUCCESS ) {
4779                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4780                                         "Invalid logbase DN \"%s\": %d (%s)",
4781                                         val, rc, ldap_err2string( rc ) );
4782                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4783                                 return -1;
4784                         }
4785                         si->si_got |= GOT_LOGBASE;
4786                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
4787                                         STRLENOF( SCOPESTR "=" ) ) )
4788                 {
4789                         int j;
4790                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
4791                         j = ldap_pvt_str2scope( val );
4792                         if ( j < 0 ) {
4793                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4794                                         "Error: parse_syncrepl_line: "
4795                                         "unknown scope \"%s\"", val);
4796                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4797                                 return -1;
4798                         }
4799                         si->si_scope = j;
4800                         si->si_got |= GOT_SCOPE;
4801                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
4802                                         STRLENOF( ATTRSONLYSTR ) ) )
4803                 {
4804                         si->si_attrsonly = 1;
4805                         si->si_got |= GOT_ATTRSONLY;
4806                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
4807                                         STRLENOF( ATTRSSTR "=" ) ) )
4808                 {
4809                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
4810                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4811                                 char *attr_fname;
4812                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
4813                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
4814                                 if ( si->si_anlist == NULL ) {
4815                                         ch_free( attr_fname );
4816                                         return -1;
4817                                 }
4818                                 si->si_anfile = attr_fname;
4819                         } else {
4820                                 char *str, *s, *next;
4821                                 const char *delimstr = " ,\t";
4822                                 str = ch_strdup( val );
4823                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
4824                                                 s != NULL;
4825                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
4826                                 {
4827                                         if ( strlen(s) == 1 && *s == '*' ) {
4828                                                 si->si_allattrs = 1;
4829                                                 val[ s - str ] = delimstr[0];
4830                                         }
4831                                         if ( strlen(s) == 1 && *s == '+' ) {
4832                                                 si->si_allopattrs = 1;
4833                                                 val [ s - str ] = delimstr[0];
4834                                         }
4835                                 }
4836                                 ch_free( str );
4837                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
4838                                 if ( si->si_anlist == NULL ) {
4839                                         return -1;
4840                                 }
4841                         }
4842                         si->si_got |= GOT_ATTRS;
4843                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
4844                                         STRLENOF( EXATTRSSTR "=" ) ) )
4845                 {
4846                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
4847                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4848                                 char *attr_fname;
4849                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
4850                                 si->si_exanlist = file2anlist(
4851                                         si->si_exanlist, attr_fname, " ,\t" );
4852                                 if ( si->si_exanlist == NULL ) {
4853                                         ch_free( attr_fname );
4854                                         return -1;
4855                                 }
4856                                 ch_free( attr_fname );
4857                         } else {
4858                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
4859                                 if ( si->si_exanlist == NULL ) {
4860                                         return -1;
4861                                 }
4862                         }
4863                         si->si_got |= GOT_EXATTRS;
4864                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
4865                                         STRLENOF( TYPESTR "=" ) ) )
4866                 {
4867                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
4868                         if ( !strncasecmp( val, "refreshOnly",
4869                                                 STRLENOF("refreshOnly") ) )
4870                         {
4871                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
4872                         } else if ( !strncasecmp( val, "refreshAndPersist",
4873                                                 STRLENOF("refreshAndPersist") ) )
4874                         {
4875                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
4876                                 si->si_interval = 60;
4877                         } else {
4878                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4879                                         "Error: parse_syncrepl_line: "
4880                                         "unknown sync type \"%s\"", val);
4881                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4882                                 return -1;
4883                         }
4884                         si->si_got |= GOT_TYPE;
4885                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
4886                                         STRLENOF( INTERVALSTR "=" ) ) )
4887                 {
4888                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
4889                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
4890                                 si->si_interval = 0;
4891                         } else if ( strchr( val, ':' ) != NULL ) {
4892                                 char *next, *ptr = val;
4893                                 int dd, hh, mm, ss;
4894
4895                                 dd = strtol( ptr, &next, 10 );
4896                                 if ( next == ptr || next[0] != ':' || dd < 0 ) {
4897                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4898                                                 "Error: parse_syncrepl_line: "
4899                                                 "invalid interval \"%s\", unable to parse days", val );
4900                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4901                                         return -1;
4902                                 }
4903                                 ptr = next + 1;
4904                                 hh = strtol( ptr, &next, 10 );
4905                                 if ( next == ptr || next[0] != ':' || hh < 0 || hh > 24 ) {
4906                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4907                                                 "Error: parse_syncrepl_line: "
4908                                                 "invalid interval \"%s\", unable to parse hours", val );
4909                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4910                                         return -1;
4911                                 }
4912                                 ptr = next + 1;
4913                                 mm = strtol( ptr, &next, 10 );
4914                                 if ( next == ptr || next[0] != ':' || mm < 0 || mm > 60 ) {
4915                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4916                                                 "Error: parse_syncrepl_line: "
4917                                                 "invalid interval \"%s\", unable to parse minutes", val );
4918                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4919                                         return -1;
4920                                 }
4921                                 ptr = next + 1;
4922                                 ss = strtol( ptr, &next, 10 );
4923                                 if ( next == ptr || next[0] != '\0' || ss < 0 || ss > 60 ) {
4924                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4925                                                 "Error: parse_syncrepl_line: "
4926                                                 "invalid interval \"%s\", unable to parse seconds", val );
4927                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4928                                         return -1;
4929                                 }
4930                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
4931                         } else {
4932                                 unsigned long   t;
4933
4934                                 if ( lutil_parse_time( val, &t ) != 0 ) {
4935                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4936                                                 "Error: parse_syncrepl_line: "
4937                                                 "invalid interval \"%s\"", val );
4938                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4939                                         return -1;
4940                                 }
4941                                 si->si_interval = (time_t)t;
4942                         }
4943                         if ( si->si_interval < 0 ) {
4944                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4945                                         "Error: parse_syncrepl_line: "
4946                                         "invalid interval \"%ld\"",
4947                                         (long) si->si_interval);
4948                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4949                                 return -1;
4950                         }
4951                         si->si_got |= GOT_INTERVAL;
4952                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
4953                                         STRLENOF( RETRYSTR "=" ) ) )
4954                 {
4955                         if ( parse_syncrepl_retry( c, c->argv[ i ], si ) ) {
4956                                 return 1;
4957                         }
4958                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
4959                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
4960                 {
4961                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
4962                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
4963                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
4964                         {
4965                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4966                                         "invalid manageDSAit value \"%s\".\n",
4967                                         val );
4968                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4969                                 return 1;
4970                         }
4971                         si->si_got |= GOT_MANAGEDSAIT;
4972                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
4973                                         STRLENOF( SLIMITSTR "=") ) )
4974                 {
4975                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
4976                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
4977                                 si->si_slimit = 0;
4978
4979                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
4980                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4981                                         "invalid size limit value \"%s\".\n",
4982                                         val );
4983                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4984                                 return 1;
4985                         }
4986                         si->si_got |= GOT_SLIMIT;
4987                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
4988                                         STRLENOF( TLIMITSTR "=" ) ) )
4989                 {
4990                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
4991                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
4992                                 si->si_tlimit = 0;
4993
4994                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
4995                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4996                                         "invalid time limit value \"%s\".\n",
4997                                         val );
4998                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4999                                 return 1;
5000                         }
5001                         si->si_got |= GOT_TLIMIT;
5002                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
5003                                         STRLENOF( SYNCDATASTR "=" ) ) )
5004                 {
5005                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
5006                         si->si_syncdata = verb_to_mask( val, datamodes );
5007                         si->si_got |= GOT_SYNCDATA;
5008                 } else if ( !strncasecmp( c->argv[ i ], STRICT_REFRESH,
5009                                         STRLENOF( STRICT_REFRESH ) ) )
5010                 {
5011                         si->si_strict_refresh = 1;
5012                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
5013                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5014                                 "Error: parse_syncrepl_line: "
5015                                 "unable to parse \"%s\"\n", c->argv[ i ] );
5016                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5017                         return -1;
5018                 }
5019                 si->si_got |= GOT_BINDCONF;
5020         }
5021
5022         if ( ( si->si_got & GOT_REQUIRED ) != GOT_REQUIRED ) {
5023                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5024                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
5025                         si->si_got & GOT_RID ? "" : " "IDSTR,
5026                         si->si_got & GOT_PROVIDER ? "" : " "PROVIDERSTR,
5027                         si->si_got & GOT_SEARCHBASE ? "" : " "SEARCHBASESTR );
5028                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5029                 return -1;
5030         }
5031
5032         if ( !be_issubordinate( c->be, &si->si_base ) && !( si->si_got & GOT_SUFFIXM )) {
5033                 ch_free( si->si_base.bv_val );
5034                 BER_BVZERO( &si->si_base );
5035                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5036                         "Base DN \"%s\" is not within the database naming context",
5037                         val );
5038                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5039                 return -1;
5040         }
5041
5042 #ifdef ENABLE_REWRITE
5043         if ( si->si_got & GOT_SUFFIXM ) {
5044                 if (config_suffixm( c, si )) {
5045                         ch_free( si->si_suffixm.bv_val );
5046                         BER_BVZERO( &si->si_suffixm );
5047                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5048                                 "Error configuring rewrite engine" );
5049                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5050                         return -1;
5051                 }
5052         }
5053 #endif
5054
5055         if ( !( si->si_got & GOT_RETRY ) ) {
5056                 Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": no retry defined, using default\n", 
5057                         si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", 0 );
5058                 if ( si->si_retryinterval == NULL ) {
5059                         if ( parse_syncrepl_retry( c, "retry=undefined", si ) ) {
5060                                 return 1;
5061                         }
5062                 }
5063         }
5064
5065         si->si_filter = str2filter( si->si_filterstr.bv_val );
5066         if ( si->si_filter == NULL ) {
5067                 Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": unable to parse filter=\"%s\"\n", 
5068                         si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", si->si_filterstr.bv_val );
5069                 return 1;
5070         }
5071
5072         return 0;
5073 }
5074
5075 static int
5076 add_syncrepl(
5077         ConfigArgs *c )
5078 {
5079         syncinfo_t *si;
5080         int     rc = 0;
5081
5082         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
5083                 snprintf( c->cr_msg, sizeof(c->cr_msg), "database %s does not support "
5084                         "operations required for syncrepl", c->be->be_type );
5085                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
5086                 return 1;
5087         }
5088         if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
5089                 strcpy( c->cr_msg, "rootDN must be defined before syncrepl may be used" );
5090                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
5091                 return 1;
5092         }
5093         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
5094
5095         if ( si == NULL ) {
5096                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
5097                 return 1;
5098         }
5099
5100         si->si_bindconf.sb_tls = SB_TLS_OFF;
5101         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
5102         si->si_schemachecking = 0;
5103         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
5104                 &si->si_filterstr );
5105         si->si_base.bv_val = NULL;
5106         si->si_scope = LDAP_SCOPE_SUBTREE;
5107         si->si_attrsonly = 0;
5108         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
5109         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
5110         si->si_attrs = NULL;
5111         si->si_allattrs = 0;
5112         si->si_allopattrs = 0;
5113         si->si_exattrs = NULL;
5114         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
5115         si->si_interval = 86400;
5116         si->si_retryinterval = NULL;
5117         si->si_retrynum_init = NULL;
5118         si->si_retrynum = NULL;
5119         si->si_manageDSAit = 0;
5120         si->si_tlimit = 0;
5121         si->si_slimit = 0;
5122
5123         si->si_presentlist = NULL;
5124         LDAP_LIST_INIT( &si->si_nonpresentlist );
5125         ldap_pvt_thread_mutex_init( &si->si_mutex );
5126
5127         rc = parse_syncrepl_line( c, si );
5128
5129         if ( rc == 0 ) {
5130                 LDAPURLDesc *lud;
5131
5132                 /* Must be LDAPv3 because we need controls */
5133                 switch ( si->si_bindconf.sb_version ) {
5134                 case 0:
5135                         /* not explicitly set */
5136                         si->si_bindconf.sb_version = LDAP_VERSION3;
5137                         break;
5138                 case 3:
5139                         /* explicitly set */
5140                         break;
5141                 default:
5142                         Debug( LDAP_DEBUG_ANY,
5143                                 "version %d incompatible with syncrepl\n",
5144                                 si->si_bindconf.sb_version, 0, 0 );
5145                         syncinfo_free( si, 0 ); 
5146                         return 1;
5147                 }
5148
5149                 if ( ldap_url_parse( si->si_bindconf.sb_uri.bv_val, &lud )) {
5150                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5151                                 "<%s> invalid URL", c->argv[0] );
5152                         Debug( LDAP_DEBUG_ANY, "%s: %s %s\n",
5153                                 c->log, c->cr_msg, si->si_bindconf.sb_uri.bv_val );
5154                         return 1;
5155                 }
5156
5157                 si->si_be = c->be;
5158                 if ( slapMode & SLAP_SERVER_MODE ) {
5159                         int isMe = 0;
5160                         /* check if consumer points to current server and database.
5161                          * If so, ignore this configuration.
5162                          */
5163                         if ( !SLAP_DBHIDDEN( c->be ) ) {
5164                                 int i;
5165                                 /* if searchbase doesn't match current DB suffix,
5166                                  * assume it's different
5167                                  */
5168                                 for ( i=0; !BER_BVISNULL( &c->be->be_nsuffix[i] ); i++ ) {
5169                                         if ( bvmatch( &si->si_base, &c->be->be_nsuffix[i] )) {
5170                                                 isMe = 1;
5171                                                 break;
5172                                         }
5173                                 }
5174                                 /* if searchbase matches, see if URLs match */
5175                                 if ( isMe && config_check_my_url( si->si_bindconf.sb_uri.bv_val,
5176                                                 lud ) == NULL )
5177                                         isMe = 0;
5178                         }
5179
5180                         if ( !isMe ) {
5181                                 init_syncrepl( si );
5182                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
5183                                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
5184                                         si->si_interval, do_syncrepl, si, "do_syncrepl",
5185                                         si->si_ridtxt );
5186                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
5187                                 if ( si->si_re )
5188                                         rc = config_sync_shadow( c ) ? -1 : 0;
5189                                 else
5190                                         rc = -1;
5191                         }
5192                 } else {
5193                         /* mirrormode still needs to see this flag in tool mode */
5194                         rc = config_sync_shadow( c ) ? -1 : 0;
5195                 }
5196                 ldap_free_urldesc( lud );
5197         }
5198
5199 #ifdef HAVE_TLS
5200         /* Use main slapd defaults */
5201         bindconf_tls_defaults( &si->si_bindconf );
5202 #endif
5203         if ( rc < 0 ) {
5204                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
5205                 syncinfo_free( si, 0 ); 
5206                 return 1;
5207         } else {
5208                 Debug( LDAP_DEBUG_CONFIG,
5209                         "Config: ** successfully added syncrepl %s \"%s\"\n",
5210                         si->si_ridtxt,
5211                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
5212                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0 );
5213                 if ( c->be->be_syncinfo ) {
5214                         syncinfo_t *sip;
5215
5216                         si->si_cookieState = c->be->be_syncinfo->si_cookieState;
5217
5218                         /* add new syncrepl to end of list (same order as when deleting) */
5219                         for ( sip = c->be->be_syncinfo; sip->si_next; sip = sip->si_next );
5220                         sip->si_next = si;
5221                 } else {
5222                         si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
5223                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
5224                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_pmutex );
5225
5226                         c->be->be_syncinfo = si;
5227                 }
5228                 si->si_cookieState->cs_ref++;
5229
5230                 si->si_next = NULL;
5231
5232                 return 0;
5233         }
5234 }
5235
5236 static void
5237 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
5238 {
5239         struct berval bc, uri, bs;
5240         char buf[BUFSIZ*2], *ptr;
5241         ber_len_t len;
5242         int i;
5243 #       define WHATSLEFT        ((ber_len_t) (&buf[sizeof( buf )] - ptr))
5244
5245         BER_BVZERO( bv );
5246
5247         /* temporarily inhibit bindconf from printing URI */
5248         uri = si->si_bindconf.sb_uri;
5249         BER_BVZERO( &si->si_bindconf.sb_uri );
5250         si->si_bindconf.sb_version = 0;
5251         bindconf_unparse( &si->si_bindconf, &bc );
5252         si->si_bindconf.sb_uri = uri;
5253         si->si_bindconf.sb_version = LDAP_VERSION3;
5254
5255         ptr = buf;
5256         assert( si->si_rid >= 0 && si->si_rid <= SLAP_SYNC_RID_MAX );
5257         len = snprintf( ptr, WHATSLEFT, IDSTR "=%03d " PROVIDERSTR "=%s",
5258                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
5259         if ( len >= sizeof( buf ) ) return;
5260         ptr += len;
5261         if ( !BER_BVISNULL( &bc ) ) {
5262                 if ( WHATSLEFT <= bc.bv_len ) {
5263                         free( bc.bv_val );
5264                         return;
5265                 }
5266                 ptr = lutil_strcopy( ptr, bc.bv_val );
5267                 free( bc.bv_val );
5268         }
5269         if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
5270                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
5271                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
5272                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
5273                 *ptr++ = '"';
5274         }
5275         if ( !BER_BVISNULL( &si->si_base ) ) {
5276                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
5277                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
5278                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
5279                 *ptr++ = '"';
5280         }
5281 #ifdef ENABLE_REWRITE
5282         if ( !BER_BVISNULL( &si->si_suffixm ) ) {
5283                 if ( WHATSLEFT <= STRLENOF( " " SUFFIXMSTR "=\"" "\"" ) + si->si_suffixm.bv_len ) return;
5284                 ptr = lutil_strcopy( ptr, " " SUFFIXMSTR "=\"" );
5285                 ptr = lutil_strcopy( ptr, si->si_suffixm.bv_val );
5286                 *ptr++ = '"';
5287         }
5288 #endif
5289         if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
5290                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
5291                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
5292                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
5293                 *ptr++ = '"';
5294         }
5295         if ( !BER_BVISNULL( &si->si_logbase ) ) {
5296                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
5297                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
5298                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
5299                 *ptr++ = '"';
5300         }
5301         if ( ldap_pvt_scope2bv( si->si_scope, &bs ) == LDAP_SUCCESS ) {
5302                 if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + bs.bv_len ) return;
5303                 ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
5304                 ptr = lutil_strcopy( ptr, bs.bv_val );
5305         }
5306         if ( si->si_attrsonly ) {
5307                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
5308                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
5309         }
5310         if ( si->si_anfile ) {
5311                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
5312                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
5313                 ptr = lutil_strcopy( ptr, si->si_anfile );
5314                 *ptr++ = '"';
5315         } else if ( si->si_allattrs || si->si_allopattrs ||
5316                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
5317         {
5318                 char *old;
5319
5320                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
5321                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
5322                 old = ptr;
5323                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
5324                 if ( ptr == NULL ) return;
5325                 if ( si->si_allattrs ) {
5326                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
5327                         if ( old != ptr ) *ptr++ = ',';
5328                         *ptr++ = '*';
5329                 }
5330                 if ( si->si_allopattrs ) {
5331                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
5332                         if ( old != ptr ) *ptr++ = ',';
5333                         *ptr++ = '+';
5334                 }
5335                 *ptr++ = '"';
5336         }
5337         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
5338                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
5339                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
5340                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
5341                 if ( ptr == NULL ) return;
5342         }
5343         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
5344         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
5345         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
5346         
5347         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
5348         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
5349         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
5350                 "refreshAndPersist" : "refreshOnly" );
5351
5352         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
5353                 int dd, hh, mm, ss;
5354
5355                 dd = si->si_interval;
5356                 ss = dd % 60;
5357                 dd /= 60;
5358                 mm = dd % 60;
5359                 dd /= 60;
5360                 hh = dd % 24;
5361                 dd /= 24;
5362                 len = snprintf( ptr, WHATSLEFT, " %s=%02d:%02d:%02d:%02d",
5363                         INTERVALSTR, dd, hh, mm, ss );
5364                 if ( len >= WHATSLEFT ) return;
5365                 ptr += len;
5366         }
5367
5368         if ( si->si_got & GOT_RETRY ) {
5369                 const char *space = "";
5370                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
5371                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
5372                 for (i=0; si->si_retryinterval[i]; i++) {
5373                         len = snprintf( ptr, WHATSLEFT, "%s%ld ", space,
5374                                 (long) si->si_retryinterval[i] );
5375                         space = " ";
5376                         if ( WHATSLEFT - 1 <= len ) return;
5377                         ptr += len;
5378                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
5379                                 *ptr++ = '+';
5380                         else {
5381                                 len = snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
5382                                 if ( WHATSLEFT <= len ) return;
5383                                 ptr += len;
5384                         }
5385                 }
5386                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
5387                 *ptr++ = '"';
5388         } else {
5389                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=undefined" );
5390         }
5391
5392         if ( si->si_slimit ) {
5393                 len = snprintf( ptr, WHATSLEFT, " " SLIMITSTR "=%d", si->si_slimit );
5394                 if ( WHATSLEFT <= len ) return;
5395                 ptr += len;
5396         }
5397
5398         if ( si->si_tlimit ) {
5399                 len = snprintf( ptr, WHATSLEFT, " " TLIMITSTR "=%d", si->si_tlimit );
5400                 if ( WHATSLEFT <= len ) return;
5401                 ptr += len;
5402         }
5403
5404         if ( si->si_syncdata ) {
5405                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
5406                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
5407                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
5408                         ptr = lutil_strcopy( ptr, bc.bv_val );
5409                 }
5410         }
5411         bc.bv_len = ptr - buf;
5412         bc.bv_val = buf;
5413         ber_dupbv( bv, &bc );
5414 }
5415
5416 int
5417 syncrepl_config( ConfigArgs *c )
5418 {
5419         if (c->op == SLAP_CONFIG_EMIT) {
5420                 if ( c->be->be_syncinfo ) {
5421                         struct berval bv;
5422                         syncinfo_t *si;
5423
5424                         for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
5425                                 syncrepl_unparse( si, &bv ); 
5426                                 ber_bvarray_add( &c->rvalue_vals, &bv );
5427                         }
5428                         return 0;
5429                 }
5430                 return 1;
5431         } else if ( c->op == LDAP_MOD_DELETE ) {
5432                 int isrunning = 0;
5433                 if ( c->be->be_syncinfo ) {
5434                         syncinfo_t *si, **sip;
5435                         int i;
5436
5437                         for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
5438                                 si = *sip;
5439                                 if ( c->valx == -1 || i == c->valx ) {
5440                                         *sip = si->si_next;
5441                                         si->si_ctype = -1;
5442                                         si->si_next = NULL;
5443                                         /* If the task is currently active, we have to leave
5444                                          * it running. It will exit on its own. This will only
5445                                          * happen when running on the cn=config DB.
5446                                          */
5447                                         if ( si->si_re ) {
5448                                                 if ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
5449                                                         isrunning = 1;
5450                                                 } else {
5451                                                         /* There is no active thread, but we must still
5452                                                          * ensure that no thread is (or will be) queued
5453                                                          * while we removes the task.
5454                                                          */
5455                                                         struct re_s *re = si->si_re;
5456                                                         si->si_re = NULL;
5457
5458                                                         if ( si->si_conn ) {
5459                                                                 connection_client_stop( si->si_conn );
5460                                                                 si->si_conn = NULL;
5461                                                         }
5462
5463                                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
5464                                                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) ) {
5465                                                                 ldap_pvt_runqueue_stoptask( &slapd_rq, re );
5466                                                                 isrunning = 1;
5467                                                         }
5468                                                         ldap_pvt_runqueue_remove( &slapd_rq, re );
5469                                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
5470
5471                                                         if ( ldap_pvt_thread_pool_retract( &connection_pool,
5472                                                                         re->routine, re ) > 0 )
5473                                                                 isrunning = 0;
5474
5475                                                         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
5476                                                 }
5477                                         }
5478                                         if ( !isrunning ) {
5479                                                 syncinfo_free( si, 0 );
5480                                         }
5481                                         if ( i == c->valx )
5482                                                 break;
5483                                 } else {
5484                                         sip = &si->si_next;
5485                                 }
5486                         }
5487                 }
5488                 if ( !c->be->be_syncinfo ) {
5489                         SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_SHADOW_MASK;
5490                 }
5491                 return 0;
5492         }
5493         if ( SLAP_SLURP_SHADOW( c->be ) ) {
5494                 Debug(LDAP_DEBUG_ANY, "%s: "
5495                         "syncrepl: database already shadowed.\n",
5496                         c->log, 0, 0);
5497                 return(1);
5498         } else {
5499                 return add_syncrepl( c );
5500         }
5501 }