]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
rework controls API
[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-2007 The OpenLDAP Foundation.
6  * Portions Copyright 2003 by IBM Corporation.
7  * Portions Copyright 2003 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 struct nonpresent_entry {
35         struct berval *npe_name;
36         struct berval *npe_nname;
37         LDAP_LIST_ENTRY(nonpresent_entry) npe_link;
38 };
39
40 typedef struct cookie_state {
41         ldap_pvt_thread_mutex_t cs_mutex;
42         int     cs_num;
43         int cs_age;
44         struct berval *cs_vals;
45         int *cs_sids;
46 } cookie_state;
47         
48 #define SYNCDATA_DEFAULT        0       /* entries are plain LDAP entries */
49 #define SYNCDATA_ACCESSLOG      1       /* entries are accesslog format */
50 #define SYNCDATA_CHANGELOG      2       /* entries are changelog format */
51
52 #define SYNCLOG_LOGGING         0       /* doing a log-based update */
53 #define SYNCLOG_FALLBACK        1       /* doing a full refresh */
54
55 #define RETRYNUM_FOREVER        (-1)    /* retry forever */
56 #define RETRYNUM_TAIL           (-2)    /* end of retrynum array */
57 #define RETRYNUM_VALID(n)       ((n) >= RETRYNUM_FOREVER)       /* valid retrynum */
58 #define RETRYNUM_FINITE(n)      ((n) > RETRYNUM_FOREVER)        /* not forever */
59
60 typedef struct syncinfo_s {
61         struct syncinfo_s       *si_next;
62         BackendDB               *si_be;
63         BackendDB               *si_wbe;
64         struct re_s             *si_re;
65         int                     si_rid;
66         char                    si_ridtxt[8];
67         slap_bindconf           si_bindconf;
68         struct berval           si_base;
69         struct berval           si_logbase;
70         struct berval           si_filterstr;
71         struct berval           si_logfilterstr;
72         int                     si_scope;
73         int                     si_attrsonly;
74         char                    *si_anfile;
75         AttributeName           *si_anlist;
76         AttributeName           *si_exanlist;
77         char                    **si_attrs;
78         char                    **si_exattrs;
79         int                     si_allattrs;
80         int                     si_allopattrs;
81         int                     si_schemachecking;
82         int                     si_type;        /* the active type */
83         int                     si_ctype;       /* the configured type */
84         time_t                  si_interval;
85         time_t                  *si_retryinterval;
86         int                     *si_retrynum_init;
87         int                     *si_retrynum;
88         struct sync_cookie      si_syncCookie;
89         cookie_state            *si_cookieState;
90         int                     si_cookieAge;
91         int                     si_manageDSAit;
92         int                     si_slimit;
93         int                     si_tlimit;
94         int                     si_refreshDelete;
95         int                     si_refreshPresent;
96         int                     si_syncdata;
97         int                     si_logstate;
98         int                     si_conn_setup;
99         Avlnode                 *si_presentlist;
100         LDAP                    *si_ld;
101         LDAP_LIST_HEAD(np, nonpresent_entry)    si_nonpresentlist;
102         ldap_pvt_thread_mutex_t si_mutex;
103 } syncinfo_t;
104
105 static int syncuuid_cmp( const void *, const void * );
106 static void avl_ber_bvfree( void * );
107 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray, struct berval * );
108 static int syncrepl_message_to_op(
109                                         syncinfo_t *, Operation *, LDAPMessage * );
110 static int syncrepl_message_to_entry(
111                                         syncinfo_t *, Operation *, LDAPMessage *,
112                                         Modifications **, Entry **, int );
113 static int syncrepl_entry(
114                                         syncinfo_t *, Operation*, Entry*,
115                                         Modifications**,int, struct berval* );
116 static int syncrepl_updateCookie(
117                                         syncinfo_t *, Operation *, struct berval *,
118                                         struct sync_cookie * );
119 static struct berval * slap_uuidstr_from_normalized(
120                                         struct berval *, struct berval *, void * );
121
122 /* callback functions */
123 static int dn_callback( Operation *, SlapReply * );
124 static int nonpresent_callback( Operation *, SlapReply * );
125 static int null_callback( Operation *, SlapReply * );
126
127 static AttributeDescription *sync_descs[4];
128
129 static void
130 init_syncrepl(syncinfo_t *si)
131 {
132         int i, j, k, l, n;
133         char **attrs, **exattrs;
134
135         if ( !sync_descs[0] ) {
136                 sync_descs[0] = slap_schema.si_ad_objectClass;
137                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
138                 sync_descs[2] = slap_schema.si_ad_entryCSN;
139                 sync_descs[3] = NULL;
140         }
141
142         if ( si->si_allattrs && si->si_allopattrs )
143                 attrs = NULL;
144         else
145                 attrs = anlist2attrs( si->si_anlist );
146
147         if ( attrs ) {
148                 if ( si->si_allattrs ) {
149                         i = 0;
150                         while ( attrs[i] ) {
151                                 if ( !is_at_operational( at_find( attrs[i] ) ) ) {
152                                         for ( j = i; attrs[j] != NULL; j++ ) {
153                                                 if ( j == i )
154                                                         ch_free( attrs[i] );
155                                                 attrs[j] = attrs[j+1];
156                                         }
157                                 } else {
158                                         i++;
159                                 }
160                         }
161                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
162                         attrs[i] = ch_strdup("*");
163                         attrs[i + 1] = NULL;
164
165                 } else if ( si->si_allopattrs ) {
166                         i = 0;
167                         while ( attrs[i] ) {
168                                 if ( is_at_operational( at_find( attrs[i] ) ) ) {
169                                         for ( j = i; attrs[j] != NULL; j++ ) {
170                                                 if ( j == i )
171                                                         ch_free( attrs[i] );
172                                                 attrs[j] = attrs[j+1];
173                                         }
174                                 } else {
175                                         i++;
176                                 }
177                         }
178                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
179                         attrs[i] = ch_strdup("+");
180                         attrs[i + 1] = NULL;
181                 }
182
183                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
184                         j = 0;
185                         while ( attrs[j] ) {
186                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
187                                         for ( k = j; attrs[k] != NULL; k++ ) {
188                                                 if ( k == j )
189                                                         ch_free( attrs[k] );
190                                                 attrs[k] = attrs[k+1];
191                                         }
192                                 } else {
193                                         j++;
194                                 }
195                         }
196                 }
197
198                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
199
200                 if ( si->si_allopattrs ) {
201                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ) );
202                 } else {
203                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ) );
204                 }
205
206                 /* Add Attributes */
207                 if ( si->si_allopattrs ) {
208                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
209                 } else {
210                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
211                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
212                         }
213                 }
214                 attrs[ n ] = NULL;
215
216         } else {
217
218                 i = 0;
219                 if ( si->si_allattrs == si->si_allopattrs ) {
220                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
221                         attrs[i++] = ch_strdup( "*" );
222                         attrs[i++] = ch_strdup( "+" );
223                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
224                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
225                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
226                         attrs[i++] = ch_strdup( "*" );
227                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
228                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
229                         }
230                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
231                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
232                         attrs[i++] = ch_strdup( "+" );
233                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
234                 }
235                 attrs[i] = NULL;
236         }
237         
238         si->si_attrs = attrs;
239
240         exattrs = anlist2attrs( si->si_exanlist );
241
242         if ( exattrs ) {
243                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
244
245                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
246                         j = 0;
247                         while ( exattrs[j] != NULL ) {
248                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
249                                         ch_free( exattrs[j] );
250                                         for ( k = j; exattrs[k] != NULL; k++ ) {
251                                                 exattrs[k] = exattrs[k+1];
252                                         }
253                                 } else {
254                                         j++;
255                                 }
256                         }
257                 }
258
259                 for ( i = 0; exattrs[i] != NULL; i++ ) {
260                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
261                                 ObjectClass     *oc;
262                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
263                                         k = 0;
264                                         while ( oc->soc_required[k] ) {
265                                                 if ( !strcmp( exattrs[i],
266                                                          oc->soc_required[k]->sat_cname.bv_val ) ) {
267                                                         ch_free( exattrs[i] );
268                                                         for ( l = i; exattrs[l]; l++ ) {
269                                                                 exattrs[l] = exattrs[l+1];
270                                                         }
271                                                 } else {
272                                                         k++;
273                                                 }
274                                         }
275                                 }
276                         }
277                 }
278
279                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
280
281                 if ( i != n )
282                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *) );
283         }
284
285         si->si_exattrs = exattrs;       
286 }
287
288 typedef struct logschema {
289         struct berval ls_dn;
290         struct berval ls_req;
291         struct berval ls_mod;
292         struct berval ls_newRdn;
293         struct berval ls_delRdn;
294         struct berval ls_newSup;
295 } logschema;
296
297 static logschema changelog_sc = {
298         BER_BVC("targetDN"),
299         BER_BVC("changeType"),
300         BER_BVC("changes"),
301         BER_BVC("newRDN"),
302         BER_BVC("deleteOldRDN"),
303         BER_BVC("newSuperior")
304 };
305
306 static logschema accesslog_sc = {
307         BER_BVC("reqDN"),
308         BER_BVC("reqType"),
309         BER_BVC("reqMod"),
310         BER_BVC("reqNewRDN"),
311         BER_BVC("reqDeleteOldRDN"),
312         BER_BVC("reqNewSuperior")
313 };
314
315 static int
316 ldap_sync_search(
317         syncinfo_t *si,
318         void *ctx )
319 {
320         BerElementBuffer berbuf;
321         BerElement *ber = (BerElement *)&berbuf;
322         LDAPControl c[2], *ctrls[3];
323         ber_int_t       msgid;
324         int rc;
325         int rhint;
326         char *base;
327         char **attrs, *lattrs[8];
328         char *filter;
329         int attrsonly;
330         int scope;
331
332         /* setup LDAP SYNC control */
333         ber_init2( ber, NULL, LBER_USE_DER );
334         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
335
336         /* If we're using a log but we have no state, then fallback to
337          * normal mode for a full refresh.
338          */
339         if ( si->si_syncdata && !si->si_syncCookie.numcsns ) {
340                 si->si_logstate = SYNCLOG_FALLBACK;
341         }
342
343         /* Use the log parameters if we're in log mode */
344         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
345                 logschema *ls;
346                 if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
347                         ls = &accesslog_sc;
348                 else
349                         ls = &changelog_sc;
350                 lattrs[0] = ls->ls_dn.bv_val;
351                 lattrs[1] = ls->ls_req.bv_val;
352                 lattrs[2] = ls->ls_mod.bv_val;
353                 lattrs[3] = ls->ls_newRdn.bv_val;
354                 lattrs[4] = ls->ls_delRdn.bv_val;
355                 lattrs[5] = ls->ls_newSup.bv_val;
356                 lattrs[6] = slap_schema.si_ad_entryCSN->ad_cname.bv_val;
357                 lattrs[7] = NULL;
358
359                 rhint = 0;
360                 base = si->si_logbase.bv_val;
361                 filter = si->si_logfilterstr.bv_val;
362                 attrs = lattrs;
363                 attrsonly = 0;
364                 scope = LDAP_SCOPE_SUBTREE;
365         } else {
366                 rhint = 1;
367                 base = si->si_base.bv_val;
368                 filter = si->si_filterstr.bv_val;
369                 attrs = si->si_attrs;
370                 attrsonly = si->si_attrsonly;
371                 scope = si->si_scope;
372         }
373         if ( si->si_syncdata && si->si_logstate == SYNCLOG_FALLBACK ) {
374                 si->si_type = LDAP_SYNC_REFRESH_ONLY;
375         } else {
376                 si->si_type = si->si_ctype;
377         }
378
379         if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
380         {
381                 ber_printf( ber, "{eOb}",
382                         abs(si->si_type), &si->si_syncCookie.octet_str, rhint );
383         } else {
384                 ber_printf( ber, "{eb}",
385                         abs(si->si_type), rhint );
386         }
387
388         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 ) ) == LBER_ERROR ) {
389                 ber_free_buf( ber );
390                 return rc;
391         }
392
393         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
394         c[0].ldctl_iscritical = si->si_type < 0;
395         ctrls[0] = &c[0];
396
397         if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
398                 c[1].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
399                 c[1].ldctl_value = si->si_bindconf.sb_authzId;
400                 c[1].ldctl_iscritical = 1;
401                 ctrls[1] = &c[1];
402                 ctrls[2] = NULL;
403         } else {
404                 ctrls[1] = NULL;
405         }
406
407         rc = ldap_search_ext( si->si_ld, base, scope, filter, attrs, attrsonly,
408                 ctrls, NULL, NULL, si->si_slimit, &msgid );
409         ber_free_buf( ber );
410         return rc;
411 }
412
413 static int
414 do_syncrep1(
415         Operation *op,
416         syncinfo_t *si )
417 {
418         int     rc;
419         int cmdline_cookie_found = 0;
420
421         struct sync_cookie      *sc = NULL;
422 #ifdef HAVE_TLS
423         void    *ssl;
424 #endif
425
426         rc = slap_client_connect( &si->si_ld, &si->si_bindconf );
427         if ( rc != LDAP_SUCCESS ) {
428                 goto done;
429         }
430         op->o_protocol = LDAP_VERSION3;
431
432         /* Set SSF to strongest of TLS, SASL SSFs */
433         op->o_sasl_ssf = 0;
434         op->o_tls_ssf = 0;
435         op->o_transport_ssf = 0;
436 #ifdef HAVE_TLS
437         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
438                 == LDAP_SUCCESS && ssl != NULL )
439         {
440                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
441         }
442 #endif /* HAVE_TLS */
443         ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &op->o_sasl_ssf );
444         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
445                 ?  op->o_sasl_ssf : op->o_tls_ssf;
446
447         ldap_set_option( si->si_ld, LDAP_OPT_TIMELIMIT, &si->si_tlimit );
448
449         /* We've just started up, or the remote server hasn't sent us
450          * any meaningful state.
451          */
452         if ( BER_BVISNULL( &si->si_syncCookie.octet_str ) ) {
453                 int i;
454
455                 si->si_syncCookie.rid = si->si_rid;
456                 si->si_syncCookie.sid = SLAP_SINGLE_SHADOW( si->si_be ) ? -1 :
457                         slap_serverID;
458
459                 LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
460                         if ( si->si_rid == sc->rid ) {
461                                 cmdline_cookie_found = 1;
462                                 break;
463                         }
464                 }
465
466                 if ( cmdline_cookie_found ) {
467                         /* cookie is supplied in the command line */
468
469                         LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
470
471                         /* ctxcsn wasn't parsed yet, do it now */
472                         slap_parse_sync_cookie( sc, op->o_tmpmemctx );
473                         slap_sync_cookie_free( &si->si_syncCookie, 0 );
474                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
475                         slap_sync_cookie_free( sc, 1 );
476                 } else {
477                         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
478                         if ( !si->si_cookieState->cs_num ) {
479                                 /* get contextCSN shadow replica from database */
480                                 BerVarray csn = NULL;
481                                 void *ctx = op->o_tmpmemctx;
482
483                                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
484                                 op->o_req_dn = op->o_req_ndn;
485
486                                 /* try to read stored contextCSN */
487                                 op->o_tmpmemctx = NULL;
488                                 backend_attribute( op, NULL, &op->o_req_ndn,
489                                         slap_schema.si_ad_contextCSN, &csn, ACL_READ );
490                                 op->o_tmpmemctx = ctx;
491                                 if ( csn ) {
492                                         si->si_cookieState->cs_vals = csn;
493                                         for (i=0; !BER_BVISNULL( &csn[i] ); i++);
494                                         si->si_cookieState->cs_num = i;
495                                         si->si_cookieState->cs_sids = slap_parse_csn_sids( csn, i, NULL );
496                                 }
497                         }
498                         if ( si->si_cookieState->cs_num ) {
499                                 ber_bvarray_free( si->si_syncCookie.ctxcsn );
500                                 if ( ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
501                                         si->si_cookieState->cs_vals, NULL )) {
502                                         rc = LDAP_NO_MEMORY;
503                                         goto done;
504                                 }
505                                 si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
506                                 si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num *
507                                         sizeof(int) );
508                                 for ( i=0; i<si->si_syncCookie.numcsns; i++ )
509                                         si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
510                         }
511                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
512                 }
513
514                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
515                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
516                         si->si_syncCookie.sid );
517         } else {
518                 AttributeName at[2];
519                 Attribute a = {0};
520                 Entry e = {0};
521                 SlapReply rs = {0};
522                 int i, j, changed = 0;
523
524                 /* Look for contextCSN from syncprov overlay. If
525                  * there's no overlay, this will be a no-op. That means
526                  * this is a pure consumer, so local changes will not be
527                  * allowed, and all changes will already be reflected in
528                  * the cookieState.
529                  */
530                 a.a_desc = slap_schema.si_ad_contextCSN;
531                 e.e_attrs = &a;
532                 e.e_name = si->si_wbe->be_suffix[0];
533                 e.e_nname = si->si_wbe->be_nsuffix[0];
534                 rs.sr_entry = &e;
535                 rs.sr_flags = REP_ENTRY_MODIFIABLE;
536                 at[0].an_name = a.a_desc->ad_cname;
537                 at[0].an_desc = a.a_desc;
538                 BER_BVZERO( &at[1].an_name );
539                 op->o_req_dn = e.e_name;
540                 op->o_req_ndn = e.e_nname;
541
542                 ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
543                 rc = backend_operational( op, &rs );
544                 if ( rc == LDAP_SUCCESS && a.a_vals ) {
545                         int num;
546                         for (i=0; !BER_BVISNULL( &a.a_vals[i] ); i++) ;
547                         num = i;
548                         /* check for differences */
549                         if ( num != si->si_cookieState->cs_num ) {
550                                 changed = 1;
551                         } else {
552                                 for ( i=0; i<num; i++ ) {
553                                         if ( ber_bvcmp( &a.a_vals[i],
554                                                 &si->si_cookieState->cs_vals[i] )) {
555                                                 changed =1;
556                                                 break;
557                                         }
558                                 }
559                         }
560                         if ( changed ) {
561                                 ber_bvarray_free( si->si_cookieState->cs_vals );
562                                 ch_free( si->si_cookieState->cs_sids );
563                                 si->si_cookieState->cs_num = num;
564                                 si->si_cookieState->cs_vals = a.a_vals;
565                                 si->si_cookieState->cs_sids = slap_parse_csn_sids( a.a_vals,
566                                         num, NULL );
567                                 si->si_cookieState->cs_age++;
568                         } else {
569                                 ber_bvarray_free( a.a_vals );
570                         }
571                         changed = 0;
572                 }
573                 /* See if the cookieState has changed due to anything outside
574                  * this particular consumer. That includes other consumers in
575                  * the same context, or local changes detected above.
576                  */
577                 if ( si->si_cookieState->cs_num > 1 && si->si_cookieAge !=
578                         si->si_cookieState->cs_age ) {
579
580                         for (i=0; !BER_BVISNULL( &si->si_syncCookie.ctxcsn[i] ); i++) {
581                                 /* bogus, just dup everything */
582                                 if ( si->si_syncCookie.sids[i] == -1 ) {
583                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
584                                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
585                                                 si->si_cookieState->cs_vals, NULL );
586                                         changed = 1;
587                                         break;
588                                 }
589                                 for (j=0; j<si->si_cookieState->cs_num; j++) {
590                                         if ( si->si_syncCookie.sids[i] !=
591                                                 si->si_cookieState->cs_sids[j] )
592                                                 continue;
593                                         if ( bvmatch( &si->si_syncCookie.ctxcsn[i],
594                                                 &si->si_cookieState->cs_vals[j] ))
595                                                 break;
596                                         ber_bvreplace( &si->si_syncCookie.ctxcsn[i],
597                                                 &si->si_cookieState->cs_vals[j] );
598                                         changed = 1;
599                                         break;
600                                 }
601                         }
602                         if ( changed ) {
603                                 ch_free( si->si_syncCookie.octet_str.bv_val );
604                                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
605                                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
606                                         SLAP_SINGLE_SHADOW( si->si_be ) ? -1 : slap_serverID );
607                         }
608                 }
609                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
610         }
611
612         rc = ldap_sync_search( si, op->o_tmpmemctx );
613
614         if( rc != LDAP_SUCCESS ) {
615                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s "
616                         "ldap_search_ext: %s (%d)\n",
617                         si->si_ridtxt, ldap_err2string( rc ), rc );
618         }
619
620 done:
621         if ( rc ) {
622                 if ( si->si_ld ) {
623                         ldap_unbind_ext( si->si_ld, NULL, NULL );
624                         si->si_ld = NULL;
625                 }
626         }
627
628         return rc;
629 }
630
631 static int
632 compare_csns( struct sync_cookie *sc1, struct sync_cookie *sc2, int *which )
633 {
634         int i, j, match = 0;
635         const char *text;
636
637         *which = 0;
638
639         if ( sc1->numcsns < sc2->numcsns ) {
640                 *which = sc1->numcsns;
641                 return -1;
642         }
643
644         for (i=0; !BER_BVISNULL( &sc1->ctxcsn[i] ); i++) {
645                 for (j=0; !BER_BVISNULL( &sc2->ctxcsn[j] ); j++) {
646                         if ( sc1->sids[i] != sc2->sids[j] )
647                                 continue;
648                         value_match( &match, slap_schema.si_ad_entryCSN,
649                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
650                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
651                                 &sc1->ctxcsn[i], &sc2->ctxcsn[i], &text );
652                         if ( match < 0 ) {
653                                 *which = j;
654                                 return match;
655                         }
656                         break;
657                 }
658         }
659         return match;
660 }
661
662 static int
663 do_syncrep2(
664         Operation *op,
665         syncinfo_t *si )
666 {
667         LDAPControl     **rctrls = NULL;
668         LDAPControl     *rctrlp;
669
670         BerElementBuffer berbuf;
671         BerElement      *ber = (BerElement *)&berbuf;
672
673         LDAPMessage     *res = NULL;
674         LDAPMessage     *msg = NULL;
675
676         char            *retoid = NULL;
677         struct berval   *retdata = NULL;
678
679         Entry           *entry = NULL;
680
681         int             syncstate;
682         struct berval   syncUUID = BER_BVNULL;
683         struct sync_cookie      syncCookie = { NULL };
684         struct sync_cookie      syncCookie_req = { NULL };
685         struct berval           cookie = BER_BVNULL;
686
687         int             rc,
688                         err = LDAP_SUCCESS;
689         ber_len_t       len;
690
691         struct berval   *psub;
692         Modifications   *modlist = NULL;
693
694         int                             match, m;
695
696         struct timeval *tout_p = NULL;
697         struct timeval tout = { 0, 0 };
698
699         int             refreshDeletes = 0;
700         int             refreshDone = 1;
701         BerVarray syncUUIDs = NULL;
702         ber_tag_t si_tag;
703
704         if ( slapd_shutdown ) {
705                 rc = -2;
706                 goto done;
707         }
708
709         ber_init2( ber, NULL, LBER_USE_DER );
710         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
711
712         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2 %s\n", si->si_ridtxt, 0, 0 );
713
714         psub = &si->si_be->be_nsuffix[0];
715
716         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
717
718         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
719                 tout_p = &tout;
720         } else {
721                 tout_p = NULL;
722         }
723
724         while ( ( rc = ldap_result( si->si_ld, LDAP_RES_ANY, LDAP_MSG_ONE,
725                 tout_p, &res ) ) > 0 )
726         {
727                 if ( slapd_shutdown ) {
728                         rc = -2;
729                         goto done;
730                 }
731                 for( msg = ldap_first_message( si->si_ld, res );
732                         msg != NULL;
733                         msg = ldap_next_message( si->si_ld, msg ) )
734                 {
735                         if ( slapd_shutdown ) {
736                                 rc = -2;
737                                 goto done;
738                         }
739                         switch( ldap_msgtype( msg ) ) {
740                         case LDAP_RES_SEARCH_ENTRY:
741                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
742                                 /* we can't work without the control */
743                                 rctrlp = NULL;
744                                 if ( rctrls ) {
745                                         LDAPControl **next;
746                                         /* NOTE: make sure we use the right one;
747                                          * a better approach would be to run thru
748                                          * the whole list and take care of all */
749                                         rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_STATE, rctrls, &next );
750                                         if ( next && ldap_control_find( LDAP_CONTROL_SYNC_STATE, next, NULL ) )
751                                         {
752                                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
753                                                         "got search entry with multiple "
754                                                         "Sync State control\n", si->si_ridtxt, 0, 0 );
755                                                 rc = -1;
756                                                 goto done;
757                                         }
758                                 }
759                                 if ( rctrlp == NULL ) {
760                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
761                                                 "got search entry without "
762                                                 "Sync State control\n", si->si_ridtxt, 0, 0 );
763                                         rc = -1;
764                                         goto done;
765                                 }
766                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
767                                 ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
768                                 /* FIXME: what if syncUUID is NULL or empty?
769                                  * (happens with back-sql...) */
770                                 if ( BER_BVISEMPTY( &syncUUID ) ) {
771                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
772                                                 "got empty syncUUID\n", si->si_ridtxt, 0, 0 );
773                                         ldap_controls_free( rctrls );
774                                         rc = -1;
775                                         goto done;
776                                 }
777                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
778                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
779                                         if ( !BER_BVISNULL( &cookie ) ) {
780                                                 ch_free( syncCookie.octet_str.bv_val );
781                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
782                                         }
783                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
784                                         {
785                                                 slap_parse_sync_cookie( &syncCookie, NULL );
786                                         }
787                                 }
788                                 rc = 0;
789                                 if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
790                                         modlist = NULL;
791                                         if ( ( rc = syncrepl_message_to_op( si, op, msg ) ) == LDAP_SUCCESS &&
792                                                 syncCookie.ctxcsn )
793                                         {
794                                                 rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
795                                         }
796                                 } else if ( ( rc = syncrepl_message_to_entry( si, op, msg,
797                                         &modlist, &entry, syncstate ) ) == LDAP_SUCCESS )
798                                 {
799                                         if ( ( rc = syncrepl_entry( si, op, entry, &modlist,
800                                                 syncstate, &syncUUID ) ) == LDAP_SUCCESS &&
801                                                 syncCookie.ctxcsn )
802                                         {
803                                                 rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
804                                         }
805                                 }
806                                 ldap_controls_free( rctrls );
807                                 if ( modlist ) {
808                                         slap_mods_free( modlist, 1 );
809                                 }
810                                 if ( rc )
811                                         goto done;
812                                 break;
813
814                         case LDAP_RES_SEARCH_REFERENCE:
815                                 Debug( LDAP_DEBUG_ANY,
816                                         "do_syncrep2: %s reference received error\n",
817                                         si->si_ridtxt, 0, 0 );
818                                 break;
819
820                         case LDAP_RES_SEARCH_RESULT:
821                                 Debug( LDAP_DEBUG_SYNC,
822                                         "do_syncrep2: %s LDAP_RES_SEARCH_RESULT\n",
823                                         si->si_ridtxt, 0, 0 );
824                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
825                                         &rctrls, 0 );
826 #ifdef LDAP_X_SYNC_REFRESH_REQUIRED
827                                 if ( err == LDAP_X_SYNC_REFRESH_REQUIRED ) {
828                                         /* map old result code to registered code */
829                                         err = LDAP_SYNC_REFRESH_REQUIRED;
830                                 }
831 #endif
832                                 if ( err == LDAP_SYNC_REFRESH_REQUIRED ) {
833                                         if ( si->si_logstate == SYNCLOG_LOGGING ) {
834                                                 si->si_logstate = SYNCLOG_FALLBACK;
835                                         }
836                                         rc = err;
837                                         goto done;
838                                 }
839                                 if ( rctrls ) {
840                                         rctrlp = *rctrls;
841                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
842
843                                         ber_scanf( ber, "{" /*"}"*/);
844                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
845                                                 ber_scanf( ber, "m", &cookie );
846                                                 if ( !BER_BVISNULL( &cookie ) ) {
847                                                         ch_free( syncCookie.octet_str.bv_val );
848                                                         ber_dupbv( &syncCookie.octet_str, &cookie);
849                                                 }
850                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
851                                                 {
852                                                         slap_parse_sync_cookie( &syncCookie, NULL );
853                                                 }
854                                         }
855                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
856                                         {
857                                                 ber_scanf( ber, "b", &refreshDeletes );
858                                         }
859                                         ber_scanf( ber, /*"{"*/ "}" );
860                                 }
861                                 if ( !syncCookie.ctxcsn ) {
862                                         match = 1;
863                                 } else if ( !syncCookie_req.ctxcsn ) {
864                                         match = -1;
865                                         m = 0;
866                                 } else {
867                                         match = compare_csns( &syncCookie_req, &syncCookie, &m );
868                                 }
869                                 if ( rctrls ) {
870                                         ldap_controls_free( rctrls );
871                                 }
872                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
873                                         /* FIXME : different error behaviors according to
874                                          *      1) err code : LDAP_BUSY ...
875                                          *      2) on err policy : stop service, stop sync, retry
876                                          */
877                                         if ( refreshDeletes == 0 && match < 0 &&
878                                                 err == LDAP_SUCCESS )
879                                         {
880                                                 syncrepl_del_nonpresent( op, si, NULL,
881                                                         &syncCookie.ctxcsn[m] );
882                                         } else {
883                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
884                                                 si->si_presentlist = NULL;
885                                         }
886                                 }
887                                 if ( syncCookie.ctxcsn && match < 0 && err == LDAP_SUCCESS )
888                                 {
889                                         rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
890                                 }
891                                 if ( err == LDAP_SUCCESS
892                                         && si->si_logstate == SYNCLOG_FALLBACK ) {
893                                         si->si_logstate = SYNCLOG_LOGGING;
894                                         rc = LDAP_SYNC_REFRESH_REQUIRED;
895                                 } else {
896                                         rc = -2;
897                                 }
898                                 goto done;
899                                 break;
900
901                         case LDAP_RES_INTERMEDIATE:
902                                 rc = ldap_parse_intermediate( si->si_ld, msg,
903                                         &retoid, &retdata, NULL, 0 );
904                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
905                                         ber_init2( ber, retdata, LBER_USE_DER );
906
907                                         switch ( si_tag = ber_peek_tag( ber, &len ) ) {
908                                         ber_tag_t tag;
909                                         case LDAP_TAG_SYNC_NEW_COOKIE:
910                                                 Debug( LDAP_DEBUG_SYNC,
911                                                         "do_syncrep2: %s %s - %s\n", 
912                                                         si->si_ridtxt,
913                                                         "LDAP_RES_INTERMEDIATE", 
914                                                         "NEW_COOKIE" );
915                                                 ber_scanf( ber, "tm", &tag, &cookie );
916                                                 break;
917                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
918                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
919                                                 Debug( LDAP_DEBUG_SYNC,
920                                                         "do_syncrep2: %s %s - %s\n", 
921                                                         si->si_ridtxt,
922                                                         "LDAP_RES_INTERMEDIATE", 
923                                                         si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
924                                                         "REFRESH_PRESENT" : "REFRESH_DELETE" );
925                                                 if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
926                                                         si->si_refreshDelete = 1;
927                                                 } else {
928                                                         si->si_refreshPresent = 1;
929                                                 }
930                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
931                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
932                                                 {
933                                                         ber_scanf( ber, "m", &cookie );
934                                                         if ( !BER_BVISNULL( &cookie ) ) {
935                                                                 ch_free( syncCookie.octet_str.bv_val );
936                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
937                                                         }
938                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
939                                                         {
940                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
941                                                         }
942                                                 }
943                                                 if ( ber_peek_tag( ber, &len ) ==
944                                                         LDAP_TAG_REFRESHDONE )
945                                                 {
946                                                         ber_scanf( ber, "b", &refreshDone );
947                                                 }
948                                                 ber_scanf( ber, /*"{"*/ "}" );
949                                                 break;
950                                         case LDAP_TAG_SYNC_ID_SET:
951                                                 Debug( LDAP_DEBUG_SYNC,
952                                                         "do_syncrep2: %s %s - %s\n", 
953                                                         si->si_ridtxt,
954                                                         "LDAP_RES_INTERMEDIATE", 
955                                                         "SYNC_ID_SET" );
956                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
957                                                 if ( ber_peek_tag( ber, &len ) ==
958                                                         LDAP_TAG_SYNC_COOKIE )
959                                                 {
960                                                         ber_scanf( ber, "m", &cookie );
961                                                         if ( !BER_BVISNULL( &cookie ) ) {
962                                                                 ch_free( syncCookie.octet_str.bv_val );
963                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
964                                                         }
965                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
966                                                         {
967                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
968                                                                 compare_csns( &syncCookie_req, &syncCookie, &m );
969                                                         }
970                                                 }
971                                                 if ( ber_peek_tag( ber, &len ) ==
972                                                         LDAP_TAG_REFRESHDELETES )
973                                                 {
974                                                         ber_scanf( ber, "b", &refreshDeletes );
975                                                 }
976                                                 ber_scanf( ber, "[W]", &syncUUIDs );
977                                                 ber_scanf( ber, /*"{"*/ "}" );
978                                                 if ( refreshDeletes ) {
979                                                         syncrepl_del_nonpresent( op, si, syncUUIDs,
980                                                                 &syncCookie.ctxcsn[m] );
981                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
982                                                 } else {
983                                                         int i;
984                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
985                                                                 struct berval *syncuuid_bv;
986                                                                 syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
987                                                                 slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
988                                                                 if ( avl_insert( &si->si_presentlist,
989                                                                         (caddr_t) syncuuid_bv,
990                                                                         syncuuid_cmp, avl_dup_error ) )
991                                                                 {
992                                                                         ber_bvfree( syncuuid_bv );
993                                                                 }
994                                                         }
995                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
996                                                 }
997                                                 slap_sync_cookie_free( &syncCookie, 0 );
998                                                 break;
999                                         default:
1000                                                 Debug( LDAP_DEBUG_ANY,
1001                                                         "do_syncrep2: %s unknown syncinfo tag (%ld)\n",
1002                                                         si->si_ridtxt, (long) si_tag, 0 );
1003                                                 ldap_memfree( retoid );
1004                                                 ber_bvfree( retdata );
1005                                                 continue;
1006                                         }
1007
1008                                         if ( !syncCookie.ctxcsn ) {
1009                                                 match = 1;
1010                                         } else if ( !syncCookie_req.ctxcsn ) {
1011                                                 match = -1;
1012                                                 m = 0;
1013                                         } else {
1014                                                 match = compare_csns( &syncCookie_req, &syncCookie, &m );
1015                                         }
1016
1017                                         if ( match < 0 ) {
1018                                                 if ( si->si_refreshPresent == 1 ) {
1019                                                         syncrepl_del_nonpresent( op, si, NULL,
1020                                                                 &syncCookie.ctxcsn[m] );
1021                                                 }
1022
1023                                                 if ( syncCookie.ctxcsn )
1024                                                 {
1025                                                         rc = syncrepl_updateCookie( si, op, psub, &syncCookie);
1026                                                 }
1027                                         } 
1028
1029                                         ldap_memfree( retoid );
1030                                         ber_bvfree( retdata );
1031                                         break;
1032
1033                                 } else {
1034                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1035                                                 "unknown intermediate response (%d)\n",
1036                                                 si->si_ridtxt, rc, 0 );
1037                                         ldap_memfree( retoid );
1038                                         ber_bvfree( retdata );
1039                                         break;
1040                                 }
1041                                 break;
1042
1043                         default:
1044                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1045                                         "unknown message\n", si->si_ridtxt, 0, 0 );
1046                                 break;
1047
1048                         }
1049                         if ( !BER_BVISNULL( &syncCookie.octet_str ) ) {
1050                                 slap_sync_cookie_free( &syncCookie_req, 0 );
1051                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
1052                                 slap_sync_cookie_free( &syncCookie, 0 );
1053                         }
1054                 }
1055                 ldap_msgfree( res );
1056                 res = NULL;
1057         }
1058
1059         if ( rc == -1 ) {
1060                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
1061                 err = rc;
1062         }
1063
1064 done:
1065         if ( err != LDAP_SUCCESS ) {
1066                 Debug( LDAP_DEBUG_ANY,
1067                         "do_syncrep2: %s (%d) %s\n",
1068                         si->si_ridtxt, err, ldap_err2string( err ) );
1069         }
1070
1071         slap_sync_cookie_free( &syncCookie, 0 );
1072         slap_sync_cookie_free( &syncCookie_req, 0 );
1073
1074         if ( res ) ldap_msgfree( res );
1075
1076         if ( rc && rc != LDAP_SYNC_REFRESH_REQUIRED && si->si_ld ) {
1077                 if ( si->si_conn_setup ) {
1078                         ber_socket_t s;
1079                         ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1080                         connection_client_stop( s );
1081                         si->si_conn_setup = 0;
1082                 }
1083                 ldap_unbind_ext( si->si_ld, NULL, NULL );
1084                 si->si_ld = NULL;
1085         }
1086
1087         return rc;
1088 }
1089
1090 static void *
1091 do_syncrepl(
1092         void    *ctx,
1093         void    *arg )
1094 {
1095         struct re_s* rtask = arg;
1096         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
1097         Connection conn = {0};
1098         OperationBuffer opbuf;
1099         Operation *op;
1100         int rc = LDAP_SUCCESS;
1101         int dostop = 0;
1102         ber_socket_t s;
1103         int i, defer = 1, fail = 0;
1104         Backend *be;
1105
1106         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl %s\n", si->si_ridtxt, 0, 0 );
1107
1108         if ( si == NULL )
1109                 return NULL;
1110
1111         ldap_pvt_thread_mutex_lock( &si->si_mutex );
1112
1113         switch( abs( si->si_type ) ) {
1114         case LDAP_SYNC_REFRESH_ONLY:
1115         case LDAP_SYNC_REFRESH_AND_PERSIST:
1116                 break;
1117         default:
1118                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1119                 return NULL;
1120         }
1121
1122         if ( slapd_shutdown ) {
1123                 if ( si->si_ld ) {
1124                         if ( si->si_conn_setup ) {
1125                                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1126                                 connection_client_stop( s );
1127                                 si->si_conn_setup = 0;
1128                         }
1129                         ldap_unbind_ext( si->si_ld, NULL, NULL );
1130                         si->si_ld = NULL;
1131                 }
1132                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1133                 return NULL;
1134         }
1135
1136         connection_fake_init( &conn, &opbuf, ctx );
1137         op = &opbuf.ob_op;
1138
1139         /* use global malloc for now */
1140         op->o_tmpmemctx = NULL;
1141         op->o_tmpmfuncs = &ch_mfuncs;
1142
1143         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1144         op->o_bd = be = si->si_be;
1145         op->o_dn = op->o_bd->be_rootdn;
1146         op->o_ndn = op->o_bd->be_rootndn;
1147         if ( !si->si_schemachecking )
1148                 op->o_no_schema_check = 1;
1149
1150         /* If we're glued, send writes through the glue parent */
1151         if ( !si->si_wbe ) {
1152                 if ( SLAP_GLUE_SUBORDINATE( be )) {
1153                         si->si_wbe = select_backend( &be->be_nsuffix[0], 1 );
1154                 } else {
1155                         si->si_wbe = be;
1156                 }
1157         }
1158
1159         /* Establish session, do search */
1160         if ( !si->si_ld ) {
1161                 si->si_refreshDelete = 0;
1162                 si->si_refreshPresent = 0;
1163                 rc = do_syncrep1( op, si );
1164         }
1165
1166 reload:
1167         /* Process results */
1168         if ( rc == LDAP_SUCCESS ) {
1169                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1170
1171                 rc = do_syncrep2( op, si );
1172                 if ( rc == LDAP_SYNC_REFRESH_REQUIRED ) {
1173                         rc = ldap_sync_search( si, op->o_tmpmemctx );
1174                         goto reload;
1175                 }
1176
1177                 /* We got deleted while running on cn=config */
1178                 if ( !si->si_ctype ) {
1179                         if ( si->si_conn_setup )
1180                                 dostop = 1;
1181                         rc = -1;
1182                 }
1183
1184                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1185                         /* If we succeeded, enable the connection for further listening.
1186                          * If we failed, tear down the connection and reschedule.
1187                          */
1188                         if ( rc == LDAP_SUCCESS ) {
1189                                 if ( si->si_conn_setup ) {
1190                                         connection_client_enable( s );
1191                                 } else {
1192                                         rc = connection_client_setup( s, do_syncrepl, arg );
1193                                         if ( rc == 0 )
1194                                                 si->si_conn_setup = 1;
1195                                 } 
1196                         } else if ( si->si_conn_setup ) {
1197                                 dostop = 1;
1198                         }
1199                 } else {
1200                         if ( rc == -2 ) rc = 0;
1201                 }
1202         }
1203
1204         /* At this point, we have 4 cases:
1205          * 1) for any hard failure, give up and remove this task
1206          * 2) for ServerDown, reschedule this task to run
1207          * 3) for Refresh and Success, reschedule to run
1208          * 4) for Persist and Success, reschedule to defer
1209          */
1210         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1211
1212         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask ) ) {
1213                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1214         }
1215
1216         if ( dostop ) {
1217                 connection_client_stop( s );
1218         }
1219
1220         if ( rc == LDAP_SUCCESS ) {
1221                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1222                         defer = 0;
1223                 }
1224                 rtask->interval.tv_sec = si->si_interval;
1225                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1226                 if ( si->si_retrynum ) {
1227                         for ( i = 0; si->si_retrynum_init[i] != RETRYNUM_TAIL; i++ ) {
1228                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1229                         }
1230                         si->si_retrynum[i] = RETRYNUM_TAIL;
1231                 }
1232         } else {
1233                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1234                         if ( si->si_retrynum[i] == RETRYNUM_FOREVER || si->si_retrynum[i] == RETRYNUM_TAIL )
1235                                 break;
1236                 }
1237
1238                 if ( !si->si_ctype
1239                         || !si->si_retrynum || si->si_retrynum[i] == RETRYNUM_TAIL ) {
1240                         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1241                         fail = RETRYNUM_TAIL;
1242                 } else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1243                         if ( si->si_retrynum[i] > 0 )
1244                                 si->si_retrynum[i]--;
1245                         fail = si->si_retrynum[i];
1246                         rtask->interval.tv_sec = si->si_retryinterval[i];
1247                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1248                         slap_wake_listener();
1249                 }
1250         }
1251
1252         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1253         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1254
1255         if ( rc ) {
1256                 if ( fail == RETRYNUM_TAIL ) {
1257                         Debug( LDAP_DEBUG_ANY,
1258                                 "do_syncrepl: rid %03d quitting\n",
1259                                 si->si_rid, 0, 0 );
1260                 } else if ( fail > 0 ) {
1261                         Debug( LDAP_DEBUG_ANY,
1262                                 "do_syncrepl: rid %03d retrying (%d retries left)\n",
1263                                 si->si_rid, fail, 0 );
1264                 } else {
1265                         Debug( LDAP_DEBUG_ANY,
1266                                 "do_syncrepl: rid %03d retrying\n",
1267                                 si->si_rid, 0, 0 );
1268                 }
1269         }
1270
1271         /* Do final delete cleanup */
1272         if ( !si->si_ctype ) {
1273                 cookie_state *cs = NULL;
1274                 syncinfo_t **sip;
1275
1276                 cs = be->be_syncinfo->si_cookieState;
1277                 for ( sip = &be->be_syncinfo; *sip != si; sip = &(*sip)->si_next );
1278                 *sip = si->si_next;
1279                 syncinfo_free( si, 0 );
1280                 if ( !be->be_syncinfo ) {
1281                         SLAP_DBFLAGS( be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
1282                         if ( cs ) {
1283                                 ch_free( cs->cs_sids );
1284                                 ber_bvarray_free( cs->cs_vals );
1285                                 ldap_pvt_thread_mutex_destroy( &cs->cs_mutex );
1286                                 ch_free( cs );
1287                         }
1288                 }
1289         }
1290         return NULL;
1291 }
1292
1293 static slap_verbmasks modops[] = {
1294         { BER_BVC("add"), LDAP_REQ_ADD },
1295         { BER_BVC("delete"), LDAP_REQ_DELETE },
1296         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1297         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1298         { BER_BVNULL, 0 }
1299 };
1300
1301 static Modifications *
1302 syncrepl_accesslog_mods(
1303         syncinfo_t *si,
1304         struct berval *vals
1305 )
1306 {
1307         char *colon;
1308         const char *text;
1309         AttributeDescription *ad;
1310         struct berval bv, bv2;
1311         short op;
1312         Modifications *mod = NULL, *modlist = NULL, **modtail;
1313         int i;
1314
1315         modtail = &modlist;
1316
1317         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1318                 ad = NULL;
1319                 bv = vals[i];
1320
1321                 colon = ber_bvchr( &bv, ':' );
1322                 if ( !colon ) {
1323                         /* Invalid */
1324                         continue;
1325                 }
1326
1327                 bv.bv_len = colon - bv.bv_val;
1328                 if ( slap_bv2ad( &bv, &ad, &text ) ) {
1329                         /* Invalid */
1330                         continue;
1331                 }
1332
1333                 /* Ignore dynamically generated attrs */
1334                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1335                         continue;
1336                 }
1337
1338                 /* Ignore excluded attrs */
1339                 if ( ldap_charray_inlist( si->si_exattrs,
1340                         ad->ad_type->sat_cname.bv_val ) )
1341                 {
1342                         continue;
1343                 }
1344
1345                 switch(colon[1]) {
1346                 case '+':       op = LDAP_MOD_ADD; break;
1347                 case '-':       op = LDAP_MOD_DELETE; break;
1348                 case '=':       op = LDAP_MOD_REPLACE; break;
1349                 case '#':       op = LDAP_MOD_INCREMENT; break;
1350                 default:        continue;
1351                 }
1352
1353                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1354                         mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
1355                         mod->sml_flags = 0;
1356                         mod->sml_op = op;
1357                         mod->sml_next = NULL;
1358                         mod->sml_desc = ad;
1359                         mod->sml_type = ad->ad_cname;
1360                         mod->sml_values = NULL;
1361                         mod->sml_nvalues = NULL;
1362
1363                         *modtail = mod;
1364                         modtail = &mod->sml_next;
1365                 }
1366                 if ( colon[2] == ' ' ) {
1367                         bv.bv_val = colon + 3;
1368                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1369                         ber_dupbv( &bv2, &bv );
1370                         ber_bvarray_add( &mod->sml_values, &bv2 );
1371                 }
1372         }
1373         return modlist;
1374 }
1375
1376 static Modifications *
1377 syncrepl_changelog_mods(
1378         syncinfo_t *si,
1379         struct berval *vals
1380 )
1381 {
1382         return NULL;    /* FIXME */
1383 }
1384
1385 static int
1386 syncrepl_message_to_op(
1387         syncinfo_t      *si,
1388         Operation       *op,
1389         LDAPMessage     *msg
1390 )
1391 {
1392         BerElement      *ber = NULL;
1393         Modifications   *modlist = NULL;
1394         logschema *ls;
1395         SlapReply rs = { REP_RESULT };
1396         slap_callback cb = { NULL, null_callback, NULL, NULL };
1397
1398         const char      *text;
1399         char txtbuf[SLAP_TEXT_BUFLEN];
1400         size_t textlen = sizeof txtbuf;
1401
1402         struct berval   bdn, dn = BER_BVNULL, ndn;
1403         struct berval   bv, *bvals = NULL;
1404         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1405                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1406                 psup = BER_BVNULL, nsup = BER_BVNULL;
1407         int             rc, deleteOldRdn = 0, freeReqDn = 0;
1408
1409         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1410                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1411                         "Message type should be entry (%d)",
1412                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1413                 return -1;
1414         }
1415
1416         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1417                 ls = &accesslog_sc;
1418         else
1419                 ls = &changelog_sc;
1420
1421         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1422
1423         if ( rc != LDAP_SUCCESS ) {
1424                 Debug( LDAP_DEBUG_ANY,
1425                         "syncrepl_message_to_op: %s dn get failed (%d)",
1426                         si->si_ridtxt, rc, 0 );
1427                 return rc;
1428         }
1429
1430         op->o_tag = LBER_DEFAULT;
1431         op->o_bd = si->si_wbe;
1432
1433         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ) )
1434                 == LDAP_SUCCESS ) {
1435                 if ( bv.bv_val == NULL )
1436                         break;
1437
1438                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn ) ) {
1439                         bdn = bvals[0];
1440                         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1441                         ber_dupbv( &op->o_req_dn, &dn );
1442                         ber_dupbv( &op->o_req_ndn, &ndn );
1443                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1444                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1445                         freeReqDn = 1;
1446                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req ) ) {
1447                         int i = verb_to_mask( bvals[0].bv_val, modops );
1448                         if ( i < 0 ) {
1449                                 Debug( LDAP_DEBUG_ANY,
1450                                         "syncrepl_message_to_op: %s unknown op %s",
1451                                         si->si_ridtxt, bvals[0].bv_val, 0 );
1452                                 ch_free( bvals );
1453                                 rc = -1;
1454                                 goto done;
1455                         }
1456                         op->o_tag = modops[i].mask;
1457                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod ) ) {
1458                         /* Parse attribute into modlist */
1459                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG ) {
1460                                 modlist = syncrepl_accesslog_mods( si, bvals );
1461                         } else {
1462                                 modlist = syncrepl_changelog_mods( si, bvals );
1463                         }
1464                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn ) ) {
1465                         rdn = bvals[0];
1466                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn ) ) {
1467                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ) ) {
1468                                 deleteOldRdn = 1;
1469                         }
1470                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup ) ) {
1471                         sup = bvals[0];
1472                 } else if ( !ber_bvstrcasecmp( &bv,
1473                         &slap_schema.si_ad_entryCSN->ad_cname ) )
1474                 {
1475                         slap_queue_csn( op, bvals );
1476                 }
1477                 ch_free( bvals );
1478         }
1479
1480         /* If we didn't get a mod type or a target DN, bail out */
1481         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn ) ) {
1482                 rc = -1;
1483                 goto done;
1484         }
1485
1486         op->o_callback = &cb;
1487         slap_op_time( &op->o_time, &op->o_tincr );
1488
1489         switch( op->o_tag ) {
1490         case LDAP_REQ_ADD:
1491         case LDAP_REQ_MODIFY:
1492                 /* If we didn't get required data, bail */
1493                 if ( !modlist ) goto done;
1494
1495                 rc = slap_mods_check( op, modlist, &text, txtbuf, textlen, NULL );
1496
1497                 if ( rc != LDAP_SUCCESS ) {
1498                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1499                                 "mods check (%s)\n",
1500                                 si->si_ridtxt, text, 0 );
1501                         goto done;
1502                 }
1503
1504                 if ( op->o_tag == LDAP_REQ_ADD ) {
1505                         Entry *e = entry_alloc();
1506                         op->ora_e = e;
1507                         op->ora_e->e_name = op->o_req_dn;
1508                         op->ora_e->e_nname = op->o_req_ndn;
1509                         freeReqDn = 0;
1510                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1511                         if( rc != LDAP_SUCCESS ) {
1512                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1513                                 "mods2entry (%s)\n",
1514                                         si->si_ridtxt, text, 0 );
1515                         } else {
1516                                 rc = op->o_bd->be_add( op, &rs );
1517                                 Debug( LDAP_DEBUG_SYNC,
1518                                         "syncrepl_message_to_op: %s be_add %s (%d)\n", 
1519                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1520                         }
1521                         if ( e == op->ora_e )
1522                                 be_entry_release_w( op, op->ora_e );
1523                 } else {
1524                         op->orm_modlist = modlist;
1525                         op->o_bd = si->si_wbe;
1526                         rc = op->o_bd->be_modify( op, &rs );
1527                         modlist = op->orm_modlist;
1528                         Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1529                                 "syncrepl_message_to_op: %s be_modify %s (%d)\n", 
1530                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
1531                         op->o_bd = si->si_be;
1532                 }
1533                 break;
1534         case LDAP_REQ_MODRDN:
1535                 if ( BER_BVISNULL( &rdn ) ) goto done;
1536
1537                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ) ) {
1538                         goto done;
1539                 }
1540                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ) ) {
1541                         goto done;
1542                 }
1543                 if ( !BER_BVISNULL( &sup ) ) {
1544                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ) ) {
1545                                 goto done;
1546                         }
1547                         op->orr_newSup = &psup;
1548                         op->orr_nnewSup = &nsup;
1549                 } else {
1550                         op->orr_newSup = NULL;
1551                         op->orr_nnewSup = NULL;
1552                 }
1553                 op->orr_newrdn = prdn;
1554                 op->orr_nnewrdn = nrdn;
1555                 op->orr_deleteoldrdn = deleteOldRdn;
1556                 op->orr_modlist = NULL;
1557                 if ( slap_modrdn2mods( op, &rs ) ) {
1558                         goto done;
1559                 }
1560
1561                 /* Append modlist for operational attrs */
1562                 {
1563                         Modifications *m;
1564
1565                         for ( m = op->orr_modlist; m->sml_next; m = m->sml_next )
1566                                 ;
1567                         m->sml_next = modlist;
1568                         modlist = NULL;
1569                 }
1570                 rc = op->o_bd->be_modrdn( op, &rs );
1571                 slap_mods_free( op->orr_modlist, 1 );
1572                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1573                         "syncrepl_message_to_op: %s be_modrdn %s (%d)\n", 
1574                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1575                 break;
1576         case LDAP_REQ_DELETE:
1577                 rc = op->o_bd->be_delete( op, &rs );
1578                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1579                         "syncrepl_message_to_op: %s be_delete %s (%d)\n", 
1580                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1581                 break;
1582         }
1583 done:
1584         slap_graduate_commit_csn( op );
1585         op->o_bd = si->si_be;
1586         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
1587         BER_BVZERO( &op->o_csn );
1588         if ( modlist ) {
1589                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1590         }
1591         if ( !BER_BVISNULL( &rdn ) ) {
1592                 if ( !BER_BVISNULL( &nsup ) ) {
1593                         ch_free( nsup.bv_val );
1594                 }
1595                 if ( !BER_BVISNULL( &psup ) ) {
1596                         ch_free( psup.bv_val );
1597                 }
1598                 if ( !BER_BVISNULL( &nrdn ) ) {
1599                         ch_free( nrdn.bv_val );
1600                 }
1601                 if ( !BER_BVISNULL( &prdn ) ) {
1602                         ch_free( prdn.bv_val );
1603                 }
1604         }
1605         if ( freeReqDn ) {
1606                 ch_free( op->o_req_ndn.bv_val );
1607                 ch_free( op->o_req_dn.bv_val );
1608         }
1609         ber_free( ber, 0 );
1610         return rc;
1611 }
1612
1613 static int
1614 syncrepl_message_to_entry(
1615         syncinfo_t      *si,
1616         Operation       *op,
1617         LDAPMessage     *msg,
1618         Modifications   **modlist,
1619         Entry                   **entry,
1620         int             syncstate
1621 )
1622 {
1623         Entry           *e = NULL;
1624         BerElement      *ber = NULL;
1625         Modifications   tmp;
1626         Modifications   *mod;
1627         Modifications   **modtail = modlist;
1628
1629         const char      *text;
1630         char txtbuf[SLAP_TEXT_BUFLEN];
1631         size_t textlen = sizeof txtbuf;
1632
1633         struct berval   bdn = BER_BVNULL, dn, ndn;
1634         int             rc, is_ctx;
1635
1636         *modlist = NULL;
1637
1638         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1639                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s "
1640                         "Message type should be entry (%d)",
1641                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1642                 return -1;
1643         }
1644
1645         op->o_tag = LDAP_REQ_ADD;
1646
1647         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1648         if ( rc != LDAP_SUCCESS ) {
1649                 Debug( LDAP_DEBUG_ANY,
1650                         "syncrepl_message_to_entry: %s dn get failed (%d)",
1651                         si->si_ridtxt, rc, 0 );
1652                 return rc;
1653         }
1654
1655         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1656                 /* NOTE: this could be done even before decoding the DN,
1657                  * although encoding errors wouldn't be detected */
1658                 rc = LDAP_SUCCESS;
1659                 goto done;
1660         }
1661
1662         if ( entry == NULL ) {
1663                 return -1;
1664         }
1665
1666         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1667         ber_dupbv( &op->o_req_dn, &dn );
1668         ber_dupbv( &op->o_req_ndn, &ndn );
1669         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1670         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1671
1672         is_ctx = dn_match( &op->o_req_ndn, &op->o_bd->be_nsuffix[0] );
1673
1674         e = entry_alloc();
1675         e->e_name = op->o_req_dn;
1676         e->e_nname = op->o_req_ndn;
1677
1678         while ( ber_remaining( ber ) ) {
1679                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1680                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1681                 {
1682                         break;
1683                 }
1684
1685                 /* Drop all updates to the contextCSN of the context entry
1686                  * (ITS#4622, etc.)
1687                  */
1688                 if ( is_ctx && !strcasecmp( tmp.sml_type.bv_val,
1689                         slap_schema.si_ad_contextCSN->ad_cname.bv_val )) {
1690                         ber_bvarray_free( tmp.sml_values );
1691                         continue;
1692                 }
1693
1694                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ) );
1695
1696                 mod->sml_op = LDAP_MOD_REPLACE;
1697                 mod->sml_flags = 0;
1698                 mod->sml_next = NULL;
1699                 mod->sml_desc = NULL;
1700                 mod->sml_type = tmp.sml_type;
1701                 mod->sml_values = tmp.sml_values;
1702                 mod->sml_nvalues = NULL;
1703
1704                 *modtail = mod;
1705                 modtail = &mod->sml_next;
1706         }
1707
1708         if ( *modlist == NULL ) {
1709                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s no attributes\n",
1710                         si->si_ridtxt, 0, 0 );
1711                 rc = -1;
1712                 goto done;
1713         }
1714
1715         rc = slap_mods_check( op, *modlist, &text, txtbuf, textlen, NULL );
1716
1717         if ( rc != LDAP_SUCCESS ) {
1718                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods check (%s)\n",
1719                         si->si_ridtxt, text, 0 );
1720                 goto done;
1721         }
1722
1723         /* Strip out dynamically generated attrs */
1724         for ( modtail = modlist; *modtail ; ) {
1725                 mod = *modtail;
1726                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1727                         *modtail = mod->sml_next;
1728                         slap_mod_free( &mod->sml_mod, 0 );
1729                         ch_free( mod );
1730                 } else {
1731                         modtail = &mod->sml_next;
1732                 }
1733         }
1734
1735         /* Strip out attrs in exattrs list */
1736         for ( modtail = modlist; *modtail ; ) {
1737                 mod = *modtail;
1738                 if ( ldap_charray_inlist( si->si_exattrs,
1739                         mod->sml_desc->ad_type->sat_cname.bv_val ) )
1740                 {
1741                         *modtail = mod->sml_next;
1742                         slap_mod_free( &mod->sml_mod, 0 );
1743                         ch_free( mod );
1744                 } else {
1745                         modtail = &mod->sml_next;
1746                 }
1747         }
1748
1749         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1750         if( rc != LDAP_SUCCESS ) {
1751                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods2entry (%s)\n",
1752                         si->si_ridtxt, text, 0 );
1753         }
1754
1755 done:
1756         ber_free( ber, 0 );
1757         if ( rc != LDAP_SUCCESS ) {
1758                 if ( e ) {
1759                         entry_free( e );
1760                         e = NULL;
1761                 }
1762         }
1763         if ( entry )
1764                 *entry = e;
1765
1766         return rc;
1767 }
1768
1769 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1770
1771 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1772  * entry if a previous refresh was interrupted before sending us a new
1773  * context state. We try to compare the new entry to the existing entry
1774  * and ignore the new entry if they are the same.
1775  *
1776  * Also, we may get an update where the entryDN has changed, due to
1777  * a ModDn on the provider. We detect this as well, so we can issue
1778  * the corresponding operation locally.
1779  *
1780  * In the case of a modify, we get a list of all the attributes
1781  * in the original entry. Rather than deleting the entry and re-adding it,
1782  * we issue a Modify request that deletes all the attributes and adds all
1783  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1784  * entry.
1785  *
1786  * We otherwise distinguish ModDN from Modify; in the case of
1787  * a ModDN we just use the CSN, modifyTimestamp and modifiersName
1788  * operational attributes from the entry, and do a regular ModDN.
1789  */
1790 typedef struct dninfo {
1791         Entry *new_entry;
1792         struct berval dn;
1793         struct berval ndn;
1794         int renamed;    /* Was an existing entry renamed? */
1795         int delOldRDN;  /* Was old RDN deleted? */
1796         Modifications **modlist;        /* the modlist we received */
1797         Modifications *mods;    /* the modlist we compared */
1798 } dninfo;
1799
1800 static int
1801 syncrepl_entry(
1802         syncinfo_t* si,
1803         Operation *op,
1804         Entry* entry,
1805         Modifications** modlist,
1806         int syncstate,
1807         struct berval* syncUUID )
1808 {
1809         Backend *be = op->o_bd;
1810         slap_callback   cb = { NULL, NULL, NULL, NULL };
1811         struct berval   *syncuuid_bv = NULL;
1812         struct berval   syncUUID_strrep = BER_BVNULL;
1813
1814         SlapReply       rs_search = {REP_RESULT};
1815         SlapReply       rs_delete = {REP_RESULT};
1816         SlapReply       rs_add = {REP_RESULT};
1817         SlapReply       rs_modify = {REP_RESULT};
1818         Filter f = {0};
1819 #ifdef LDAP_COMP_MATCH
1820         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1821 #else
1822         AttributeAssertion ava = { NULL, BER_BVNULL };
1823 #endif
1824         int rc = LDAP_SUCCESS;
1825
1826         struct berval pdn = BER_BVNULL;
1827         dninfo dni = {0};
1828         int     retry = 1;
1829
1830         switch( syncstate ) {
1831         case LDAP_SYNC_PRESENT:
1832                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1833                                         si->si_ridtxt,
1834                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1835                 break;
1836         case LDAP_SYNC_ADD:
1837                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1838                                         si->si_ridtxt,
1839                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1840                 break;
1841         case LDAP_SYNC_DELETE:
1842                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1843                                         si->si_ridtxt,
1844                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1845                 break;
1846         case LDAP_SYNC_MODIFY:
1847                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1848                                         si->si_ridtxt,
1849                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1850                 break;
1851         default:
1852                 Debug( LDAP_DEBUG_ANY, "syncrepl_entry: %s %s\n",
1853                                         si->si_ridtxt,
1854                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1855         }
1856
1857         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ) ) {
1858                 if ( !si->si_refreshPresent ) {
1859                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1860                         if ( avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1861                                 syncuuid_cmp, avl_dup_error ) )
1862                         {
1863                                 ber_bvfree( syncuuid_bv );
1864                                 syncuuid_bv = NULL;
1865                         }
1866                 }
1867         }
1868
1869         if ( syncstate == LDAP_SYNC_PRESENT ) {
1870                 return 0;
1871         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1872                 if ( entry == NULL ) {
1873                         return 0;
1874                 }
1875         }
1876
1877         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1878         if ( syncstate != LDAP_SYNC_DELETE ) {
1879                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1880
1881                 if ( a == NULL ) {
1882                         /* add if missing */
1883                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1884                                 &syncUUID_strrep, syncUUID );
1885
1886                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1887                         /* replace only if necessary */
1888                         if ( a->a_nvals != a->a_vals ) {
1889                                 ber_memfree( a->a_nvals[0].bv_val );
1890                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1891                         }
1892                         ber_memfree( a->a_vals[0].bv_val );
1893                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1894                 }
1895         }
1896
1897         f.f_choice = LDAP_FILTER_EQUALITY;
1898         f.f_ava = &ava;
1899         ava.aa_desc = slap_schema.si_ad_entryUUID;
1900         ava.aa_value = *syncUUID;
1901
1902         if ( syncuuid_bv ) {
1903                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s inserted UUID %s\n",
1904                         si->si_ridtxt, syncUUID_strrep.bv_val, 0 );
1905         }
1906         op->ors_filter = &f;
1907
1908         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
1909         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1910                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1911         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1912         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1913                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
1914         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1915         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1916
1917         op->o_tag = LDAP_REQ_SEARCH;
1918         op->ors_scope = LDAP_SCOPE_SUBTREE;
1919         op->ors_deref = LDAP_DEREF_NEVER;
1920
1921         /* get the entry for this UUID */
1922         op->o_req_dn = si->si_base;
1923         op->o_req_ndn = si->si_base;
1924
1925         op->o_time = slap_get_time();
1926         op->ors_tlimit = SLAP_NO_LIMIT;
1927         op->ors_slimit = 1;
1928
1929         op->ors_attrs = slap_anlist_all_attributes;
1930         op->ors_attrsonly = 0;
1931
1932         /* set callback function */
1933         op->o_callback = &cb;
1934         cb.sc_response = dn_callback;
1935         cb.sc_private = &dni;
1936         dni.new_entry = entry;
1937         dni.modlist = modlist;
1938
1939         if ( limits_check( op, &rs_search ) == 0 ) {
1940                 rc = be->be_search( op, &rs_search );
1941                 Debug( LDAP_DEBUG_SYNC,
1942                                 "syncrepl_entry: %s be_search (%d)\n", 
1943                                 si->si_ridtxt, rc, 0 );
1944         }
1945
1946         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1947                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1948         }
1949
1950         cb.sc_response = null_callback;
1951         cb.sc_private = si;
1952
1953         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1954                 Debug( LDAP_DEBUG_SYNC,
1955                                 "syncrepl_entry: %s %s\n",
1956                                 si->si_ridtxt, entry->e_name.bv_val, 0 );
1957         } else {
1958                 Debug( LDAP_DEBUG_SYNC,
1959                                 "syncrepl_entry: %s %s\n",
1960                                 si->si_ridtxt, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
1961         }
1962
1963         slap_op_time( &op->o_time, &op->o_tincr );
1964         switch ( syncstate ) {
1965         case LDAP_SYNC_ADD:
1966         case LDAP_SYNC_MODIFY:
1967                 {
1968                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
1969                         if ( a ) {
1970                                 /* FIXME: op->o_csn is assumed to be
1971                                  * on the thread's slab; this needs
1972                                  * to be cleared ASAP.
1973                                  * What happens if already present?
1974                                  */
1975                                 assert( BER_BVISNULL( &op->o_csn ) );
1976                                 op->o_csn = a->a_vals[0];
1977                         }
1978                 }
1979 retry_add:;
1980                 if ( BER_BVISNULL( &dni.dn ) ) {
1981
1982                         op->o_req_dn = entry->e_name;
1983                         op->o_req_ndn = entry->e_nname;
1984                         op->o_tag = LDAP_REQ_ADD;
1985                         op->ora_e = entry;
1986                         op->o_bd = si->si_wbe;
1987
1988                         rc = op->o_bd->be_add( op, &rs_add );
1989                         Debug( LDAP_DEBUG_SYNC,
1990                                         "syncrepl_entry: %s be_add (%d)\n", 
1991                                         si->si_ridtxt, rc, 0 );
1992                         switch ( rs_add.sr_err ) {
1993                         case LDAP_SUCCESS:
1994                                 if ( op->ora_e == entry ) {
1995                                         be_entry_release_w( op, entry );
1996                                 }
1997                                 entry = NULL;
1998                                 break;
1999
2000                         case LDAP_REFERRAL:
2001                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
2002                          * only if the suffix entry is not present */
2003                         case LDAP_NO_SUCH_OBJECT:
2004                                 rc = syncrepl_add_glue( op, entry );
2005                                 entry = NULL;
2006                                 break;
2007
2008                         /* if an entry was added via syncrepl_add_glue(),
2009                          * it likely has no entryUUID, so the previous
2010                          * be_search() doesn't find it.  In this case,
2011                          * give syncrepl a chance to modify it. Also
2012                          * allow for entries that were recreated with the
2013                          * same DN but a different entryUUID.
2014                          */
2015                         case LDAP_ALREADY_EXISTS:
2016                                 if ( retry ) {
2017                                         Operation       op2 = *op;
2018                                         SlapReply       rs2 = { 0 };
2019                                         slap_callback   cb2 = { 0 };
2020
2021                                         op2.o_bd = be;
2022                                         op2.o_tag = LDAP_REQ_SEARCH;
2023                                         op2.o_req_dn = entry->e_name;
2024                                         op2.o_req_ndn = entry->e_nname;
2025                                         op2.ors_scope = LDAP_SCOPE_BASE;
2026                                         op2.ors_deref = LDAP_DEREF_NEVER;
2027                                         op2.ors_attrs = slap_anlist_all_attributes;
2028                                         op2.ors_attrsonly = 0;
2029                                         op2.ors_limit = NULL;
2030                                         op2.ors_slimit = 1;
2031                                         op2.ors_tlimit = SLAP_NO_LIMIT;
2032
2033                                         f.f_choice = LDAP_FILTER_PRESENT;
2034                                         f.f_desc = slap_schema.si_ad_objectClass;
2035                                         op2.ors_filter = &f;
2036                                         op2.ors_filterstr = generic_filterstr;
2037
2038                                         op2.o_callback = &cb2;
2039                                         cb2.sc_response = dn_callback;
2040                                         cb2.sc_private = &dni;
2041
2042                                         rc = be->be_search( &op2, &rs2 );
2043                                         if ( rc ) goto done;
2044
2045                                         retry = 0;
2046                                         slap_op_time( &op->o_time, &op->o_tincr );
2047                                         goto retry_add;
2048                                 }
2049                                 /* FALLTHRU */
2050
2051                         default:
2052                                 Debug( LDAP_DEBUG_ANY,
2053                                         "syncrepl_entry: %s be_add failed (%d)\n",
2054                                         si->si_ridtxt, rs_add.sr_err, 0 );
2055                                 break;
2056                         }
2057                         op->o_bd = be;
2058                         goto done;
2059                 }
2060                 /* FALLTHRU */
2061                 op->o_req_dn = dni.dn;
2062                 op->o_req_ndn = dni.ndn;
2063                 if ( dni.renamed ) {
2064                         struct berval noldp, newp, nnewp;
2065
2066                         op->o_tag = LDAP_REQ_MODRDN;
2067                         dnRdn( &entry->e_name, &op->orr_newrdn );
2068                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
2069
2070                         dnParent( &dni.ndn, &noldp );
2071                         dnParent( &entry->e_nname, &nnewp );
2072                         if ( !dn_match( &noldp, &nnewp ) ) {
2073                                 dnParent( &entry->e_name, &newp );
2074                                 op->orr_newSup = &newp;
2075                                 op->orr_nnewSup = &nnewp;
2076                         } else {
2077                                 op->orr_newSup = NULL;
2078                                 op->orr_nnewSup = NULL;
2079                         }
2080                         op->orr_deleteoldrdn = dni.delOldRDN;
2081                         op->orr_modlist = NULL;
2082                         if ( ( rc = slap_modrdn2mods( op, &rs_modify ) ) ) {
2083                                 goto done;
2084                         }
2085
2086                         /* RDNs must be NUL-terminated for back-ldap */
2087                         noldp = op->orr_newrdn;
2088                         ber_dupbv_x( &op->orr_newrdn, &noldp, op->o_tmpmemctx );
2089                         noldp = op->orr_nnewrdn;
2090                         ber_dupbv_x( &op->orr_nnewrdn, &noldp, op->o_tmpmemctx );
2091
2092                         /* Setup opattrs too */
2093                         {
2094                                 static AttributeDescription *nullattr = NULL;
2095                                 static AttributeDescription **const opattrs[] = {
2096                                         &slap_schema.si_ad_entryCSN,
2097                                         &slap_schema.si_ad_modifiersName,
2098                                         &slap_schema.si_ad_modifyTimestamp,
2099                                         &nullattr
2100                                 };
2101                                 AttributeDescription *opattr;
2102                                 Modifications *mod, **modtail, **ml;
2103                                 int i;
2104
2105                                 for ( mod = op->orr_modlist;
2106                                         mod->sml_next;
2107                                         mod = mod->sml_next )
2108                                         ;
2109                                 modtail = &mod->sml_next;
2110
2111                                 /* pull mod off incoming modlist, append to orr_modlist */
2112                                 for ( i = 0; (opattr = *opattrs[i]) != NULL; i++ ) {
2113                                         for ( ml = modlist; *ml; ml = &(*ml)->sml_next )
2114                                         {
2115                                                 if ( (*ml)->sml_desc == opattr ) {
2116                                                         mod = *ml;
2117                                                         *ml = mod->sml_next;
2118                                                         mod->sml_next = NULL;
2119                                                         *modtail = mod;
2120                                                         modtail = &mod->sml_next;
2121                                                         break;
2122                                                 }
2123                                         }
2124                                 }
2125                         }
2126                         op->o_bd = si->si_wbe;
2127                         rc = op->o_bd->be_modrdn( op, &rs_modify );
2128                         op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
2129                         op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
2130
2131                         slap_mods_free( op->orr_modlist, 1 );
2132                         Debug( LDAP_DEBUG_SYNC,
2133                                         "syncrepl_entry: %s be_modrdn (%d)\n", 
2134                                         si->si_ridtxt, rc, 0 );
2135                         op->o_bd = be;
2136                         goto done;
2137                 }
2138                 if ( dni.mods ) {
2139                         op->o_tag = LDAP_REQ_MODIFY;
2140                         op->orm_modlist = dni.mods;
2141                         op->orm_no_opattrs = 1;
2142                         op->o_bd = si->si_wbe;
2143
2144                         rc = op->o_bd->be_modify( op, &rs_modify );
2145                         slap_mods_free( op->orm_modlist, 1 );
2146                         op->orm_no_opattrs = 0;
2147                         Debug( LDAP_DEBUG_SYNC,
2148                                         "syncrepl_entry: %s be_modify (%d)\n", 
2149                                         si->si_ridtxt, rc, 0 );
2150                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2151                                 Debug( LDAP_DEBUG_ANY,
2152                                         "syncrepl_entry: %s be_modify failed (%d)\n",
2153                                         si->si_ridtxt, rs_modify.sr_err, 0 );
2154                         }
2155                         op->o_bd = be;
2156                 } else {
2157                         Debug( LDAP_DEBUG_SYNC,
2158                                         "syncrepl_entry: %s entry unchanged, ignored (%s)\n", 
2159                                         si->si_ridtxt, op->o_req_dn.bv_val, 0 );
2160                 }
2161                 goto done;
2162         case LDAP_SYNC_DELETE :
2163                 if ( !BER_BVISNULL( &dni.dn ) ) {
2164                         op->o_req_dn = dni.dn;
2165                         op->o_req_ndn = dni.ndn;
2166                         op->o_tag = LDAP_REQ_DELETE;
2167                         op->o_bd = si->si_wbe;
2168                         rc = op->o_bd->be_delete( op, &rs_delete );
2169                         Debug( LDAP_DEBUG_SYNC,
2170                                         "syncrepl_entry: %s be_delete (%d)\n", 
2171                                         si->si_ridtxt, rc, 0 );
2172
2173                         while ( rs_delete.sr_err == LDAP_SUCCESS
2174                                 && op->o_delete_glue_parent ) {
2175                                 op->o_delete_glue_parent = 0;
2176                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2177                                         slap_callback cb = { NULL };
2178                                         cb.sc_response = slap_null_cb;
2179                                         dnParent( &op->o_req_ndn, &pdn );
2180                                         op->o_req_dn = pdn;
2181                                         op->o_req_ndn = pdn;
2182                                         op->o_callback = &cb;
2183                                         op->o_bd->be_delete( op, &rs_delete );
2184                                 } else {
2185                                         break;
2186                                 }
2187                         }
2188                         op->o_bd = be;
2189                 }
2190                 goto done;
2191
2192         default :
2193                 Debug( LDAP_DEBUG_ANY,
2194                         "syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
2195                 goto done;
2196         }
2197
2198 done:
2199         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2200                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2201                 BER_BVZERO( &syncUUID_strrep );
2202         }
2203         if ( !BER_BVISNULL( &dni.ndn ) ) {
2204                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2205         }
2206         if ( !BER_BVISNULL( &dni.dn ) ) {
2207                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2208         }
2209         if ( entry )
2210                 entry_free( entry );
2211         BER_BVZERO( &op->o_csn );
2212         return rc;
2213 }
2214
2215 static struct berval gcbva[] = {
2216         BER_BVC("top"),
2217         BER_BVC("glue"),
2218         BER_BVNULL
2219 };
2220
2221 #define NP_DELETE_ONE   2
2222
2223 static void
2224 syncrepl_del_nonpresent(
2225         Operation *op,
2226         syncinfo_t *si,
2227         BerVarray uuids,
2228         struct berval *cookiecsn )
2229 {
2230         Backend* be = op->o_bd;
2231         slap_callback   cb = { NULL };
2232         SlapReply       rs_search = {REP_RESULT};
2233         SlapReply       rs_delete = {REP_RESULT};
2234         SlapReply       rs_modify = {REP_RESULT};
2235         struct nonpresent_entry *np_list, *np_prev;
2236         int rc;
2237         AttributeName   an[2];
2238
2239         struct berval pdn = BER_BVNULL;
2240         struct berval csn;
2241
2242         op->o_req_dn = si->si_base;
2243         op->o_req_ndn = si->si_base;
2244
2245         cb.sc_response = nonpresent_callback;
2246         cb.sc_private = si;
2247
2248         op->o_callback = &cb;
2249         op->o_tag = LDAP_REQ_SEARCH;
2250         op->ors_scope = si->si_scope;
2251         op->ors_deref = LDAP_DEREF_NEVER;
2252         op->o_time = slap_get_time();
2253         op->ors_tlimit = SLAP_NO_LIMIT;
2254
2255
2256         if ( uuids ) {
2257                 Filter uf;
2258 #ifdef LDAP_COMP_MATCH
2259                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
2260 #else
2261                 AttributeAssertion eq = { NULL, BER_BVNULL };
2262 #endif
2263                 int i;
2264
2265                 op->ors_attrsonly = 1;
2266                 op->ors_attrs = slap_anlist_no_attrs;
2267                 op->ors_limit = NULL;
2268                 op->ors_filter = &uf;
2269
2270                 uf.f_ava = &eq;
2271                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2272                 uf.f_next = NULL;
2273                 uf.f_choice = LDAP_FILTER_EQUALITY;
2274                 si->si_refreshDelete |= NP_DELETE_ONE;
2275
2276                 for (i=0; uuids[i].bv_val; i++) {
2277                         op->ors_slimit = 1;
2278                         slap_uuidstr_from_normalized( &uf.f_av_value, &uuids[i],
2279                                 op->o_tmpmemctx );
2280                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2281                         op->o_tmpfree( uf.f_av_value.bv_val, op->o_tmpmemctx );
2282                         uf.f_av_value = uuids[i];
2283                         rc = be->be_search( op, &rs_search );
2284                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2285                 }
2286                 si->si_refreshDelete ^= NP_DELETE_ONE;
2287         } else {
2288                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2289                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2290                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2291                 op->ors_attrs = an;
2292                 op->ors_slimit = SLAP_NO_LIMIT;
2293                 op->ors_attrsonly = 0;
2294                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2295                 op->ors_filterstr = si->si_filterstr;
2296                 op->o_nocaching = 1;
2297
2298                 if ( limits_check( op, &rs_search ) == 0 ) {
2299                         rc = be->be_search( op, &rs_search );
2300                 }
2301                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
2302         }
2303
2304         op->o_nocaching = 0;
2305
2306         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2307
2308                 if ( cookiecsn && !BER_BVISNULL( cookiecsn ) ) {
2309                         csn = *cookiecsn;
2310                 } else {
2311                         csn = si->si_syncCookie.ctxcsn[0];
2312                 }
2313
2314                 op->o_bd = si->si_wbe;
2315                 slap_queue_csn( op, &csn );
2316
2317                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2318                 while ( np_list != NULL ) {
2319                         LDAP_LIST_REMOVE( np_list, npe_link );
2320                         np_prev = np_list;
2321                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2322                         op->o_tag = LDAP_REQ_DELETE;
2323                         op->o_callback = &cb;
2324                         cb.sc_response = null_callback;
2325                         cb.sc_private = si;
2326                         op->o_req_dn = *np_prev->npe_name;
2327                         op->o_req_ndn = *np_prev->npe_nname;
2328                         rc = op->o_bd->be_delete( op, &rs_delete );
2329                         Debug( LDAP_DEBUG_SYNC,
2330                                 "syncrepl_del_nonpresent: %s be_delete %s (%d)\n", 
2331                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
2332
2333                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2334                                 Modifications mod1, mod2;
2335                                 mod1.sml_op = LDAP_MOD_REPLACE;
2336                                 mod1.sml_flags = 0;
2337                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2338                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2339                                 mod1.sml_values = &gcbva[0];
2340                                 mod1.sml_nvalues = NULL;
2341                                 mod1.sml_next = &mod2;
2342
2343                                 mod2.sml_op = LDAP_MOD_REPLACE;
2344                                 mod2.sml_flags = 0;
2345                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2346                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2347                                 mod2.sml_values = &gcbva[1];
2348                                 mod2.sml_nvalues = NULL;
2349                                 mod2.sml_next = NULL;
2350
2351                                 op->o_tag = LDAP_REQ_MODIFY;
2352                                 op->orm_modlist = &mod1;
2353
2354                                 rc = op->o_bd->be_modify( op, &rs_modify );
2355                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2356                         }
2357
2358                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2359                                         op->o_delete_glue_parent ) {
2360                                 op->o_delete_glue_parent = 0;
2361                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2362                                         slap_callback cb = { NULL };
2363                                         cb.sc_response = slap_null_cb;
2364                                         dnParent( &op->o_req_ndn, &pdn );
2365                                         op->o_req_dn = pdn;
2366                                         op->o_req_ndn = pdn;
2367                                         op->o_callback = &cb;
2368                                         /* give it a root privil ? */
2369                                         op->o_bd->be_delete( op, &rs_delete );
2370                                 } else {
2371                                         break;
2372                                 }
2373                         }
2374
2375                         op->o_delete_glue_parent = 0;
2376
2377                         ber_bvfree( np_prev->npe_name );
2378                         ber_bvfree( np_prev->npe_nname );
2379                         ch_free( np_prev );
2380                 }
2381
2382                 slap_graduate_commit_csn( op );
2383                 op->o_bd = be;
2384
2385                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2386                 BER_BVZERO( &op->o_csn );
2387         }
2388
2389         return;
2390 }
2391
2392 int
2393 syncrepl_add_glue(
2394         Operation* op,
2395         Entry *e )
2396 {
2397         Backend *be = op->o_bd;
2398         slap_callback cb = { NULL };
2399         Attribute       *a;
2400         int     rc;
2401         int suffrdns;
2402         int i;
2403         struct berval dn = BER_BVNULL;
2404         struct berval ndn = BER_BVNULL;
2405         Entry   *glue;
2406         SlapReply       rs_add = {REP_RESULT};
2407         struct berval   ptr, nptr;
2408         char            *comma;
2409
2410         op->o_tag = LDAP_REQ_ADD;
2411         op->o_callback = &cb;
2412         cb.sc_response = null_callback;
2413         cb.sc_private = NULL;
2414
2415         dn = e->e_name;
2416         ndn = e->e_nname;
2417
2418         /* count RDNs in suffix */
2419         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2420                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2421                         comma++;
2422                         ptr.bv_len -= comma - ptr.bv_val;
2423                         ptr.bv_val = comma;
2424                         i++;
2425                 }
2426                 suffrdns = i;
2427         } else {
2428                 /* suffix is "" */
2429                 suffrdns = 0;
2430         }
2431
2432         /* Start with BE suffix */
2433         ptr = dn;
2434         for ( i = 0; i < suffrdns; i++ ) {
2435                 comma = ber_bvrchr( &ptr, ',' );
2436                 if ( comma != NULL ) {
2437                         ptr.bv_len = comma - ptr.bv_val;
2438                 } else {
2439                         ptr.bv_len = 0;
2440                         break;
2441                 }
2442         }
2443         
2444         if ( !BER_BVISEMPTY( &ptr ) ) {
2445                 dn.bv_len -= ptr.bv_len + 1;
2446                 dn.bv_val += ptr.bv_len + 1;
2447         }
2448
2449         /* the normalizedDNs are always the same length, no counting
2450          * required.
2451          */
2452         nptr = ndn;
2453         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2454                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2455                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2456
2457                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2458
2459         } else {
2460                 nptr.bv_len = 0;
2461         }
2462
2463         while ( ndn.bv_val > e->e_nname.bv_val ) {
2464                 glue = entry_alloc();
2465                 ber_dupbv( &glue->e_name, &dn );
2466                 ber_dupbv( &glue->e_nname, &ndn );
2467
2468                 a = attr_alloc( slap_schema.si_ad_objectClass );
2469
2470                 a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
2471                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2472                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2473                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2474
2475                 a->a_nvals = a->a_vals;
2476
2477                 a->a_next = glue->e_attrs;
2478                 glue->e_attrs = a;
2479
2480                 a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
2481
2482                 a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
2483                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2484                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2485
2486                 a->a_nvals = a->a_vals;
2487
2488                 a->a_next = glue->e_attrs;
2489                 glue->e_attrs = a;
2490
2491                 op->o_req_dn = glue->e_name;
2492                 op->o_req_ndn = glue->e_nname;
2493                 op->ora_e = glue;
2494                 rc = be->be_add ( op, &rs_add );
2495                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2496                         if ( op->ora_e == glue )
2497                                 be_entry_release_w( op, glue );
2498                 } else {
2499                 /* incl. ALREADY EXIST */
2500                         entry_free( glue );
2501                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
2502                                 entry_free( e );
2503                                 return rc;
2504                         }
2505                 }
2506
2507                 /* Move to next child */
2508                 comma = ber_bvrchr( &ptr, ',' );
2509                 if ( comma == NULL ) {
2510                         break;
2511                 }
2512                 ptr.bv_len = comma - ptr.bv_val;
2513                 
2514                 dn.bv_val = ++comma;
2515                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2516
2517                 comma = ber_bvrchr( &nptr, ',' );
2518                 assert( comma != NULL );
2519                 nptr.bv_len = comma - nptr.bv_val;
2520
2521                 ndn.bv_val = ++comma;
2522                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2523         }
2524
2525         op->o_req_dn = e->e_name;
2526         op->o_req_ndn = e->e_nname;
2527         op->ora_e = e;
2528         rc = be->be_add ( op, &rs_add );
2529         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2530                 if ( op->ora_e == e )
2531                         be_entry_release_w( op, e );
2532         } else {
2533                 entry_free( e );
2534         }
2535
2536         return rc;
2537 }
2538
2539 static int
2540 syncrepl_updateCookie(
2541         syncinfo_t *si,
2542         Operation *op,
2543         struct berval *pdn,
2544         struct sync_cookie *syncCookie )
2545 {
2546         Backend *be = op->o_bd;
2547         Modifications mod[2];
2548         struct berval first = BER_BVNULL;
2549
2550         int rc, i, j, len;
2551
2552         slap_callback cb = { NULL };
2553         SlapReply       rs_modify = {REP_RESULT};
2554
2555         mod[0].sml_op = LDAP_MOD_DELETE;
2556         mod[0].sml_desc = slap_schema.si_ad_contextCSN;
2557         mod[0].sml_type = mod[0].sml_desc->ad_cname;
2558         mod[0].sml_values = NULL;
2559         mod[0].sml_nvalues = NULL;
2560         mod[0].sml_next = &mod[1];
2561
2562         mod[1].sml_op = LDAP_MOD_ADD;
2563         mod[1].sml_desc = slap_schema.si_ad_contextCSN;
2564         mod[1].sml_type = mod[0].sml_desc->ad_cname;
2565         mod[1].sml_values = NULL;
2566         mod[1].sml_nvalues = NULL;
2567         mod[1].sml_next = NULL;
2568
2569         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
2570
2571         for ( i=0; i<syncCookie->numcsns; i++ ) {
2572                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
2573                         if ( syncCookie->sids[i] != si->si_cookieState->cs_sids[j] )
2574                                 continue;
2575                         len = syncCookie->ctxcsn[i].bv_len;
2576                         if ( len > si->si_cookieState->cs_vals[j].bv_len )
2577                                 len = si->si_cookieState->cs_vals[j].bv_len;
2578                         if ( memcmp( syncCookie->ctxcsn[i].bv_val,
2579                                 si->si_cookieState->cs_vals[j].bv_val, len ) > 0 ) {
2580                                 ber_bvarray_add_x( &mod[0].sml_values,
2581                                         &si->si_cookieState->cs_vals[j], op->o_tmpmemctx );
2582                                 ber_bvarray_add_x( &mod[1].sml_values,
2583                                         &syncCookie->ctxcsn[i], op->o_tmpmemctx );
2584                                 if ( BER_BVISNULL( &first ))
2585                                         first = syncCookie->ctxcsn[i];
2586                         }
2587                         break;
2588                 }
2589                 /* there was no match for this SID, it's a new CSN */
2590                 if ( j == si->si_cookieState->cs_num ) {
2591                         ber_bvarray_add_x( &mod[1].sml_values,
2592                                 &syncCookie->ctxcsn[i], op->o_tmpmemctx );
2593                         if ( BER_BVISNULL( &first ))
2594                                 first = syncCookie->ctxcsn[i];
2595                 }
2596         }
2597         /* Should never happen, ITS#5065 */
2598         if ( BER_BVISNULL( &first )) {
2599                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
2600                 return 0;
2601         }
2602         op->o_bd = si->si_wbe;
2603         slap_queue_csn( op, &first );
2604
2605         op->o_tag = LDAP_REQ_MODIFY;
2606
2607         cb.sc_response = null_callback;
2608         cb.sc_private = si;
2609
2610         op->o_callback = &cb;
2611         op->o_req_dn = op->o_bd->be_suffix[0];
2612         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2613
2614         /* update contextCSN */
2615         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2616
2617         if ( mod[0].sml_values )
2618                 op->orm_modlist = mod;
2619         else
2620                 op->orm_modlist = &mod[1];
2621
2622         op->orm_no_opattrs = 1;
2623         rc = op->o_bd->be_modify( op, &rs_modify );
2624         op->orm_no_opattrs = 0;
2625         op->o_msgid = 0;
2626
2627         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
2628                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
2629                 slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2630                 /* If we replaced any old values */
2631                 if ( mod[0].sml_values ) {
2632                         for ( i=0; !BER_BVISNULL( &mod[0].sml_values[i] ); i++ ) {
2633                                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
2634                                         if ( mod[0].sml_values[i].bv_val !=
2635                                                 si->si_cookieState->cs_vals[j].bv_val )
2636                                                 continue;
2637                                         ber_bvreplace( &si->si_cookieState->cs_vals[j],
2638                                                 &mod[1].sml_values[i] );
2639                                         break;
2640                                 }
2641                         }
2642                 } else {
2643                         /* Else we just added */
2644                         si->si_cookieState->cs_num += syncCookie->numcsns;
2645                         value_add( &si->si_cookieState->cs_vals, syncCookie->ctxcsn );
2646                         free( si->si_cookieState->cs_sids );
2647                         si->si_cookieState->cs_sids = slap_parse_csn_sids(
2648                                 si->si_cookieState->cs_vals, si->si_cookieState->cs_num, NULL );
2649                 }
2650
2651                 si->si_cookieState->cs_age++;
2652                 si->si_cookieAge = si->si_cookieState->cs_age;
2653         } else {
2654                 Debug( LDAP_DEBUG_ANY,
2655                         "syncrepl_updateCookie: %s be_modify failed (%d)\n",
2656                         si->si_ridtxt, rs_modify.sr_err, 0 );
2657         }
2658         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
2659
2660         slap_graduate_commit_csn( op );
2661         op->o_bd = be;
2662         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2663         BER_BVZERO( &op->o_csn );
2664         if ( mod[1].sml_next ) slap_mods_free( mod[1].sml_next, 1 );
2665         op->o_tmpfree( mod[1].sml_values, op->o_tmpmemctx );
2666         op->o_tmpfree( mod[0].sml_values, op->o_tmpmemctx );
2667
2668         return rc;
2669 }
2670
2671 static void
2672 attr_cmp( Operation *op, Attribute *old, Attribute *new,
2673         Modifications ***mret, Modifications ***mcur )
2674 {
2675         int i, j;
2676         Modifications *mod, **modtail;
2677
2678         modtail = *mret;
2679
2680         if ( old ) {
2681                 int n, o, d, a, *adds, *dels;
2682                 /* count old and new */
2683                 for ( o=0; old->a_vals[o].bv_val; o++ ) ;
2684                 for ( n=0; new->a_vals[n].bv_val; n++ ) ;
2685
2686                 adds = op->o_tmpalloc( sizeof(int) * n, op->o_tmpmemctx );
2687                 dels = op->o_tmpalloc( sizeof(int) * o, op->o_tmpmemctx );
2688                 d = 0;
2689                 a = 0;
2690                 i = 0;
2691                 j = 0;
2692
2693                 while ( i < o && j < n ) {
2694                         int k;
2695                         if ( bvmatch( &old->a_vals[i], &new->a_vals[j] ) ) {
2696                                 i++;
2697                                 j++;
2698                                 continue;
2699                         }
2700                         for ( k = j + 1; k<n; k++ ) {
2701                                 if ( bvmatch( &old->a_vals[i], &new->a_vals[k] ) ) {
2702                                         break;
2703                                 }
2704                         }
2705                         /* an old value was deleted */
2706                         if ( k == n ) {
2707                                 dels[d++] = i++;
2708                                 continue;
2709                         }
2710                         /* old value still exists, move to next */
2711                         i++;
2712                         for ( k = i; k < o; k++ ) {
2713                                 if ( bvmatch( &old->a_vals[k], &new->a_vals[j] ) ) {
2714                                         break;
2715                                 }
2716                         }
2717                         if ( k == o ) {
2718                                 adds[a++] = j++;
2719                         } else {
2720                                 j++;
2721                         }
2722                 }
2723                 while ( i < o )
2724                         dels[d++] = i++;
2725                 while ( j < n )
2726                         adds[a++] = j++;
2727
2728                 /* all old values were deleted, just use the replace op */
2729                 if ( d == o ) {
2730                         i = j-1;
2731                 } else if ( d ) {
2732                 /* delete some values */
2733                         mod = ch_malloc( sizeof( Modifications ) );
2734                         mod->sml_op = LDAP_MOD_DELETE;
2735                         mod->sml_flags = 0;
2736                         mod->sml_desc = old->a_desc;
2737                         mod->sml_type = mod->sml_desc->ad_cname;
2738                         mod->sml_values = ch_malloc( ( d + 1 ) * sizeof(struct berval) );
2739                         if ( old->a_vals != old->a_nvals ) {
2740                                 mod->sml_nvalues = ch_malloc( ( d + 1 ) * sizeof(struct berval) );
2741                         } else {
2742                                 mod->sml_nvalues = NULL;
2743                         }
2744                         for ( i = 0; i < d; i++ ) {
2745                                 ber_dupbv( &mod->sml_values[i], &old->a_vals[dels[i]] );
2746                                 if ( mod->sml_nvalues ) {
2747                                         ber_dupbv( &mod->sml_nvalues[i], &old->a_nvals[dels[i]] );
2748                                 }
2749                         }
2750                         BER_BVZERO( &mod->sml_values[i] );
2751                         if ( mod->sml_nvalues ) {
2752                                 BER_BVZERO( &mod->sml_nvalues[i] );
2753                         }
2754                         *modtail = mod;
2755                         modtail = &mod->sml_next;
2756                         i = j;
2757                 }
2758                 op->o_tmpfree( dels, op->o_tmpmemctx );
2759                 /* some values were added */
2760                 if ( a && d < o ) {
2761                         mod = ch_malloc( sizeof( Modifications ) );
2762                         mod->sml_op = LDAP_MOD_ADD;
2763                         mod->sml_flags = 0;
2764                         mod->sml_desc = old->a_desc;
2765                         mod->sml_type = mod->sml_desc->ad_cname;
2766                         mod->sml_values = ch_malloc( ( a + 1 ) * sizeof(struct berval) );
2767                         if ( old->a_vals != old->a_nvals ) {
2768                                 mod->sml_nvalues = ch_malloc( ( a + 1 ) * sizeof(struct berval) );
2769                         } else {
2770                                 mod->sml_nvalues = NULL;
2771                         }
2772                         for ( i = 0; i < a; i++ ) {
2773                                 ber_dupbv( &mod->sml_values[i], &new->a_vals[adds[i]] );
2774                                 if ( mod->sml_nvalues ) {
2775                                         ber_dupbv( &mod->sml_nvalues[i], &new->a_nvals[adds[i]] );
2776                                 }
2777                         }
2778                         BER_BVZERO( &mod->sml_values[i] );
2779                         if ( mod->sml_nvalues ) {
2780                                 BER_BVZERO( &mod->sml_nvalues[i] );
2781                         }
2782                         *modtail = mod;
2783                         modtail = &mod->sml_next;
2784                         i = j;
2785                 }
2786                 op->o_tmpfree( adds, op->o_tmpmemctx );
2787         } else {
2788                 /* new attr, just use the new mod */
2789                 i = 0;
2790                 j = 1;
2791         }
2792         /* advance to next element */
2793         mod = **mcur;
2794         if ( mod ) {
2795                 if ( i != j ) {
2796                         **mcur = mod->sml_next;
2797                         *modtail = mod;
2798                         modtail = &mod->sml_next;
2799                 } else {
2800                         *mcur = &mod->sml_next;
2801                 }
2802         }
2803         *mret = modtail;
2804 }
2805
2806 static int
2807 dn_callback(
2808         Operation*      op,
2809         SlapReply*      rs )
2810 {
2811         dninfo *dni = op->o_callback->sc_private;
2812
2813         if ( rs->sr_type == REP_SEARCH ) {
2814                 if ( !BER_BVISNULL( &dni->dn ) ) {
2815                         Debug( LDAP_DEBUG_ANY,
2816                                 "dn_callback : consistency error - "
2817                                 "entryUUID is not unique\n", 0, 0, 0 );
2818                 } else {
2819                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2820                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2821                         /* If there is a new entry, see if it differs from the old.
2822                          * We compare the non-normalized values so that cosmetic changes
2823                          * in the provider are always propagated.
2824                          */
2825                         if ( dni->new_entry ) {
2826                                 Modifications **modtail, **ml;
2827                                 Attribute *old, *new;
2828                                 int is_ctx;
2829
2830                                 is_ctx = dn_match( &rs->sr_entry->e_nname,
2831                                         &op->o_bd->be_nsuffix[0] );
2832
2833                                 /* Did the DN change?
2834                                  */
2835                                 if ( !dn_match( &rs->sr_entry->e_name,
2836                                                 &dni->new_entry->e_name ) )
2837                                 {
2838                                         struct berval oldRDN, oldVal;
2839                                         AttributeDescription *ad = NULL;
2840                                         Attribute *a;
2841
2842                                         dni->renamed = 1;
2843                                         /* See if the oldRDN was deleted */
2844                                         dnRdn( &rs->sr_entry->e_nname, &oldRDN );
2845                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
2846                                         oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
2847                                                 oldRDN.bv_val );
2848                                         oldRDN.bv_len -= oldVal.bv_len + 2;
2849                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
2850                                         a = attr_find( dni->new_entry->e_attrs, ad );
2851                                         if ( !a || value_find_ex( ad,
2852                                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
2853                                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
2854                                                 SLAP_MR_VALUE_OF_SYNTAX, a->a_nvals,
2855                                                 &oldVal, op->o_tmpmemctx ) != LDAP_SUCCESS )
2856                                         {
2857                                                 dni->delOldRDN = 1;
2858                                         }
2859                                         /* OK, this was just a modDN, we're done */
2860                                         return LDAP_SUCCESS;
2861                                 }
2862
2863                                 modtail = &dni->mods;
2864                                 ml = dni->modlist;
2865
2866                                 /* Make sure new entry is actually newer than old entry */
2867                                 old = attr_find( rs->sr_entry->e_attrs,
2868                                         slap_schema.si_ad_entryCSN );
2869                                 new = attr_find( dni->new_entry->e_attrs,
2870                                         slap_schema.si_ad_entryCSN );
2871                                 if ( new && old ) {
2872                                         int len = old->a_vals[0].bv_len;
2873                                         if ( len > new->a_vals[0].bv_len )
2874                                                 len = new->a_vals[0].bv_len;
2875                                         if ( memcmp( old->a_vals[0].bv_val,
2876                                                 new->a_vals[0].bv_val, len ) >= 0 ) {
2877                                                 Debug( LDAP_DEBUG_SYNC,
2878                                                         "dn_callback : new entry is older than ours "
2879                                                         "%s ours %s, new %s\n",
2880                                                         rs->sr_entry->e_name.bv_val,
2881                                                         old->a_vals[0].bv_val,
2882                                                         new->a_vals[0].bv_val );
2883                                                 return LDAP_SUCCESS;
2884                                         }
2885                                 }
2886
2887                                 /* We assume that attributes are saved in the same order
2888                                  * in the remote and local databases. So if we walk through
2889                                  * the attributeDescriptions one by one they should match in
2890                                  * lock step. If not, look for an add or delete.
2891                                  */
2892                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2893                                                 old && new; )
2894                                 {
2895                                         /* If we've seen this before, use its mod now */
2896                                         if ( new->a_flags & SLAP_ATTR_IXADD ) {
2897                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2898                                                 new = new->a_next;
2899                                                 continue;
2900                                         }
2901                                         /* Skip contextCSN */
2902                                         if ( is_ctx && old->a_desc ==
2903                                                 slap_schema.si_ad_contextCSN ) {
2904                                                 old = old->a_next;
2905                                                 continue;
2906                                         }
2907
2908                                         if ( old->a_desc != new->a_desc ) {
2909                                                 Modifications *mod;
2910                                                 Attribute *tmp;
2911
2912                                                 /* If it's just been re-added later,
2913                                                  * remember that we've seen it.
2914                                                  */
2915                                                 tmp = attr_find( new, old->a_desc );
2916                                                 if ( tmp ) {
2917                                                         tmp->a_flags |= SLAP_ATTR_IXADD;
2918                                                 } else {
2919                                                         /* If it's a new attribute, pull it in.
2920                                                          */
2921                                                         tmp = attr_find( old, new->a_desc );
2922                                                         if ( !tmp ) {
2923                                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2924                                                                 new = new->a_next;
2925                                                                 continue;
2926                                                         }
2927                                                         /* Delete old attr */
2928                                                         mod = ch_malloc( sizeof( Modifications ) );
2929                                                         mod->sml_op = LDAP_MOD_DELETE;
2930                                                         mod->sml_flags = 0;
2931                                                         mod->sml_desc = old->a_desc;
2932                                                         mod->sml_type = mod->sml_desc->ad_cname;
2933                                                         mod->sml_values = NULL;
2934                                                         mod->sml_nvalues = NULL;
2935                                                         *modtail = mod;
2936                                                         modtail = &mod->sml_next;
2937                                                 }
2938                                                 old = old->a_next;
2939                                                 continue;
2940                                         }
2941                                         /* kludge - always update modifiersName so that it
2942                                          * stays co-located with the other mod opattrs. But only
2943                                          * if we know there are other valid mods.
2944                                          */
2945                                         if ( old->a_desc == slap_schema.si_ad_modifiersName &&
2946                                                 dni->mods )
2947                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2948                                         else
2949                                                 attr_cmp( op, old, new, &modtail, &ml );
2950                                         new = new->a_next;
2951                                         old = old->a_next;
2952                                 }
2953                                 *modtail = *ml;
2954                                 *ml = NULL;
2955                         }
2956                 }
2957         } else if ( rs->sr_type == REP_RESULT ) {
2958                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2959                         Debug( LDAP_DEBUG_ANY,
2960                                 "dn_callback : consistency error - "
2961                                 "entryUUID is not unique\n", 0, 0, 0 );
2962                 }
2963         }
2964
2965         return LDAP_SUCCESS;
2966 }
2967
2968 static int
2969 nonpresent_callback(
2970         Operation*      op,
2971         SlapReply*      rs )
2972 {
2973         syncinfo_t *si = op->o_callback->sc_private;
2974         Attribute *a;
2975         int count = 0;
2976         struct berval* present_uuid = NULL;
2977         struct nonpresent_entry *np_entry;
2978
2979         if ( rs->sr_type == REP_RESULT ) {
2980                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2981                 si->si_presentlist = NULL;
2982
2983         } else if ( rs->sr_type == REP_SEARCH ) {
2984                 if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
2985                         char buf[sizeof("rid=000 not")];
2986
2987                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2988
2989                         if ( a ) {
2990                                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2991                                         syncuuid_cmp );
2992                         }
2993
2994                         if ( slap_debug & LDAP_DEBUG_SYNC ) {
2995                                 sprintf( buf, "%s %s", si->si_ridtxt,
2996                                         present_uuid ? "got" : "not" );
2997                         }
2998
2999                         Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %s UUID %s, dn %s\n",
3000                                 buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
3001
3002                         if ( a == NULL ) return 0;
3003                 }
3004
3005                 if ( present_uuid == NULL ) {
3006                         np_entry = (struct nonpresent_entry *)
3007                                 ch_calloc( 1, sizeof( struct nonpresent_entry ) );
3008                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
3009                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
3010                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
3011
3012                 } else {
3013                         avl_delete( &si->si_presentlist,
3014                                         &a->a_nvals[0], syncuuid_cmp );
3015                         ch_free( present_uuid->bv_val );
3016                         ch_free( present_uuid );
3017                 }
3018         }
3019         return LDAP_SUCCESS;
3020 }
3021
3022 static int
3023 null_callback(
3024         Operation*      op,
3025         SlapReply*      rs )
3026 {
3027         if ( rs->sr_err != LDAP_SUCCESS &&
3028                 rs->sr_err != LDAP_REFERRAL &&
3029                 rs->sr_err != LDAP_ALREADY_EXISTS &&
3030                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
3031                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
3032         {
3033                 Debug( LDAP_DEBUG_ANY,
3034                         "null_callback : error code 0x%x\n",
3035                         rs->sr_err, 0, 0 );
3036         }
3037         return LDAP_SUCCESS;
3038 }
3039
3040 static struct berval *
3041 slap_uuidstr_from_normalized(
3042         struct berval* uuidstr,
3043         struct berval* normalized,
3044         void *ctx )
3045 {
3046 #if 0
3047         struct berval *new;
3048         unsigned char nibble;
3049         int i, d = 0;
3050
3051         if ( normalized == NULL ) return NULL;
3052         if ( normalized->bv_len != 16 ) return NULL;
3053
3054         if ( uuidstr ) {
3055                 new = uuidstr;
3056         } else {
3057                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3058                 if ( new == NULL ) {
3059                         return NULL;
3060                 }
3061         }
3062
3063         new->bv_len = 36;
3064
3065         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3066                 if ( new != uuidstr ) {
3067                         slap_sl_free( new, ctx );
3068                 }
3069                 return NULL;
3070         }
3071
3072         for ( i = 0; i < 16; i++ ) {
3073                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
3074                         new->bv_val[(i<<1)+d] = '-';
3075                         d += 1;
3076                 }
3077
3078                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
3079                 if ( nibble < 10 ) {
3080                         new->bv_val[(i<<1)+d] = nibble + '0';
3081                 } else {
3082                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
3083                 }
3084
3085                 nibble = (normalized->bv_val[i]) & 0xF;
3086                 if ( nibble < 10 ) {
3087                         new->bv_val[(i<<1)+d+1] = nibble + '0';
3088                 } else {
3089                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
3090                 }
3091         }
3092
3093         new->bv_val[new->bv_len] = '\0';
3094         return new;
3095 #endif
3096
3097         struct berval   *new;
3098         int             rc = 0;
3099
3100         if ( normalized == NULL ) return NULL;
3101         if ( normalized->bv_len != 16 ) return NULL;
3102
3103         if ( uuidstr ) {
3104                 new = uuidstr;
3105
3106         } else {
3107                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3108                 if ( new == NULL ) {
3109                         return NULL;
3110                 }
3111         }
3112
3113         new->bv_len = 36;
3114
3115         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3116                 rc = 1;
3117                 goto done;
3118         }
3119
3120         rc = lutil_uuidstr_from_normalized( normalized->bv_val,
3121                 normalized->bv_len, new->bv_val, new->bv_len + 1 );
3122
3123 done:;
3124         if ( rc == -1 ) {
3125                 if ( new != NULL ) {
3126                         if ( new->bv_val != NULL ) {
3127                                 slap_sl_free( new->bv_val, ctx );
3128                         }
3129
3130                         if ( new != uuidstr ) {
3131                                 slap_sl_free( new, ctx );
3132                         }
3133                 }
3134                 new = NULL;
3135
3136         } else {
3137                 new->bv_len = rc;
3138         }
3139
3140         return new;
3141 }
3142
3143 static int
3144 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
3145 {
3146         const struct berval *uuid1 = v_uuid1;
3147         const struct berval *uuid2 = v_uuid2;
3148         int rc = uuid1->bv_len - uuid2->bv_len;
3149         if ( rc ) return rc;
3150         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
3151 }
3152
3153 static void
3154 avl_ber_bvfree( void *v_bv )
3155 {
3156         struct berval   *bv = (struct berval *)v_bv;
3157         
3158         if( v_bv == NULL ) return;
3159         if ( !BER_BVISNULL( bv ) ) {
3160                 ch_free( bv->bv_val );
3161         }
3162         ch_free( (char *) bv );
3163 }
3164
3165 void
3166 syncinfo_free( syncinfo_t *sie, int free_all )
3167 {
3168         syncinfo_t *si_next;
3169
3170         if ( free_all && sie->si_cookieState ) {
3171                 ch_free( sie->si_cookieState->cs_sids );
3172                 ber_bvarray_free( sie->si_cookieState->cs_vals );
3173                 ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_mutex );
3174                 ch_free( sie->si_cookieState );
3175         }
3176         do {
3177                 si_next = sie->si_next;
3178
3179                 if ( sie->si_ld ) {
3180                         if ( sie->si_conn_setup ) {
3181                                 ber_socket_t s;
3182                                 ldap_get_option( sie->si_ld, LDAP_OPT_DESC, &s );
3183                                 connection_client_stop( s );
3184                                 sie->si_conn_setup = 0;
3185                         }
3186                         ldap_unbind_ext( sie->si_ld, NULL, NULL );
3187                 }
3188         
3189                 /* re-fetch it, in case it was already removed */
3190                 sie->si_re = ldap_pvt_runqueue_find( &slapd_rq, do_syncrepl, sie );
3191                 if ( sie->si_re ) {
3192                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, sie->si_re ) )
3193                                 ldap_pvt_runqueue_stoptask( &slapd_rq, sie->si_re );
3194                         ldap_pvt_runqueue_remove( &slapd_rq, sie->si_re );
3195                 }
3196         
3197                 ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
3198         
3199                 bindconf_free( &sie->si_bindconf );
3200         
3201                 if ( sie->si_filterstr.bv_val ) {
3202                         ch_free( sie->si_filterstr.bv_val );
3203                 }
3204                 if ( sie->si_logfilterstr.bv_val ) {
3205                         ch_free( sie->si_logfilterstr.bv_val );
3206                 }
3207                 if ( sie->si_base.bv_val ) {
3208                         ch_free( sie->si_base.bv_val );
3209                 }
3210                 if ( sie->si_logbase.bv_val ) {
3211                         ch_free( sie->si_logbase.bv_val );
3212                 }
3213                 if ( sie->si_attrs ) {
3214                         int i = 0;
3215                         while ( sie->si_attrs[i] != NULL ) {
3216                                 ch_free( sie->si_attrs[i] );
3217                                 i++;
3218                         }
3219                         ch_free( sie->si_attrs );
3220                 }
3221                 if ( sie->si_exattrs ) {
3222                         int i = 0;
3223                         while ( sie->si_exattrs[i] != NULL ) {
3224                                 ch_free( sie->si_exattrs[i] );
3225                                 i++;
3226                         }
3227                         ch_free( sie->si_exattrs );
3228                 }
3229                 if ( sie->si_anlist ) {
3230                         int i = 0;
3231                         while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
3232                                 ch_free( sie->si_anlist[i].an_name.bv_val );
3233                                 i++;
3234                         }
3235                         ch_free( sie->si_anlist );
3236                 }
3237                 if ( sie->si_exanlist ) {
3238                         int i = 0;
3239                         while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
3240                                 ch_free( sie->si_exanlist[i].an_name.bv_val );
3241                                 i++;
3242                         }
3243                         ch_free( sie->si_exanlist );
3244                 }
3245                 if ( sie->si_retryinterval ) {
3246                         ch_free( sie->si_retryinterval );
3247                 }
3248                 if ( sie->si_retrynum ) {
3249                         ch_free( sie->si_retrynum );
3250                 }
3251                 if ( sie->si_retrynum_init ) {
3252                         ch_free( sie->si_retrynum_init );
3253                 }
3254                 slap_sync_cookie_free( &sie->si_syncCookie, 0 );
3255                 if ( sie->si_presentlist ) {
3256                     avl_free( sie->si_presentlist, avl_ber_bvfree );
3257                 }
3258                 while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
3259                         struct nonpresent_entry* npe;
3260                         npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
3261                         LDAP_LIST_REMOVE( npe, npe_link );
3262                         if ( npe->npe_name ) {
3263                                 if ( npe->npe_name->bv_val ) {
3264                                         ch_free( npe->npe_name->bv_val );
3265                                 }
3266                                 ch_free( npe->npe_name );
3267                         }
3268                         if ( npe->npe_nname ) {
3269                                 if ( npe->npe_nname->bv_val ) {
3270                                         ch_free( npe->npe_nname->bv_val );
3271                                 }
3272                                 ch_free( npe->npe_nname );
3273                         }
3274                         ch_free( npe );
3275                 }
3276                 ch_free( sie );
3277                 sie = si_next;
3278         } while ( free_all && si_next );
3279 }
3280
3281
3282
3283 /* NOTE: used & documented in slapd.conf(5) */
3284 #define IDSTR                   "rid"
3285 #define PROVIDERSTR             "provider"
3286 #define SCHEMASTR               "schemachecking"
3287 #define FILTERSTR               "filter"
3288 #define SEARCHBASESTR           "searchbase"
3289 #define SCOPESTR                "scope"
3290 #define ATTRSONLYSTR            "attrsonly"
3291 #define ATTRSSTR                "attrs"
3292 #define TYPESTR                 "type"
3293 #define INTERVALSTR             "interval"
3294 #define RETRYSTR                "retry"
3295 #define SLIMITSTR               "sizelimit"
3296 #define TLIMITSTR               "timelimit"
3297 #define SYNCDATASTR             "syncdata"
3298 #define LOGBASESTR              "logbase"
3299 #define LOGFILTERSTR    "logfilter"
3300
3301 /* FIXME: undocumented */
3302 #define EXATTRSSTR              "exattrs"
3303 #define MANAGEDSAITSTR          "manageDSAit"
3304
3305 /* mandatory */
3306 #define GOT_ID                  0x0001
3307 #define GOT_PROVIDER    0x0002
3308 #define GOT_BASE                0x0004
3309
3310 /* check */
3311 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER|GOT_BASE)
3312
3313 static struct {
3314         struct berval key;
3315         int val;
3316 } scopes[] = {
3317         { BER_BVC("base"), LDAP_SCOPE_BASE },
3318         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
3319         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
3320         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
3321         { BER_BVC("subord"), LDAP_SCOPE_SUBORDINATE },
3322         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
3323         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
3324         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
3325         { BER_BVNULL, 0 }
3326 };
3327
3328 static slap_verbmasks datamodes[] = {
3329         { BER_BVC("default"), SYNCDATA_DEFAULT },
3330         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
3331         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
3332         { BER_BVNULL, 0 }
3333 };
3334
3335 static int
3336 parse_syncrepl_line(
3337         ConfigArgs      *c,
3338         syncinfo_t      *si )
3339 {
3340         int     gots = 0;
3341         int     i;
3342         char    *val;
3343
3344         for ( i = 1; i < c->argc; i++ ) {
3345                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
3346                                         STRLENOF( IDSTR "=" ) ) )
3347                 {
3348                         int tmp;
3349                         /* '\0' string terminator accounts for '=' */
3350                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
3351                         if ( lutil_atoi( &tmp, val ) != 0 ) {
3352                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3353                                         "Error: parse_syncrepl_line: "
3354                                         "unable to parse syncrepl id \"%s\"", val );
3355                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3356                                 return -1;
3357                         }
3358                         if ( tmp >= 1000 || tmp < 0 ) {
3359                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3360                                         "Error: parse_syncrepl_line: "
3361                                         "syncrepl id %d is out of range [0..999]", tmp );
3362                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3363                                 return -1;
3364                         }
3365                         si->si_rid = tmp;
3366                         sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
3367                         gots |= GOT_ID;
3368                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
3369                                         STRLENOF( PROVIDERSTR "=" ) ) )
3370                 {
3371                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
3372                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
3373                         gots |= GOT_PROVIDER;
3374                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
3375                                         STRLENOF( SCHEMASTR "=" ) ) )
3376                 {
3377                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
3378                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
3379                                 si->si_schemachecking = 1;
3380                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
3381                                 si->si_schemachecking = 0;
3382                         } else {
3383                                 si->si_schemachecking = 1;
3384                         }
3385                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
3386                                         STRLENOF( FILTERSTR "=" ) ) )
3387                 {
3388                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
3389                         if ( si->si_filterstr.bv_val )
3390                                 ch_free( si->si_filterstr.bv_val );
3391                         ber_str2bv( val, 0, 1, &si->si_filterstr );
3392                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
3393                                         STRLENOF( LOGFILTERSTR "=" ) ) )
3394                 {
3395                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
3396                         if ( si->si_logfilterstr.bv_val )
3397                                 ch_free( si->si_logfilterstr.bv_val );
3398                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
3399                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
3400                                         STRLENOF( SEARCHBASESTR "=" ) ) )
3401                 {
3402                         struct berval   bv;
3403                         int             rc;
3404
3405                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
3406                         if ( si->si_base.bv_val ) {
3407                                 ch_free( si->si_base.bv_val );
3408                         }
3409                         ber_str2bv( val, 0, 0, &bv );
3410                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
3411                         if ( rc != LDAP_SUCCESS ) {
3412                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3413                                         "Invalid base DN \"%s\": %d (%s)",
3414                                         val, rc, ldap_err2string( rc ) );
3415                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3416                                 return -1;
3417                         }
3418                         if ( !be_issubordinate( c->be, &si->si_base ) ) {
3419                                 ch_free( si->si_base.bv_val );
3420                                 BER_BVZERO( &si->si_base );
3421                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3422                                         "Base DN \"%s\" is not within the database naming context",
3423                                         val );
3424                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3425                                 return -1;
3426                         }
3427                         gots |= GOT_BASE;
3428                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
3429                                         STRLENOF( LOGBASESTR "=" ) ) )
3430                 {
3431                         struct berval   bv;
3432                         int             rc;
3433
3434                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
3435                         if ( si->si_logbase.bv_val ) {
3436                                 ch_free( si->si_logbase.bv_val );
3437                         }
3438                         ber_str2bv( val, 0, 0, &bv );
3439                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
3440                         if ( rc != LDAP_SUCCESS ) {
3441                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3442                                         "Invalid logbase DN \"%s\": %d (%s)",
3443                                         val, rc, ldap_err2string( rc ) );
3444                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3445                                 return -1;
3446                         }
3447                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
3448                                         STRLENOF( SCOPESTR "=" ) ) )
3449                 {
3450                         int j;
3451                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
3452                         for ( j = 0; !BER_BVISNULL(&scopes[j].key); j++ ) {
3453                                 if (!strcasecmp( val, scopes[j].key.bv_val ) ) {
3454                                         si->si_scope = scopes[j].val;
3455                                         break;
3456                                 }
3457                         }
3458                         if ( BER_BVISNULL(&scopes[j].key) ) {
3459                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3460                                         "Error: parse_syncrepl_line: "
3461                                         "unknown scope \"%s\"", val);
3462                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3463                                 return -1;
3464                         }
3465                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
3466                                         STRLENOF( ATTRSONLYSTR ) ) )
3467                 {
3468                         si->si_attrsonly = 1;
3469                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
3470                                         STRLENOF( ATTRSSTR "=" ) ) )
3471                 {
3472                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
3473                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
3474                                 char *attr_fname;
3475                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
3476                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
3477                                 if ( si->si_anlist == NULL ) {
3478                                         ch_free( attr_fname );
3479                                         return -1;
3480                                 }
3481                                 si->si_anfile = attr_fname;
3482                         } else {
3483                                 char *str, *s, *next;
3484                                 char delimstr[] = " ,\t";
3485                                 str = ch_strdup( val );
3486                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
3487                                                 s != NULL;
3488                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
3489                                 {
3490                                         if ( strlen(s) == 1 && *s == '*' ) {
3491                                                 si->si_allattrs = 1;
3492                                                 val[ s - str ] = delimstr[0];
3493                                         }
3494                                         if ( strlen(s) == 1 && *s == '+' ) {
3495                                                 si->si_allopattrs = 1;
3496                                                 val [ s - str ] = delimstr[0];
3497                                         }
3498                                 }
3499                                 ch_free( str );
3500                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
3501                                 if ( si->si_anlist == NULL ) {
3502                                         return -1;
3503                                 }
3504                         }
3505                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
3506                                         STRLENOF( EXATTRSSTR "=" ) ) )
3507                 {
3508                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
3509                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
3510                                 char *attr_fname;
3511                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
3512                                 si->si_exanlist = file2anlist(
3513                                         si->si_exanlist, attr_fname, " ,\t" );
3514                                 if ( si->si_exanlist == NULL ) {
3515                                         ch_free( attr_fname );
3516                                         return -1;
3517                                 }
3518                                 ch_free( attr_fname );
3519                         } else {
3520                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
3521                                 if ( si->si_exanlist == NULL ) {
3522                                         return -1;
3523                                 }
3524                         }
3525                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
3526                                         STRLENOF( TYPESTR "=" ) ) )
3527                 {
3528                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
3529                         if ( !strncasecmp( val, "refreshOnly",
3530                                                 STRLENOF("refreshOnly") ) )
3531                         {
3532                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3533                         } else if ( !strncasecmp( val, "refreshAndPersist",
3534                                                 STRLENOF("refreshAndPersist") ) )
3535                         {
3536                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
3537                                 si->si_interval = 60;
3538                         } else {
3539                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3540                                         "Error: parse_syncrepl_line: "
3541                                         "unknown sync type \"%s\"", val);
3542                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3543                                 return -1;
3544                         }
3545                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
3546                                         STRLENOF( INTERVALSTR "=" ) ) )
3547                 {
3548                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
3549                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
3550                                 si->si_interval = 0;
3551                         } else if ( strchr( val, ':' ) != NULL ) {
3552                                 char *next, *ptr = val;
3553                                 unsigned dd, hh, mm, ss;
3554
3555                                 /* NOTE: the test for ptr[ 0 ] == '-'
3556                                  * should go before the call to strtoul() */
3557                                 dd = strtoul( ptr, &next, 10 );
3558                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' ) {
3559                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3560                                                 "Error: parse_syncrepl_line: "
3561                                                 "invalid interval \"%s\", unable to parse days", val );
3562                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3563                                         return -1;
3564                                 }
3565                                 ptr = next + 1;
3566                                 hh = strtoul( ptr, &next, 10 );
3567                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || hh > 24 ) {
3568                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3569                                                 "Error: parse_syncrepl_line: "
3570                                                 "invalid interval \"%s\", unable to parse hours", val );
3571                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3572                                         return -1;
3573                                 }
3574                                 ptr = next + 1;
3575                                 mm = strtoul( ptr, &next, 10 );
3576                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || mm > 60 ) {
3577                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3578                                                 "Error: parse_syncrepl_line: "
3579                                                 "invalid interval \"%s\", unable to parse minutes", val );
3580                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3581                                         return -1;
3582                                 }
3583                                 ptr = next + 1;
3584                                 ss = strtoul( ptr, &next, 10 );
3585                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != '\0' || ss > 60 ) {
3586                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3587                                                 "Error: parse_syncrepl_line: "
3588                                                 "invalid interval \"%s\", unable to parse seconds", val );
3589                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3590                                         return -1;
3591                                 }
3592                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
3593                         } else {
3594                                 unsigned long   t;
3595
3596                                 if ( lutil_parse_time( val, &t ) != 0 ) {
3597                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3598                                                 "Error: parse_syncrepl_line: "
3599                                                 "invalid interval \"%s\"", val );
3600                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3601                                         return -1;
3602                                 }
3603                                 si->si_interval = (time_t)t;
3604                         }
3605                         if ( si->si_interval < 0 ) {
3606                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3607                                         "Error: parse_syncrepl_line: "
3608                                         "invalid interval \"%ld\"",
3609                                         (long) si->si_interval);
3610                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3611                                 return -1;
3612                         }
3613                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
3614                                         STRLENOF( RETRYSTR "=" ) ) )
3615                 {
3616                         char **retry_list;
3617                         int j, k, n;
3618
3619                         val = c->argv[ i ] + STRLENOF( RETRYSTR "=" );
3620                         retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
3621                         retry_list[0] = NULL;
3622
3623                         slap_str2clist( &retry_list, val, " ,\t" );
3624
3625                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3626                         n = k / 2;
3627                         if ( k % 2 ) {
3628                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3629                                         "Error: incomplete syncrepl retry list" );
3630                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3631                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3632                                         ch_free( retry_list[k] );
3633                                 }
3634                                 ch_free( retry_list );
3635                                 return 1;
3636                         }
3637                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
3638                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
3639                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
3640                         for ( j = 0; j < n; j++ ) {
3641                                 unsigned long   t;
3642                                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3643                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3644                                                 "Error: invalid retry interval \"%s\" (#%d)",
3645                                                 retry_list[j*2], j );
3646                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3647                                         /* do some cleanup */
3648                                         return 1;
3649                                 }
3650                                 si->si_retryinterval[j] = (time_t)t;
3651                                 if ( *retry_list[j*2+1] == '+' ) {
3652                                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3653                                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3654                                         j++;
3655                                         break;
3656                                 } else {
3657                                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3658                                                         || si->si_retrynum_init[j] <= 0 )
3659                                         {
3660                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3661                                                         "Error: invalid initial retry number \"%s\" (#%d)",
3662                                                         retry_list[j*2+1], j );
3663                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3664                                                 /* do some cleanup */
3665                                                 return 1;
3666                                         }
3667                                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3668                                                         || si->si_retrynum[j] <= 0 )
3669                                         {
3670                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3671                                                         "Error: invalid retry number \"%s\" (#%d)",
3672                                                         retry_list[j*2+1], j );
3673                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3674                                                 /* do some cleanup */
3675                                                 return 1;
3676                                         }
3677                                 }
3678                         }
3679                         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3680                         si->si_retrynum[j] = RETRYNUM_TAIL;
3681                         si->si_retryinterval[j] = 0;
3682                         
3683                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3684                                 ch_free( retry_list[k] );
3685                         }
3686                         ch_free( retry_list );
3687                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
3688                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
3689                 {
3690                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
3691                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
3692                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
3693                         {
3694                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3695                                         "invalid manageDSAit value \"%s\".\n",
3696                                         val );
3697                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3698                                 return 1;
3699                         }
3700                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
3701                                         STRLENOF( SLIMITSTR "=") ) )
3702                 {
3703                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
3704                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3705                                 si->si_slimit = 0;
3706
3707                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
3708                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3709                                         "invalid size limit value \"%s\".\n",
3710                                         val );
3711                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3712                                 return 1;
3713                         }
3714                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
3715                                         STRLENOF( TLIMITSTR "=" ) ) )
3716                 {
3717                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
3718                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3719                                 si->si_tlimit = 0;
3720
3721                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
3722                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3723                                         "invalid time limit value \"%s\".\n",
3724                                         val );
3725                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3726                                 return 1;
3727                         }
3728                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
3729                                         STRLENOF( SYNCDATASTR "=" ) ) )
3730                 {
3731                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
3732                         si->si_syncdata = verb_to_mask( val, datamodes );
3733                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
3734                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3735                                 "Error: parse_syncrepl_line: "
3736                                 "unable to parse \"%s\"\n", c->argv[ i ] );
3737                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3738                         return -1;
3739                 }
3740         }
3741
3742         if ( gots != GOT_ALL ) {
3743                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3744                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
3745                         gots & GOT_ID ? "" : " "IDSTR,
3746                         gots & GOT_PROVIDER ? "" : " "PROVIDERSTR,
3747                         gots & GOT_BASE ? "" : " "SEARCHBASESTR );
3748                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3749                 return -1;
3750         }
3751
3752         return 0;
3753 }
3754
3755 static int
3756 add_syncrepl(
3757         ConfigArgs *c )
3758 {
3759         syncinfo_t *si;
3760         int     rc = 0;
3761
3762         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
3763                 snprintf( c->cr_msg, sizeof(c->cr_msg), "database %s does not support "
3764                         "operations required for syncrepl", c->be->be_type );
3765                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
3766                 return 1;
3767         }
3768         if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
3769                 strcpy( c->cr_msg, "rootDN must be defined before syncrepl may be used" );
3770                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
3771                 return 1;
3772         }
3773         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
3774
3775         if ( si == NULL ) {
3776                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
3777                 return 1;
3778         }
3779
3780         si->si_bindconf.sb_tls = SB_TLS_OFF;
3781         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
3782         si->si_schemachecking = 0;
3783         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
3784                 &si->si_filterstr );
3785         si->si_base.bv_val = NULL;
3786         si->si_scope = LDAP_SCOPE_SUBTREE;
3787         si->si_attrsonly = 0;
3788         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
3789         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
3790         si->si_attrs = NULL;
3791         si->si_allattrs = 0;
3792         si->si_allopattrs = 0;
3793         si->si_exattrs = NULL;
3794         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3795         si->si_interval = 86400;
3796         si->si_retryinterval = NULL;
3797         si->si_retrynum_init = NULL;
3798         si->si_retrynum = NULL;
3799         si->si_manageDSAit = 0;
3800         si->si_tlimit = 0;
3801         si->si_slimit = 0;
3802         si->si_conn_setup = 0;
3803
3804         si->si_presentlist = NULL;
3805         LDAP_LIST_INIT( &si->si_nonpresentlist );
3806         ldap_pvt_thread_mutex_init( &si->si_mutex );
3807
3808         rc = parse_syncrepl_line( c, si );
3809
3810         if ( rc == 0 ) {
3811                 /* Must be LDAPv3 because we need controls */
3812                 switch ( si->si_bindconf.sb_version ) {
3813                 case 0:
3814                         /* not explicitly set */
3815                         si->si_bindconf.sb_version = LDAP_VERSION3;
3816                         break;
3817                 case 3:
3818                         /* explicitly set */
3819                         break;
3820                 default:
3821                         Debug( LDAP_DEBUG_ANY,
3822                                 "version %d incompatible with syncrepl\n",
3823                                 si->si_bindconf.sb_version, 0, 0 );
3824                         syncinfo_free( si, 0 ); 
3825                         return 1;
3826                 }
3827
3828                 si->si_be = c->be;
3829                 if ( slapMode & SLAP_SERVER_MODE ) {
3830                         Listener **l = slapd_get_listeners();
3831                         int isMe = 0;
3832
3833                         /* check if URL points to current server. If so, ignore
3834                          * this configuration. We require an exact match. Just
3835                          * in case they really want to do this, they can vary
3836                          * the case of the URL to allow it.
3837                          */
3838                         if ( l && !SLAP_DBHIDDEN( c->be ) ) {
3839                                 int i;
3840                                 for ( i=0; l[i]; i++ ) {
3841                                         if ( bvmatch( &l[i]->sl_url, &si->si_bindconf.sb_uri ) ) {
3842                                                 isMe = 1;
3843                                                 break;
3844                                         }
3845                                 }
3846                         }
3847
3848                         if ( !isMe ) {
3849                                 init_syncrepl( si );
3850                                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
3851                                         si->si_interval, do_syncrepl, si, "do_syncrepl",
3852                                         si->si_ridtxt );
3853                                 if ( si->si_re )
3854                                         rc = config_sync_shadow( c ) ? -1 : 0;
3855                                 else
3856                                         rc = -1;
3857                         }
3858                 } else {
3859                         /* mirrormode still needs to see this flag in tool mode */
3860                         rc = config_sync_shadow( c ) ? -1 : 0;
3861                 }
3862         }
3863
3864 #ifdef HAVE_TLS
3865         /* Use main slapd defaults */
3866         bindconf_tls_defaults( &si->si_bindconf );
3867 #endif
3868         if ( rc < 0 ) {
3869                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
3870                 syncinfo_free( si, 0 ); 
3871                 return 1;
3872         } else {
3873                 Debug( LDAP_DEBUG_CONFIG,
3874                         "Config: ** successfully added syncrepl \"%s\"\n",
3875                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
3876                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
3877                 if ( !si->si_schemachecking ) {
3878                         SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3879                 }
3880                 if ( c->be->be_syncinfo ) {
3881                         si->si_cookieState = c->be->be_syncinfo->si_cookieState;
3882                 } else {
3883                         si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
3884                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
3885                 }
3886                 si->si_next = c->be->be_syncinfo;
3887                 c->be->be_syncinfo = si;
3888                 return 0;
3889         }
3890 }
3891
3892 static void
3893 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
3894 {
3895         struct berval bc, uri;
3896         char buf[BUFSIZ*2], *ptr;
3897         int i;
3898
3899 #define WHATSLEFT       ( sizeof( buf ) - ( ptr - buf ) )
3900
3901         BER_BVZERO( bv );
3902
3903         /* temporarily inhibit bindconf from printing URI */
3904         uri = si->si_bindconf.sb_uri;
3905         BER_BVZERO( &si->si_bindconf.sb_uri );
3906         si->si_bindconf.sb_version = 0;
3907         bindconf_unparse( &si->si_bindconf, &bc );
3908         si->si_bindconf.sb_uri = uri;
3909         si->si_bindconf.sb_version = LDAP_VERSION3;
3910
3911         ptr = buf;
3912         ptr += snprintf( ptr, WHATSLEFT, IDSTR "=%03d " PROVIDERSTR "=%s",
3913                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
3914         if ( ptr - buf >= sizeof( buf ) ) return;
3915         if ( !BER_BVISNULL( &bc ) ) {
3916                 if ( WHATSLEFT <= bc.bv_len ) {
3917                         free( bc.bv_val );
3918                         return;
3919                 }
3920                 ptr = lutil_strcopy( ptr, bc.bv_val );
3921                 free( bc.bv_val );
3922         }
3923         if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
3924                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
3925                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
3926                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
3927                 *ptr++ = '"';
3928         }
3929         if ( !BER_BVISNULL( &si->si_base ) ) {
3930                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
3931                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
3932                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
3933                 *ptr++ = '"';
3934         }
3935         if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
3936                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
3937                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
3938                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
3939                 *ptr++ = '"';
3940         }
3941         if ( !BER_BVISNULL( &si->si_logbase ) ) {
3942                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
3943                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
3944                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
3945                 *ptr++ = '"';
3946         }
3947         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
3948                 if ( si->si_scope == scopes[i].val ) {
3949                         if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + scopes[i].key.bv_len ) return;
3950                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
3951                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
3952                         break;
3953                 }
3954         }
3955         if ( si->si_attrsonly ) {
3956                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3957                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
3958         }
3959         if ( si->si_anfile ) {
3960                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
3961                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
3962                 ptr = lutil_strcopy( ptr, si->si_anfile );
3963                 *ptr++ = '"';
3964         } else if ( si->si_allattrs || si->si_allopattrs ||
3965                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
3966         {
3967                 char *old;
3968
3969                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3970                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
3971                 old = ptr;
3972                 /* FIXME: add check for overflow */
3973                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
3974                 if ( si->si_allattrs ) {
3975                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
3976                         if ( old != ptr ) *ptr++ = ',';
3977                         *ptr++ = '*';
3978                 }
3979                 if ( si->si_allopattrs ) {
3980                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
3981                         if ( old != ptr ) *ptr++ = ',';
3982                         *ptr++ = '+';
3983                 }
3984                 *ptr++ = '"';
3985         }
3986         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3987                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
3988                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3989                 /* FIXME: add check for overflow */
3990                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
3991         }
3992         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
3993         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3994         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3995         
3996         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
3997         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3998         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3999                 "refreshAndPersist" : "refreshOnly" );
4000
4001         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
4002                 int dd, hh, mm, ss;
4003
4004                 dd = si->si_interval;
4005                 ss = dd % 60;
4006                 dd /= 60;
4007                 mm = dd % 60;
4008                 dd /= 60;
4009                 hh = dd % 24;
4010                 dd /= 24;
4011                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
4012                 ptr += snprintf( ptr, WHATSLEFT, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
4013                 if ( ptr - buf >= sizeof( buf ) ) return;
4014         } else if ( si->si_retryinterval ) {
4015                 int space=0;
4016                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
4017                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
4018                 for (i=0; si->si_retryinterval[i]; i++) {
4019                         if ( space ) *ptr++ = ' ';
4020                         space = 1;
4021                         ptr += snprintf( ptr, WHATSLEFT, "%ld ", (long) si->si_retryinterval[i] );
4022                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
4023                                 *ptr++ = '+';
4024                         else
4025                                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
4026                 }
4027                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
4028                 *ptr++ = '"';
4029         }
4030
4031         if ( si->si_slimit ) {
4032                 if ( WHATSLEFT <= STRLENOF( " " SLIMITSTR "=" ) ) return;
4033                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
4034                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_slimit );
4035         }
4036
4037         if ( si->si_tlimit ) {
4038                 if ( WHATSLEFT <= STRLENOF( " " TLIMITSTR "=" ) ) return;
4039                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
4040                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_tlimit );
4041         }
4042
4043         if ( si->si_syncdata ) {
4044                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
4045                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
4046                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
4047                         ptr = lutil_strcopy( ptr, bc.bv_val );
4048                 }
4049         }
4050         bc.bv_len = ptr - buf;
4051         bc.bv_val = buf;
4052         ber_dupbv( bv, &bc );
4053 }
4054
4055 int
4056 syncrepl_config( ConfigArgs *c )
4057 {
4058         if (c->op == SLAP_CONFIG_EMIT) {
4059                 if ( c->be->be_syncinfo ) {
4060                         struct berval bv;
4061                         syncinfo_t *si;
4062
4063                         for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
4064                                 syncrepl_unparse( si, &bv ); 
4065                                 ber_bvarray_add( &c->rvalue_vals, &bv );
4066                         }
4067                         return 0;
4068                 }
4069                 return 1;
4070         } else if ( c->op == LDAP_MOD_DELETE ) {
4071                 cookie_state *cs = NULL;
4072                 if ( c->be->be_syncinfo ) {
4073                         syncinfo_t *si, **sip;
4074                         int i;
4075
4076                         cs = c->be->be_syncinfo->si_cookieState;
4077                         for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
4078                                 si = *sip;
4079                                 if ( c->valx == -1 || i == c->valx ) {
4080                                         *sip = si->si_next;
4081                                         /* If the task is currently active, we have to leave
4082                                          * it running. It will exit on its own. This will only
4083                                          * happen when running on the cn=config DB.
4084                                          */
4085                                         if ( si->si_re &&
4086                                                 ldap_pvt_runqueue_isrunning( &slapd_rq, si->si_re ) ) {
4087                                                 si->si_ctype = 0;
4088                                         } else {
4089                                                 syncinfo_free( si, 0 );
4090                                         }
4091                                         if ( i == c->valx )
4092                                                 break;
4093                                 } else {
4094                                         sip = &si->si_next;
4095                                 }
4096                         }
4097                 }
4098                 if ( !c->be->be_syncinfo ) {
4099                         SLAP_DBFLAGS( c->be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
4100                         if ( cs ) {
4101                                 ber_bvarray_free( cs->cs_vals );
4102                                 ldap_pvt_thread_mutex_destroy( &cs->cs_mutex );
4103                                 ch_free( cs );
4104                         }
4105                 }
4106                 return 0;
4107         }
4108         if ( SLAP_SLURP_SHADOW( c->be ) ) {
4109                 Debug(LDAP_DEBUG_ANY, "%s: "
4110                         "syncrepl: database already shadowed.\n",
4111                         c->log, 0, 0);
4112                 return(1);
4113         } else {
4114                 return add_syncrepl( c );
4115         }
4116 }