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