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