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