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