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