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