]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
ITS#4904 fix from HEAD delta-sync modlist free
[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;
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                 } else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1152                         if ( si->si_retrynum[i] > 0 )
1153                                 si->si_retrynum[i]--;
1154                         rtask->interval.tv_sec = si->si_retryinterval[i];
1155                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1156                         slap_wake_listener();
1157                 }
1158         }
1159         
1160         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1161         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1162
1163         return NULL;
1164 }
1165
1166 static slap_verbmasks modops[] = {
1167         { BER_BVC("add"), LDAP_REQ_ADD },
1168         { BER_BVC("delete"), LDAP_REQ_DELETE },
1169         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1170         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1171         { BER_BVNULL, 0 }
1172 };
1173
1174 static Modifications *
1175 syncrepl_accesslog_mods(
1176         syncinfo_t *si,
1177         struct berval *vals
1178 )
1179 {
1180         char *colon;
1181         const char *text;
1182         AttributeDescription *ad;
1183         struct berval bv, bv2;
1184         short op;
1185         Modifications *mod = NULL, *modlist = NULL, **modtail;
1186         int i;
1187
1188         modtail = &modlist;
1189
1190         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1191                 ad = NULL;
1192                 bv = vals[i];
1193
1194                 colon = ber_bvchr( &bv, ':' );
1195                 if ( !colon )
1196                         continue;       /* invalid */
1197                 bv.bv_len = colon - bv.bv_val;
1198                 if ( slap_bv2ad( &bv, &ad, &text )) {
1199                         /* Invalid */
1200                         continue;
1201                 }
1202                 /* Ignore dynamically generated attrs */
1203                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC )
1204                         continue;
1205                 /* Ignore excluded attrs */
1206                 if ( ldap_charray_inlist( si->si_exattrs,
1207                         ad->ad_type->sat_cname.bv_val ))
1208                         continue;
1209
1210                 switch(colon[1]) {
1211                 case '+':       op = LDAP_MOD_ADD; break;
1212                 case '-':       op = LDAP_MOD_DELETE; break;
1213                 case '=':       op = LDAP_MOD_REPLACE; break;
1214                 case '#':       op = LDAP_MOD_INCREMENT; break;
1215                 default:        continue;
1216                 }
1217
1218                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1219                         mod = (Modifications *) ch_malloc( sizeof( Modifications ));
1220                         mod->sml_flags = 0;
1221                         mod->sml_op = op;
1222                         mod->sml_next = NULL;
1223                         mod->sml_desc = ad;
1224                         mod->sml_type = ad->ad_cname;
1225                         mod->sml_values = NULL;
1226                         mod->sml_nvalues = NULL;
1227
1228                         *modtail = mod;
1229                         modtail = &mod->sml_next;
1230                 }
1231                 if ( colon[2] == ' ' ) {
1232                         bv.bv_val = colon + 3;
1233                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1234                         ber_dupbv( &bv2, &bv );
1235                         ber_bvarray_add( &mod->sml_values, &bv2 );
1236                 }
1237         }
1238         return modlist;
1239 }
1240
1241 static Modifications *
1242 syncrepl_changelog_mods(
1243         syncinfo_t *si,
1244         struct berval *vals
1245 )
1246 {
1247         return NULL;    /* FIXME */
1248 }
1249
1250 static int
1251 syncrepl_message_to_op(
1252         syncinfo_t      *si,
1253         Operation       *op,
1254         LDAPMessage     *msg
1255 )
1256 {
1257         BerElement      *ber = NULL;
1258         Modifications   *modlist = NULL;
1259         logschema *ls;
1260         SlapReply rs = { REP_RESULT };
1261         slap_callback cb = { NULL, null_callback, NULL, NULL };
1262
1263         const char      *text;
1264         char txtbuf[SLAP_TEXT_BUFLEN];
1265         size_t textlen = sizeof txtbuf;
1266
1267         struct berval   bdn, dn = BER_BVNULL, ndn;
1268         struct berval   bv, *bvals = NULL;
1269         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1270                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1271                 psup = BER_BVNULL, nsup = BER_BVNULL;
1272         int             rc, deleteOldRdn = 0, freeReqDn = 0;
1273
1274         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1275                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: rid %03d "
1276                         "Message type should be entry (%d)",
1277                         si->si_rid, ldap_msgtype( msg ), 0 );
1278                 return -1;
1279         }
1280
1281         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1282                 ls = &accesslog_sc;
1283         else
1284                 ls = &changelog_sc;
1285
1286         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1287
1288         if ( rc != LDAP_SUCCESS ) {
1289                 Debug( LDAP_DEBUG_ANY,
1290                         "syncrepl_message_to_op: rid %03d dn get failed (%d)",
1291                         si->si_rid, rc, 0 );
1292                 return rc;
1293         }
1294
1295         op->o_tag = LBER_DEFAULT;
1296
1297         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ))
1298                 == LDAP_SUCCESS ) {
1299                 if ( bv.bv_val == NULL )
1300                         break;
1301
1302                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn )) {
1303                         bdn = bvals[0];
1304                         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1305                         ber_dupbv( &op->o_req_dn, &dn );
1306                         ber_dupbv( &op->o_req_ndn, &ndn );
1307                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1308                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1309                         freeReqDn = 1;
1310                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req )) {
1311                         int i = verb_to_mask( bvals[0].bv_val, modops );
1312                         if ( i < 0 ) {
1313                                 Debug( LDAP_DEBUG_ANY,
1314                                         "syncrepl_message_to_op: rid %03d unknown op %s",
1315                                         si->si_rid, bvals[0].bv_val, 0 );
1316                                 ch_free( bvals );
1317                                 rc = -1;
1318                                 goto done;
1319                         }
1320                         op->o_tag = modops[i].mask;
1321                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod )) {
1322                         /* Parse attribute into modlist */
1323                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1324                                 modlist = syncrepl_accesslog_mods( si, bvals );
1325                         else
1326                                 modlist = syncrepl_changelog_mods( si, bvals );
1327                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn )) {
1328                         rdn = bvals[0];
1329                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn )) {
1330                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ))
1331                                 deleteOldRdn = 1;
1332                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup )) {
1333                         sup = bvals[0];
1334                 } else if ( !ber_bvstrcasecmp( &bv,
1335                         &slap_schema.si_ad_entryCSN->ad_cname )) {
1336                         slap_queue_csn( op, bvals );
1337                 }
1338                 ch_free( bvals );
1339         }
1340
1341         /* If we didn't get a mod type or a target DN, bail out */
1342         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn )) {
1343                 rc = -1;
1344                 goto done;
1345         }
1346
1347         op->o_callback = &cb;
1348         slap_op_time( &op->o_time, &op->o_tincr );
1349
1350         switch( op->o_tag ) {
1351         case LDAP_REQ_ADD:
1352         case LDAP_REQ_MODIFY:
1353                 /* If we didn't get required data, bail */
1354                 if ( !modlist ) goto done;
1355
1356                 rc = slap_mods_check( modlist, &text, txtbuf, textlen, NULL );
1357
1358                 if ( rc != LDAP_SUCCESS ) {
1359                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: rid %03d "
1360                                 "mods check (%s)\n",
1361                                 si->si_rid, text, 0 );
1362                         goto done;
1363                 }
1364
1365                 if ( op->o_tag == LDAP_REQ_ADD ) {
1366                         op->ora_e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1367                         op->ora_e->e_name = op->o_req_dn;
1368                         op->ora_e->e_nname = op->o_req_ndn;
1369                         freeReqDn = 0;
1370                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1371                         if( rc != LDAP_SUCCESS ) {
1372                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: rid %03d "
1373                                 "mods2entry (%s)\n",
1374                                         si->si_rid, text, 0 );
1375                         } else {
1376                                 rc = op->o_bd->be_add( op, &rs );
1377                                 Debug( LDAP_DEBUG_SYNC,
1378                                         "syncrepl_message_to_op: rid %03d be_add %s (%d)\n", 
1379                                         si->si_rid, op->o_req_dn.bv_val, rc );
1380                         }
1381                         be_entry_release_w( op, op->ora_e );
1382                 } else {
1383                         op->orm_modlist = modlist;
1384                         rc = op->o_bd->be_modify( op, &rs );
1385                         modlist = op->orm_modlist;
1386                         Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1387                                 "syncrepl_message_to_op: rid %03d be_modify %s (%d)\n", 
1388                                 si->si_rid, op->o_req_dn.bv_val, rc );
1389                 }
1390                 break;
1391         case LDAP_REQ_MODRDN:
1392                 if ( BER_BVISNULL( &rdn )) goto done;
1393
1394                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ))
1395                         goto done;
1396                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ))
1397                         goto done;
1398                 if ( !BER_BVISNULL( &sup )) {
1399                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ))
1400                                 goto done;
1401                         op->orr_newSup = &psup;
1402                         op->orr_nnewSup = &nsup;
1403                 } else {
1404                         op->orr_newSup = NULL;
1405                         op->orr_nnewSup = NULL;
1406                 }
1407                 op->orr_newrdn = prdn;
1408                 op->orr_nnewrdn = nrdn;
1409                 op->orr_deleteoldrdn = deleteOldRdn;
1410                 rc = op->o_bd->be_modrdn( op, &rs );
1411                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1412                         "syncrepl_message_to_op: rid %03d be_modrdn %s (%d)\n", 
1413                         si->si_rid, op->o_req_dn.bv_val, rc );
1414                 break;
1415         case LDAP_REQ_DELETE:
1416                 rc = op->o_bd->be_delete( op, &rs );
1417                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1418                         "syncrepl_message_to_op: rid %03d be_delete %s (%d)\n", 
1419                         si->si_rid, op->o_req_dn.bv_val, rc );
1420                 break;
1421         }
1422 done:
1423         slap_graduate_commit_csn( op );
1424         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
1425         BER_BVZERO( &op->o_csn );
1426         if ( modlist )
1427                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1428         if ( !BER_BVISNULL( &rdn )) {
1429                 if ( !BER_BVISNULL( &nsup ))
1430                         ch_free( nsup.bv_val );
1431                 if ( !BER_BVISNULL( &psup ))
1432                         ch_free( psup.bv_val );
1433                 if ( !BER_BVISNULL( &nrdn ))
1434                         ch_free( nrdn.bv_val );
1435                 if ( !BER_BVISNULL( &prdn ))
1436                         ch_free( prdn.bv_val );
1437         }
1438         if ( freeReqDn ) {
1439                 ch_free( op->o_req_ndn.bv_val );
1440                 ch_free( op->o_req_dn.bv_val );
1441         }
1442         ber_free ( ber, 0 );
1443         return rc;
1444 }
1445
1446 static int
1447 syncrepl_message_to_entry(
1448         syncinfo_t      *si,
1449         Operation       *op,
1450         LDAPMessage     *msg,
1451         Modifications   **modlist,
1452         Entry                   **entry,
1453         int             syncstate
1454 )
1455 {
1456         Entry           *e = NULL;
1457         BerElement      *ber = NULL;
1458         Modifications   tmp;
1459         Modifications   *mod;
1460         Modifications   **modtail = modlist;
1461
1462         const char      *text;
1463         char txtbuf[SLAP_TEXT_BUFLEN];
1464         size_t textlen = sizeof txtbuf;
1465
1466         struct berval   bdn = BER_BVNULL, dn, ndn;
1467         int             rc;
1468
1469         *modlist = NULL;
1470
1471         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1472                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: rid %03d "
1473                         "Message type should be entry (%d)",
1474                         si->si_rid, ldap_msgtype( msg ), 0 );
1475                 return -1;
1476         }
1477
1478         op->o_tag = LDAP_REQ_ADD;
1479
1480         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1481         if ( rc != LDAP_SUCCESS ) {
1482                 Debug( LDAP_DEBUG_ANY,
1483                         "syncrepl_message_to_entry: rid %03d dn get failed (%d)",
1484                         si->si_rid, rc, 0 );
1485                 return rc;
1486         }
1487
1488         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1489         ber_dupbv( &op->o_req_dn, &dn );
1490         ber_dupbv( &op->o_req_ndn, &ndn );
1491         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1492         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1493
1494         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1495                 /* NOTE: this could be done even before decoding the DN,
1496                  * although encoding errors wouldn't be detected */
1497                 rc = LDAP_SUCCESS;
1498                 goto done;
1499         }
1500
1501         if ( entry == NULL ) {
1502                 rc = -1;
1503                 goto done;
1504         }
1505
1506         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1507         *entry = e;
1508         e->e_name = op->o_req_dn;
1509         e->e_nname = op->o_req_ndn;
1510
1511         while ( ber_remaining( ber ) ) {
1512                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1513                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1514                 {
1515                         break;
1516                 }
1517
1518                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1519
1520                 mod->sml_op = LDAP_MOD_REPLACE;
1521                 mod->sml_flags = 0;
1522                 mod->sml_next = NULL;
1523                 mod->sml_desc = NULL;
1524                 mod->sml_type = tmp.sml_type;
1525                 mod->sml_values = tmp.sml_values;
1526                 mod->sml_nvalues = NULL;
1527
1528                 *modtail = mod;
1529                 modtail = &mod->sml_next;
1530         }
1531
1532         if ( *modlist == NULL ) {
1533                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: rid %03d no attributes\n",
1534                         si->si_rid, 0, 0 );
1535                 rc = -1;
1536                 goto done;
1537         }
1538
1539         rc = slap_mods_check( *modlist, &text, txtbuf, textlen, NULL );
1540
1541         if ( rc != LDAP_SUCCESS ) {
1542                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: rid %03d mods check (%s)\n",
1543                         si->si_rid, text, 0 );
1544                 goto done;
1545         }
1546
1547         /* Strip out dynamically generated attrs */
1548         for ( modtail = modlist; *modtail ; ) {
1549                 mod = *modtail;
1550                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1551                         *modtail = mod->sml_next;
1552                         slap_mod_free( &mod->sml_mod, 0 );
1553                         ch_free( mod );
1554                 } else {
1555                         modtail = &mod->sml_next;
1556                 }
1557         }
1558
1559         /* Strip out attrs in exattrs list */
1560         for ( modtail = modlist; *modtail ; ) {
1561                 mod = *modtail;
1562                 if ( ldap_charray_inlist( si->si_exattrs,
1563                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1564                         *modtail = mod->sml_next;
1565                         slap_mod_free( &mod->sml_mod, 0 );
1566                         ch_free( mod );
1567                 } else {
1568                         modtail = &mod->sml_next;
1569                 }
1570         }
1571         
1572         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1573         if( rc != LDAP_SUCCESS ) {
1574                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: rid %03d mods2entry (%s)\n",
1575                         si->si_rid, text, 0 );
1576         }
1577
1578 done:
1579         ber_free( ber, 0 );
1580         if ( rc != LDAP_SUCCESS ) {
1581                 if ( e ) {
1582                         entry_free( e );
1583                         *entry = e = NULL;
1584                 }
1585         }
1586
1587         return rc;
1588 }
1589
1590 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1591
1592 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1593  * entry if a previous refresh was interrupted before sending us a new
1594  * context state. We try to compare the new entry to the existing entry
1595  * and ignore the new entry if they are the same.
1596  *
1597  * Also, we may get an update where the entryDN has changed, due to
1598  * a ModDn on the provider. We detect this as well, so we can issue
1599  * the corresponding operation locally.
1600  *
1601  * In the case of a modify, we get a list of all the attributes
1602  * in the original entry. Rather than deleting the entry and re-adding it,
1603  * we issue a Modify request that deletes all the attributes and adds all
1604  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1605  * entry.
1606  *
1607  * We don't try to otherwise distinguish ModDN from Modify; in the case of
1608  * a ModDN we will issue both operations on the local database.
1609  */
1610 typedef struct dninfo {
1611         Entry *new_entry;
1612         struct berval dn;
1613         struct berval ndn;
1614         int renamed;    /* Was an existing entry renamed? */
1615         int wasChanged; /* are the attributes changed? */
1616         int attrs;              /* how many attribute types are in the ads list */
1617         AttributeDescription **ads;
1618 } dninfo;
1619
1620 static int
1621 syncrepl_entry(
1622         syncinfo_t* si,
1623         Operation *op,
1624         Entry* entry,
1625         Modifications** modlist,
1626         int syncstate,
1627         struct berval* syncUUID,
1628         struct sync_cookie* syncCookie_req,
1629         struct berval* syncCSN )
1630 {
1631         Backend *be = op->o_bd;
1632         slap_callback   cb = { NULL, NULL, NULL, NULL };
1633         struct berval   *syncuuid_bv = NULL;
1634         struct berval   syncUUID_strrep = BER_BVNULL;
1635         struct berval   uuid_bv = BER_BVNULL;
1636
1637         SlapReply       rs_search = {REP_RESULT};
1638         SlapReply       rs_delete = {REP_RESULT};
1639         SlapReply       rs_add = {REP_RESULT};
1640         SlapReply       rs_modify = {REP_RESULT};
1641         Filter f = {0};
1642 #ifdef LDAP_COMP_MATCH
1643         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1644 #else
1645         AttributeAssertion ava = { NULL, BER_BVNULL };
1646 #endif
1647         int rc = LDAP_SUCCESS;
1648         int ret = LDAP_SUCCESS;
1649
1650         struct berval pdn = BER_BVNULL;
1651         dninfo dni = {0};
1652         int     retry = 1;
1653
1654         switch( syncstate ) {
1655         case LDAP_SYNC_PRESENT:
1656                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1657                                         si->si_rid,
1658                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1659                 break;
1660         case LDAP_SYNC_ADD:
1661                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1662                                         si->si_rid,
1663                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1664                 break;
1665         case LDAP_SYNC_DELETE:
1666                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1667                                         si->si_rid,
1668                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1669                 break;
1670         case LDAP_SYNC_MODIFY:
1671                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1672                                         si->si_rid,
1673                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1674                 break;
1675         default:
1676                 Debug( LDAP_DEBUG_ANY, "syncrepl_entry: rid %03d %s\n",
1677                                         si->si_rid,
1678                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1679         }
1680
1681         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1682                 if ( !si->si_refreshPresent ) {
1683                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1684                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1685                                 syncuuid_cmp, avl_dup_error );
1686                 }
1687         }
1688
1689         if ( syncstate == LDAP_SYNC_PRESENT ) {
1690                 return 0;
1691         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1692                 if ( entry == NULL ) {
1693                         return 0;
1694                 }
1695         }
1696
1697         f.f_choice = LDAP_FILTER_EQUALITY;
1698         f.f_ava = &ava;
1699         ava.aa_desc = slap_schema.si_ad_entryUUID;
1700         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1701         ava.aa_value = *syncUUID;
1702         op->ors_filter = &f;
1703
1704         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
1705         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1706                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1707         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1708         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1709                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
1710         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1711         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1712
1713         op->o_tag = LDAP_REQ_SEARCH;
1714         op->ors_scope = LDAP_SCOPE_SUBTREE;
1715         op->ors_deref = LDAP_DEREF_NEVER;
1716
1717         /* get the entry for this UUID */
1718         op->o_req_dn = si->si_base;
1719         op->o_req_ndn = si->si_base;
1720
1721         op->o_time = slap_get_time();
1722         op->ors_tlimit = SLAP_NO_LIMIT;
1723         op->ors_slimit = 1;
1724
1725         op->ors_attrs = slap_anlist_all_attributes;
1726         op->ors_attrsonly = 0;
1727
1728         /* set callback function */
1729         op->o_callback = &cb;
1730         cb.sc_response = dn_callback;
1731         cb.sc_private = &dni;
1732         dni.new_entry = entry;
1733
1734         if ( limits_check( op, &rs_search ) == 0 ) {
1735                 rc = be->be_search( op, &rs_search );
1736                 Debug( LDAP_DEBUG_SYNC,
1737                                 "syncrepl_entry: rid %03d be_search (%d)\n", 
1738                                 si->si_rid, rc, 0 );
1739         }
1740
1741         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1742                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1743         }
1744
1745         cb.sc_response = null_callback;
1746         cb.sc_private = si;
1747
1748         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1749                 Debug( LDAP_DEBUG_SYNC,
1750                                 "syncrepl_entry: rid %03d %s\n",
1751                                 si->si_rid, entry->e_name.bv_val, 0 );
1752         } else {
1753                 Debug( LDAP_DEBUG_SYNC,
1754                                 "syncrepl_entry: rid %03d %s\n",
1755                                 si->si_rid, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
1756         }
1757
1758         if ( syncstate != LDAP_SYNC_DELETE ) {
1759                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1760
1761                 if ( a == NULL ) {
1762                         /* add if missing */
1763                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1764                                 &syncUUID_strrep, syncUUID );
1765
1766                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1767                         /* replace only if necessary */
1768                         if ( a->a_nvals != a->a_vals ) {
1769                                 ber_memfree( a->a_nvals[0].bv_val );
1770                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1771                         }
1772                         ber_memfree( a->a_vals[0].bv_val );
1773                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1774                 }
1775                 /* Don't save the contextCSN on the inooming context entry,
1776                  * we'll write it when syncrepl_updateCookie eventually
1777                  * gets called. (ITS#4622)
1778                  */
1779                 if ( syncstate == LDAP_SYNC_ADD && dn_match( &entry->e_nname,
1780                         &be->be_nsuffix[0] )) {
1781                         Attribute **ap;
1782                         for ( ap = &entry->e_attrs; *ap; ap=&(*ap)->a_next ) {
1783                                 a = *ap;
1784                                 if ( a->a_desc == slap_schema.si_ad_contextCSN ) {
1785                                         *ap = a->a_next;
1786                                         attr_free( a );
1787                                         break;
1788                                 }
1789                         }
1790                 }
1791         }
1792
1793         slap_op_time( &op->o_time, &op->o_tincr );
1794         switch ( syncstate ) {
1795         case LDAP_SYNC_ADD:
1796         case LDAP_SYNC_MODIFY:
1797                 {
1798                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
1799                         if ( a )
1800                                 op->o_csn = a->a_vals[0];
1801                 }
1802 retry_add:;
1803                 if ( BER_BVISNULL( &dni.dn )) {
1804
1805                         op->o_req_dn = entry->e_name;
1806                         op->o_req_ndn = entry->e_nname;
1807                         op->o_tag = LDAP_REQ_ADD;
1808                         op->ora_e = entry;
1809
1810                         rc = be->be_add( op, &rs_add );
1811                         Debug( LDAP_DEBUG_SYNC,
1812                                         "syncrepl_entry: rid %03d be_add (%d)\n", 
1813                                         si->si_rid, rc, 0 );
1814                         switch ( rs_add.sr_err ) {
1815                         case LDAP_SUCCESS:
1816                                 be_entry_release_w( op, entry );
1817                                 ret = 0;
1818                                 break;
1819
1820                         case LDAP_REFERRAL:
1821                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1822                          * only if the suffix entry is not present */
1823                         case LDAP_NO_SUCH_OBJECT:
1824                                 syncrepl_add_glue( op, entry );
1825                                 ret = 0;
1826                                 break;
1827
1828                         /* if an entry was added via syncrepl_add_glue(),
1829                          * it likely has no entryUUID, so the previous
1830                          * be_search() doesn't find it.  In this case,
1831                          * give syncrepl a chance to modify it. Also
1832                          * allow for entries that were recreated with the
1833                          * same DN but a different entryUUID.
1834                          */
1835                         case LDAP_ALREADY_EXISTS:
1836                                 if ( retry ) {
1837                                         Operation       op2 = *op;
1838                                         SlapReply       rs2 = { 0 };
1839                                         slap_callback   cb2 = { 0 };
1840
1841                                         op2.o_tag = LDAP_REQ_SEARCH;
1842                                         op2.o_req_dn = entry->e_name;
1843                                         op2.o_req_ndn = entry->e_nname;
1844                                         op2.ors_scope = LDAP_SCOPE_BASE;
1845                                         op2.ors_deref = LDAP_DEREF_NEVER;
1846                                         op2.ors_attrs = slap_anlist_all_attributes;
1847                                         op2.ors_attrsonly = 0;
1848                                         op2.ors_limit = NULL;
1849                                         op2.ors_slimit = 1;
1850                                         op2.ors_tlimit = SLAP_NO_LIMIT;
1851
1852                                         f.f_choice = LDAP_FILTER_PRESENT;
1853                                         f.f_desc = slap_schema.si_ad_objectClass;
1854                                         op2.ors_filter = &f;
1855                                         op2.ors_filterstr = generic_filterstr;
1856
1857                                         op2.o_callback = &cb2;
1858                                         cb2.sc_response = dn_callback;
1859                                         cb2.sc_private = &dni;
1860
1861                                         be->be_search( &op2, &rs2 );
1862
1863                                         retry = 0;
1864                                         slap_op_time( &op->o_time, &op->o_tincr );
1865                                         goto retry_add;
1866                                 }
1867                                 /* FALLTHRU */
1868
1869                         default:
1870                                 Debug( LDAP_DEBUG_ANY,
1871                                         "syncrepl_entry: rid %03d be_add failed (%d)\n",
1872                                         si->si_rid, rs_add.sr_err, 0 );
1873                                 ret = 1;
1874                                 break;
1875                         }
1876                         goto done;
1877                 }
1878                 /* FALLTHRU */
1879                 op->o_req_dn = dni.dn;
1880                 op->o_req_ndn = dni.ndn;
1881                 if ( dni.renamed ) {
1882                         struct berval noldp, newp, nnewp;
1883
1884                         op->o_tag = LDAP_REQ_MODRDN;
1885                         dnRdn( &entry->e_name, &op->orr_newrdn );
1886                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
1887
1888                         dnParent( &dni.ndn, &noldp );
1889                         dnParent( &entry->e_nname, &nnewp );
1890                         if ( !dn_match( &noldp, &nnewp )) {
1891                                 dnParent( &entry->e_name, &newp );
1892                                 op->orr_newSup = &newp;
1893                                 op->orr_nnewSup = &nnewp;
1894                         } else {
1895                                 op->orr_newSup = NULL;
1896                                 op->orr_nnewSup = NULL;
1897                         }
1898                         op->orr_deleteoldrdn = 0;
1899                         rc = be->be_modrdn( op, &rs_modify );
1900                         Debug( LDAP_DEBUG_SYNC,
1901                                         "syncrepl_entry: rid %03d be_modrdn (%d)\n", 
1902                                         si->si_rid, rc, 0 );
1903                         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
1904                                 op->o_req_dn = entry->e_name;
1905                                 op->o_req_ndn = entry->e_nname;
1906                         } else {
1907                                 ret = 1;
1908                                 goto done;
1909                         }
1910                         if ( dni.wasChanged )
1911                                 slap_op_time( &op->o_time, &op->o_tincr );
1912                 }
1913                 if ( dni.wasChanged ) {
1914                         Modifications *mod, *modhead = NULL;
1915                         Modifications *modtail = NULL;
1916                         int i;
1917
1918                         op->o_tag = LDAP_REQ_MODIFY;
1919
1920                         assert( *modlist != NULL );
1921
1922                         /* Delete all the old attrs */
1923                         for ( i = 0; i < dni.attrs; i++ ) {
1924                                 mod = ch_malloc( sizeof( Modifications ) );
1925                                 mod->sml_op = LDAP_MOD_DELETE;
1926                                 mod->sml_flags = 0;
1927                                 mod->sml_desc = dni.ads[i];
1928                                 mod->sml_type = mod->sml_desc->ad_cname;
1929                                 mod->sml_values = NULL;
1930                                 mod->sml_nvalues = NULL;
1931                                 if ( !modhead ) modhead = mod;
1932                                 if ( modtail ) {
1933                                         modtail->sml_next = mod;
1934                                 }
1935                                 modtail = mod;
1936                         }
1937
1938                         /* Append passed in list to ours */
1939                         if ( modtail ) {
1940                                 modtail->sml_next = *modlist;
1941                                 *modlist = modhead;
1942                         } else {
1943                                 mod = *modlist;
1944                         }
1945
1946                         /* Find end of this list */
1947                         for ( ; mod != NULL; mod = mod->sml_next ) {
1948                                 modtail = mod;
1949                         }
1950
1951                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1952                         mod->sml_op = LDAP_MOD_REPLACE;
1953                         mod->sml_flags = 0;
1954                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1955                         mod->sml_type = mod->sml_desc->ad_cname;
1956                         ber_dupbv( &uuid_bv, &syncUUID_strrep );
1957                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1958                         ber_dupbv( &uuid_bv, syncUUID );
1959                         ber_bvarray_add( &mod->sml_nvalues, &uuid_bv );
1960                         modtail->sml_next = mod;
1961                                         
1962                         op->o_tag = LDAP_REQ_MODIFY;
1963                         op->orm_modlist = *modlist;
1964
1965                         rc = be->be_modify( op, &rs_modify );
1966                         Debug( LDAP_DEBUG_SYNC,
1967                                         "syncrepl_entry: rid %03d be_modify (%d)\n", 
1968                                         si->si_rid, rc, 0 );
1969                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1970                                 Debug( LDAP_DEBUG_ANY,
1971                                         "syncrepl_entry: rid %03d be_modify failed (%d)\n",
1972                                         si->si_rid, rs_modify.sr_err, 0 );
1973                         }
1974                 }
1975                 ret = 1;
1976                 goto done;
1977         case LDAP_SYNC_DELETE :
1978                 if ( !BER_BVISNULL( &dni.dn )) {
1979                         op->o_req_dn = dni.dn;
1980                         op->o_req_ndn = dni.ndn;
1981                         op->o_tag = LDAP_REQ_DELETE;
1982                         rc = be->be_delete( op, &rs_delete );
1983                         Debug( LDAP_DEBUG_SYNC,
1984                                         "syncrepl_entry: rid %03d be_delete (%d)\n", 
1985                                         si->si_rid, rc, 0 );
1986
1987                         while ( rs_delete.sr_err == LDAP_SUCCESS
1988                                 && op->o_delete_glue_parent ) {
1989                                 op->o_delete_glue_parent = 0;
1990                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1991                                         slap_callback cb = { NULL };
1992                                         cb.sc_response = slap_null_cb;
1993                                         dnParent( &op->o_req_ndn, &pdn );
1994                                         op->o_req_dn = pdn;
1995                                         op->o_req_ndn = pdn;
1996                                         op->o_callback = &cb;
1997                                         op->o_bd->be_delete( op, &rs_delete );
1998                                 } else {
1999                                         break;
2000                                 }
2001                         }
2002                 }
2003                 ret = 0;
2004                 goto done;
2005
2006         default :
2007                 Debug( LDAP_DEBUG_ANY,
2008                         "syncrepl_entry: rid %03d unknown syncstate\n", si->si_rid, 0, 0 );
2009                 ret = 1;
2010                 goto done;
2011         }
2012
2013 done :
2014         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2015                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2016                 BER_BVZERO( &syncUUID_strrep );
2017         }
2018         if ( dni.ads ) {
2019                 op->o_tmpfree( dni.ads, op->o_tmpmemctx );
2020         }
2021         if ( !BER_BVISNULL( &dni.ndn ) ) {
2022                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2023         }
2024         if ( !BER_BVISNULL( &dni.dn ) ) {
2025                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2026         }
2027         BER_BVZERO( &op->o_csn );
2028         return ret;
2029 }
2030
2031 static struct berval gcbva[] = {
2032         BER_BVC("top"),
2033         BER_BVC("glue"),
2034         BER_BVNULL
2035 };
2036
2037 #define NP_DELETE_ONE   2
2038
2039 static void
2040 syncrepl_del_nonpresent(
2041         Operation *op,
2042         syncinfo_t *si,
2043         BerVarray uuids,
2044         struct berval *cookiecsn )
2045 {
2046         Backend* be = op->o_bd;
2047         slap_callback   cb = { NULL };
2048         SlapReply       rs_search = {REP_RESULT};
2049         SlapReply       rs_delete = {REP_RESULT};
2050         SlapReply       rs_modify = {REP_RESULT};
2051         struct nonpresent_entry *np_list, *np_prev;
2052         int rc;
2053         AttributeName   an[2];
2054
2055         struct berval pdn = BER_BVNULL;
2056         struct berval csn;
2057
2058         op->o_req_dn = si->si_base;
2059         op->o_req_ndn = si->si_base;
2060
2061         cb.sc_response = nonpresent_callback;
2062         cb.sc_private = si;
2063
2064         op->o_callback = &cb;
2065         op->o_tag = LDAP_REQ_SEARCH;
2066         op->ors_scope = si->si_scope;
2067         op->ors_deref = LDAP_DEREF_NEVER;
2068         op->o_time = slap_get_time();
2069         op->ors_tlimit = SLAP_NO_LIMIT;
2070
2071
2072         if ( uuids ) {
2073                 Filter uf;
2074 #ifdef LDAP_COMP_MATCH
2075                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
2076 #else
2077                 AttributeAssertion eq = { NULL, BER_BVNULL };
2078 #endif
2079                 int i;
2080
2081                 op->ors_attrsonly = 1;
2082                 op->ors_attrs = slap_anlist_no_attrs;
2083                 op->ors_limit = NULL;
2084                 op->ors_filter = &uf;
2085
2086                 uf.f_ava = &eq;
2087                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2088                 uf.f_next = NULL;
2089                 uf.f_choice = LDAP_FILTER_EQUALITY;
2090                 si->si_refreshDelete |= NP_DELETE_ONE;
2091
2092                 for (i=0; uuids[i].bv_val; i++) {
2093                         op->ors_slimit = 1;
2094                         slap_uuidstr_from_normalized( &uf.f_av_value, &uuids[i],
2095                                 op->o_tmpmemctx );
2096                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2097                         op->o_tmpfree( uf.f_av_value.bv_val, op->o_tmpmemctx );
2098                         uf.f_av_value = uuids[i];
2099                         rc = be->be_search( op, &rs_search );
2100                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2101                 }
2102                 si->si_refreshDelete ^= NP_DELETE_ONE;
2103         } else {
2104                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2105                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2106                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2107                 op->ors_attrs = an;
2108                 op->ors_slimit = SLAP_NO_LIMIT;
2109                 op->ors_attrsonly = 0;
2110                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2111                 op->ors_filterstr = si->si_filterstr;
2112                 op->o_nocaching = 1;
2113
2114                 if ( limits_check( op, &rs_search ) == 0 ) {
2115                         rc = be->be_search( op, &rs_search );
2116                 }
2117                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
2118         }
2119
2120         op->o_nocaching = 0;
2121
2122         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2123
2124                 if ( cookiecsn && !BER_BVISNULL( cookiecsn ))
2125                         csn = *cookiecsn;
2126                 else
2127                         csn = si->si_syncCookie.ctxcsn;
2128
2129                 slap_queue_csn( op, &csn );
2130
2131                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2132                 while ( np_list != NULL ) {
2133                         LDAP_LIST_REMOVE( np_list, npe_link );
2134                         np_prev = np_list;
2135                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2136                         op->o_tag = LDAP_REQ_DELETE;
2137                         op->o_callback = &cb;
2138                         cb.sc_response = null_callback;
2139                         cb.sc_private = si;
2140                         op->o_req_dn = *np_prev->npe_name;
2141                         op->o_req_ndn = *np_prev->npe_nname;
2142                         rc = op->o_bd->be_delete( op, &rs_delete );
2143                         Debug( LDAP_DEBUG_SYNC,
2144                                 "syncrepl_del_nonpresent: rid %03d be_delete %s (%d)\n", 
2145                                 si->si_rid, op->o_req_dn.bv_val, rc );
2146
2147                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2148                                 Modifications mod1, mod2;
2149                                 mod1.sml_op = LDAP_MOD_REPLACE;
2150                                 mod1.sml_flags = 0;
2151                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2152                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2153                                 mod1.sml_values = &gcbva[0];
2154                                 mod1.sml_nvalues = NULL;
2155                                 mod1.sml_next = &mod2;
2156
2157                                 mod2.sml_op = LDAP_MOD_REPLACE;
2158                                 mod2.sml_flags = 0;
2159                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2160                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2161                                 mod2.sml_values = &gcbva[1];
2162                                 mod2.sml_nvalues = NULL;
2163                                 mod2.sml_next = NULL;
2164
2165                                 op->o_tag = LDAP_REQ_MODIFY;
2166                                 op->orm_modlist = &mod1;
2167
2168                                 rc = be->be_modify( op, &rs_modify );
2169                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2170                         }
2171
2172                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2173                                         op->o_delete_glue_parent ) {
2174                                 op->o_delete_glue_parent = 0;
2175                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
2176                                         slap_callback cb = { NULL };
2177                                         cb.sc_response = slap_null_cb;
2178                                         dnParent( &op->o_req_ndn, &pdn );
2179                                         op->o_req_dn = pdn;
2180                                         op->o_req_ndn = pdn;
2181                                         op->o_callback = &cb;
2182                                         /* give it a root privil ? */
2183                                         op->o_bd->be_delete( op, &rs_delete );
2184                                 } else {
2185                                         break;
2186                             }
2187                         }
2188
2189                         op->o_delete_glue_parent = 0;
2190
2191                         ber_bvfree( np_prev->npe_name );
2192                         ber_bvfree( np_prev->npe_nname );
2193                         ch_free( np_prev );
2194                 }
2195
2196                 slap_graduate_commit_csn( op );
2197                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2198                 BER_BVZERO( &op->o_csn );
2199         }
2200
2201         return;
2202 }
2203
2204 void
2205 syncrepl_add_glue(
2206         Operation* op,
2207         Entry *e )
2208 {
2209         Backend *be = op->o_bd;
2210         slap_callback cb = { NULL };
2211         Attribute       *a;
2212         int     rc;
2213         int suffrdns;
2214         int i;
2215         struct berval dn = BER_BVNULL;
2216         struct berval ndn = BER_BVNULL;
2217         Entry   *glue;
2218         SlapReply       rs_add = {REP_RESULT};
2219         struct berval   ptr, nptr;
2220         char            *comma;
2221
2222         op->o_tag = LDAP_REQ_ADD;
2223         op->o_callback = &cb;
2224         cb.sc_response = null_callback;
2225         cb.sc_private = NULL;
2226
2227         dn = e->e_name;
2228         ndn = e->e_nname;
2229
2230         /* count RDNs in suffix */
2231         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2232                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2233                         comma++;
2234                         ptr.bv_len -= comma - ptr.bv_val;
2235                         ptr.bv_val = comma;
2236                         i++;
2237                 }
2238                 suffrdns = i;
2239         } else {
2240                 /* suffix is "" */
2241                 suffrdns = 0;
2242         }
2243
2244         /* Start with BE suffix */
2245         ptr = dn;
2246         for ( i = 0; i < suffrdns; i++ ) {
2247                 comma = ber_bvrchr( &ptr, ',' );
2248                 if ( comma != NULL ) {
2249                         ptr.bv_len = comma - ptr.bv_val;
2250                 } else {
2251                         ptr.bv_len = 0;
2252                         break;
2253                 }
2254         }
2255         
2256         if ( !BER_BVISEMPTY( &ptr ) ) {
2257                 dn.bv_len -= ptr.bv_len + 1;
2258                 dn.bv_val += ptr.bv_len + 1;
2259         }
2260
2261         /* the normalizedDNs are always the same length, no counting
2262          * required.
2263          */
2264         nptr = ndn;
2265         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2266                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2267                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2268
2269                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2270
2271         } else {
2272                 nptr.bv_len = 0;
2273         }
2274
2275         while ( ndn.bv_val > e->e_nname.bv_val ) {
2276                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
2277                 ber_dupbv( &glue->e_name, &dn );
2278                 ber_dupbv( &glue->e_nname, &ndn );
2279
2280                 a = ch_calloc( 1, sizeof( Attribute ));
2281                 a->a_desc = slap_schema.si_ad_objectClass;
2282
2283                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
2284                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2285                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2286                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2287
2288                 a->a_nvals = a->a_vals;
2289
2290                 a->a_next = glue->e_attrs;
2291                 glue->e_attrs = a;
2292
2293                 a = ch_calloc( 1, sizeof( Attribute ));
2294                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
2295
2296                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
2297                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2298                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2299
2300                 a->a_nvals = a->a_vals;
2301
2302                 a->a_next = glue->e_attrs;
2303                 glue->e_attrs = a;
2304
2305                 op->o_req_dn = glue->e_name;
2306                 op->o_req_ndn = glue->e_nname;
2307                 op->ora_e = glue;
2308                 rc = be->be_add ( op, &rs_add );
2309                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2310                         be_entry_release_w( op, glue );
2311                 } else {
2312                 /* incl. ALREADY EXIST */
2313                         entry_free( glue );
2314                 }
2315
2316                 /* Move to next child */
2317                 comma = ber_bvrchr( &ptr, ',' );
2318                 if ( comma == NULL ) {
2319                         break;
2320                 }
2321                 ptr.bv_len = comma - ptr.bv_val;
2322                 
2323                 dn.bv_val = ++comma;
2324                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2325
2326                 comma = ber_bvrchr( &nptr, ',' );
2327                 assert( comma != NULL );
2328                 nptr.bv_len = comma - nptr.bv_val;
2329
2330                 ndn.bv_val = ++comma;
2331                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2332         }
2333
2334         op->o_req_dn = e->e_name;
2335         op->o_req_ndn = e->e_nname;
2336         op->ora_e = e;
2337         rc = be->be_add ( op, &rs_add );
2338         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2339                 be_entry_release_w( op, e );
2340         } else {
2341                 entry_free( e );
2342         }
2343
2344         return;
2345 }
2346
2347 static void
2348 syncrepl_updateCookie(
2349         syncinfo_t *si,
2350         Operation *op,
2351         struct berval *pdn,
2352         struct sync_cookie *syncCookie )
2353 {
2354         Backend *be = op->o_bd;
2355         Modifications mod = { { 0 } };
2356         struct berval vals[ 2 ];
2357
2358         int rc;
2359
2360         slap_callback cb = { NULL };
2361         SlapReply       rs_modify = {REP_RESULT};
2362
2363         slap_sync_cookie_free( &si->si_syncCookie, 0 );
2364         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2365
2366         mod.sml_op = LDAP_MOD_REPLACE;
2367         mod.sml_desc = slap_schema.si_ad_contextCSN;
2368         mod.sml_type = mod.sml_desc->ad_cname;
2369         mod.sml_values = vals;
2370         vals[0] = si->si_syncCookie.ctxcsn;
2371         vals[1].bv_val = NULL;
2372         vals[1].bv_len = 0;
2373
2374         slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
2375
2376         op->o_tag = LDAP_REQ_MODIFY;
2377
2378         assert( si->si_rid < 1000 );
2379
2380         cb.sc_response = null_callback;
2381         cb.sc_private = si;
2382
2383         op->o_callback = &cb;
2384         op->o_req_dn = op->o_bd->be_suffix[0];
2385         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2386
2387         /* update contextCSN */
2388         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2389         op->orm_modlist = &mod;
2390         rc = be->be_modify( op, &rs_modify );
2391         op->o_msgid = 0;
2392
2393         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2394                 Debug( LDAP_DEBUG_ANY,
2395                         "syncrepl_updateCookie: rid %03d be_modify failed (%d)\n",
2396                         si->si_rid, rs_modify.sr_err, 0 );
2397         }
2398
2399         slap_graduate_commit_csn( op );
2400         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2401         BER_BVZERO( &op->o_csn );
2402         if ( mod.sml_next ) slap_mods_free( mod.sml_next, 1 );
2403
2404         return;
2405 }
2406
2407 static int
2408 dn_callback(
2409         Operation*      op,
2410         SlapReply*      rs )
2411 {
2412         dninfo *dni = op->o_callback->sc_private;
2413
2414         if ( rs->sr_type == REP_SEARCH ) {
2415                 if ( !BER_BVISNULL( &dni->dn ) ) {
2416                         Debug( LDAP_DEBUG_ANY,
2417                                 "dn_callback: consistency error - "
2418                                 "entryUUID is not unique\n", 0, 0, 0 );
2419                 } else {
2420                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2421                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2422                         /* If there is a new entry, see if it differs from the old.
2423                          * We compare the non-normalized values so that cosmetic changes
2424                          * in the provider are always propagated.
2425                          */
2426                         if ( dni->new_entry ) {
2427                                 Attribute *old, *new;
2428                                 int i;
2429
2430                                 /* Did the DN change? Note that we don't explicitly try to
2431                                  * discover if the deleteOldRdn argument applies here. It
2432                                  * would save an unnecessary Modify if we detected it, but
2433                                  * that's a fair amount of trouble to compare the two attr
2434                                  * lists in detail. (Just test normalized DN; we ignore
2435                                  * insignificant changes here.)
2436                                  */
2437                                 if ( !dn_match( &rs->sr_entry->e_nname,
2438                                                 &dni->new_entry->e_nname ) )
2439                                 {
2440                                         dni->renamed = 1;
2441                                 }
2442
2443                                 for ( i = 0, old = rs->sr_entry->e_attrs;
2444                                                 old;
2445                                                 i++, old = old->a_next )
2446                                         ;
2447
2448                                 dni->attrs = i;
2449
2450                                 /* We assume that attributes are saved in the same order
2451                                  * in the remote and local databases. So if we walk through
2452                                  * the attributeDescriptions one by one they should match in
2453                                  * lock step. If not, we signal a change. Otherwise we test
2454                                  * all the values...
2455                                  */
2456                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2457                                                 old && new;
2458                                                 old = old->a_next, new = new->a_next )
2459                                 {
2460                                         if ( old->a_desc != new->a_desc ) {
2461                                                 dni->wasChanged = 1;
2462                                                 break;
2463                                         }
2464                                         for ( i = 0; ; i++ ) {
2465                                                 int nold, nnew;
2466                                                 nold = BER_BVISNULL( &old->a_vals[i] );
2467                                                 nnew = BER_BVISNULL( &new->a_vals[i] );
2468                                                 /* If both are empty, stop looking */
2469                                                 if ( nold && nnew ) {
2470                                                         break;
2471                                                 }
2472                                                 /* If they are different, stop looking */
2473                                                 if ( nold != nnew ) {
2474                                                         dni->wasChanged = 1;
2475                                                         break;
2476                                                 }
2477                                                 if ( ber_bvcmp( &old->a_vals[i], &new->a_vals[i] )) {
2478                                                         dni->wasChanged = 1;
2479                                                         break;
2480                                                 }
2481                                         }
2482                                         if ( dni->wasChanged ) break;
2483                                 }
2484                                 if ( dni->wasChanged ) {
2485                                         dni->ads = op->o_tmpalloc( dni->attrs *
2486                                                 sizeof(AttributeDescription *), op->o_tmpmemctx );
2487                                         i = 0;
2488                                         for ( old = rs->sr_entry->e_attrs; old; old = old->a_next ) {
2489                                                 dni->ads[i] = old->a_desc;
2490                                                 i++;
2491                                         }
2492                                 }
2493                         }
2494                 }
2495         } else if ( rs->sr_type == REP_RESULT ) {
2496                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2497                         Debug( LDAP_DEBUG_ANY,
2498                                 "dn_callback: consistency error - "
2499                                 "entryUUID is not unique\n", 0, 0, 0 );
2500                 }
2501         }
2502
2503         return LDAP_SUCCESS;
2504 }
2505
2506 static int
2507 nonpresent_callback(
2508         Operation*      op,
2509         SlapReply*      rs )
2510 {
2511         syncinfo_t *si = op->o_callback->sc_private;
2512         Attribute *a;
2513         int count = 0;
2514         struct berval* present_uuid = NULL;
2515         struct nonpresent_entry *np_entry;
2516
2517         if ( rs->sr_type == REP_RESULT ) {
2518                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2519                 si->si_presentlist = NULL;
2520
2521         } else if ( rs->sr_type == REP_SEARCH ) {
2522                 if ( !(si->si_refreshDelete & NP_DELETE_ONE )) {
2523                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2524
2525                         if ( a == NULL ) return 0;
2526
2527                         present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2528                                 syncuuid_cmp );
2529                 }
2530
2531                 if ( present_uuid == NULL ) {
2532                         np_entry = (struct nonpresent_entry *)
2533                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2534                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2535                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2536                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2537
2538                 } else {
2539                         avl_delete( &si->si_presentlist,
2540                                         &a->a_nvals[0], syncuuid_cmp );
2541                         ch_free( present_uuid->bv_val );
2542                         ch_free( present_uuid );
2543                 }
2544         }
2545         return LDAP_SUCCESS;
2546 }
2547
2548 static int
2549 null_callback(
2550         Operation*      op,
2551         SlapReply*      rs )
2552 {
2553         if ( rs->sr_err != LDAP_SUCCESS &&
2554                 rs->sr_err != LDAP_REFERRAL &&
2555                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2556                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2557                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2558         {
2559                 Debug( LDAP_DEBUG_ANY,
2560                         "null_callback: error code 0x%x\n",
2561                         rs->sr_err, 0, 0 );
2562         }
2563         return LDAP_SUCCESS;
2564 }
2565
2566 static struct berval *
2567 slap_uuidstr_from_normalized(
2568         struct berval* uuidstr,
2569         struct berval* normalized,
2570         void *ctx )
2571 {
2572         struct berval *new;
2573         unsigned char nibble;
2574         int i, d = 0;
2575
2576         if ( normalized == NULL ) return NULL;
2577         if ( normalized->bv_len != 16 ) return NULL;
2578
2579         if ( uuidstr ) {
2580                 new = uuidstr;
2581         } else {
2582                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2583                 if ( new == NULL ) {
2584                         return NULL;
2585                 }
2586         }
2587
2588         new->bv_len = 36;
2589
2590         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2591                 if ( new != uuidstr ) {
2592                         slap_sl_free( new, ctx );
2593                 }
2594                 return NULL;
2595         }
2596
2597         for ( i = 0; i < 16; i++ ) {
2598                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2599                         new->bv_val[(i<<1)+d] = '-';
2600                         d += 1;
2601                 }
2602
2603                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2604                 if ( nibble < 10 ) {
2605                         new->bv_val[(i<<1)+d] = nibble + '0';
2606                 } else {
2607                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2608                 }
2609
2610                 nibble = (normalized->bv_val[i]) & 0xF;
2611                 if ( nibble < 10 ) {
2612                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2613                 } else {
2614                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2615                 }
2616         }
2617
2618         new->bv_val[new->bv_len] = '\0';
2619         return new;
2620 }
2621
2622 static int
2623 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2624 {
2625         const struct berval *uuid1 = v_uuid1;
2626         const struct berval *uuid2 = v_uuid2;
2627         int rc = uuid1->bv_len - uuid2->bv_len;
2628         if ( rc ) return rc;
2629         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2630 }
2631
2632 static void
2633 avl_ber_bvfree( void *v_bv )
2634 {
2635         struct berval   *bv = (struct berval *)v_bv;
2636         
2637         if( v_bv == NULL ) return;
2638         if ( !BER_BVISNULL( bv ) ) {
2639                 ch_free( bv->bv_val );
2640         }
2641         ch_free( (char *) bv );
2642 }
2643
2644 void
2645 syncinfo_free( syncinfo_t *sie )
2646 {
2647         if ( sie->si_ld ) {
2648                 if ( sie->si_conn_setup ) {
2649                         ber_socket_t s;
2650                         ldap_get_option( sie->si_ld, LDAP_OPT_DESC, &s );
2651                         connection_client_stop( s );
2652                         sie->si_conn_setup = 0;
2653                 }
2654                 ldap_unbind_ext( sie->si_ld, NULL, NULL );
2655         }
2656
2657         ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
2658
2659         bindconf_free( &sie->si_bindconf );
2660
2661         if ( sie->si_filterstr.bv_val ) {
2662                 ch_free( sie->si_filterstr.bv_val );
2663         }
2664         if ( sie->si_base.bv_val ) {
2665                 ch_free( sie->si_base.bv_val );
2666         }
2667         if ( sie->si_attrs ) {
2668                 int i = 0;
2669                 while ( sie->si_attrs[i] != NULL ) {
2670                         ch_free( sie->si_attrs[i] );
2671                         i++;
2672                 }
2673                 ch_free( sie->si_attrs );
2674         }
2675         if ( sie->si_exattrs ) {
2676                 int i = 0;
2677                 while ( sie->si_exattrs[i] != NULL ) {
2678                         ch_free( sie->si_exattrs[i] );
2679                         i++;
2680                 }
2681                 ch_free( sie->si_exattrs );
2682         }
2683         if ( sie->si_anlist ) {
2684                 int i = 0;
2685                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2686                         ch_free( sie->si_anlist[i].an_name.bv_val );
2687                         i++;
2688                 }
2689                 ch_free( sie->si_anlist );
2690         }
2691         if ( sie->si_exanlist ) {
2692                 int i = 0;
2693                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2694                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2695                         i++;
2696                 }
2697                 ch_free( sie->si_exanlist );
2698         }
2699         if ( sie->si_retryinterval ) {
2700                 ch_free( sie->si_retryinterval );
2701         }
2702         if ( sie->si_retrynum ) {
2703                 ch_free( sie->si_retrynum );
2704         }
2705         if ( sie->si_retrynum_init ) {
2706                 ch_free( sie->si_retrynum_init );
2707         }
2708         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2709         if ( sie->si_presentlist ) {
2710             avl_free( sie->si_presentlist, avl_ber_bvfree );
2711         }
2712         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2713                 struct nonpresent_entry* npe;
2714                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2715                 LDAP_LIST_REMOVE( npe, npe_link );
2716                 if ( npe->npe_name ) {
2717                         if ( npe->npe_name->bv_val ) {
2718                                 ch_free( npe->npe_name->bv_val );
2719                         }
2720                         ch_free( npe->npe_name );
2721                 }
2722                 if ( npe->npe_nname ) {
2723                         if ( npe->npe_nname->bv_val ) {
2724                                 ch_free( npe->npe_nname->bv_val );
2725                         }
2726                         ch_free( npe->npe_nname );
2727                 }
2728                 ch_free( npe );
2729         }
2730         ch_free( sie );
2731 }
2732
2733
2734
2735 /* NOTE: used & documented in slapd.conf(5) */
2736 #define IDSTR                   "rid"
2737 #define PROVIDERSTR             "provider"
2738 #define SCHEMASTR               "schemachecking"
2739 #define FILTERSTR               "filter"
2740 #define SEARCHBASESTR           "searchbase"
2741 #define SCOPESTR                "scope"
2742 #define ATTRSONLYSTR            "attrsonly"
2743 #define ATTRSSTR                "attrs"
2744 #define TYPESTR                 "type"
2745 #define INTERVALSTR             "interval"
2746 #define RETRYSTR                "retry"
2747 #define SLIMITSTR               "sizelimit"
2748 #define TLIMITSTR               "timelimit"
2749 #define SYNCDATASTR             "syncdata"
2750
2751 /* FIXME: undocumented */
2752 #define LOGBASESTR      "logbase"
2753 #define LOGFILTERSTR    "logfilter"
2754 #define OLDAUTHCSTR             "bindprincipal"
2755 #define EXATTRSSTR              "exattrs"
2756 #define MANAGEDSAITSTR          "manageDSAit"
2757
2758 /* FIXME: unused */
2759 #define LASTMODSTR              "lastmod"
2760 #define LMGENSTR                "gen"
2761 #define LMNOSTR                 "no"
2762 #define LMREQSTR                "req"
2763 #define SRVTABSTR               "srvtab"
2764 #define SUFFIXSTR               "suffix"
2765
2766 /* mandatory */
2767 #define GOT_ID                  0x0001
2768 #define GOT_PROVIDER            0x0002
2769 #define GOT_BASE                0x0004
2770
2771 /* check */
2772 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER|GOT_BASE)
2773
2774 static struct {
2775         struct berval key;
2776         int val;
2777 } scopes[] = {
2778         { BER_BVC("base"), LDAP_SCOPE_BASE },
2779         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
2780         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
2781         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
2782         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
2783         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
2784         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
2785         { BER_BVNULL, 0 }
2786 };
2787
2788 static slap_verbmasks datamodes[] = {
2789         { BER_BVC("default"), SYNCDATA_DEFAULT },
2790         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
2791         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
2792         { BER_BVNULL, 0 }
2793 };
2794
2795 static int
2796 parse_syncrepl_line(
2797         ConfigArgs      *c,
2798         syncinfo_t      *si )
2799 {
2800         int     gots = 0;
2801         int     i;
2802         char    *val;
2803
2804         for ( i = 1; i < c->argc; i++ ) {
2805                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
2806                                         STRLENOF( IDSTR "=" ) ) )
2807                 {
2808                         int tmp;
2809                         /* '\0' string terminator accounts for '=' */
2810                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
2811                         if ( lutil_atoi( &tmp, val ) != 0 ) {
2812                                 snprintf( c->msg, sizeof( c->msg ),
2813                                         "Error: parse_syncrepl_line: "
2814                                         "unable to parse syncrepl id \"%s\"", val );
2815                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2816                                 return -1;
2817                         }
2818                         if ( tmp >= 1000 || tmp < 0 ) {
2819                                 snprintf( c->msg, sizeof( c->msg ),
2820                                         "Error: parse_syncrepl_line: "
2821                                         "syncrepl id %d is out of range [0..999]", tmp );
2822                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2823                                 return -1;
2824                         }
2825                         si->si_rid = tmp;
2826                         gots |= GOT_ID;
2827                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
2828                                         STRLENOF( PROVIDERSTR "=" ) ) )
2829                 {
2830                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
2831                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
2832                         gots |= GOT_PROVIDER;
2833                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
2834                                         STRLENOF( SCHEMASTR "=" ) ) )
2835                 {
2836                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
2837                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) )) {
2838                                 si->si_schemachecking = 1;
2839                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
2840                                 si->si_schemachecking = 0;
2841                         } else {
2842                                 si->si_schemachecking = 1;
2843                         }
2844                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
2845                                         STRLENOF( FILTERSTR "=" ) ) )
2846                 {
2847                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
2848                         if ( si->si_filterstr.bv_val )
2849                                 ch_free( si->si_filterstr.bv_val );
2850                         ber_str2bv( val, 0, 1, &si->si_filterstr );
2851                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
2852                                         STRLENOF( LOGFILTERSTR "=" ) ) )
2853                 {
2854                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
2855                         if ( si->si_logfilterstr.bv_val )
2856                                 ch_free( si->si_logfilterstr.bv_val );
2857                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
2858                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
2859                                         STRLENOF( SEARCHBASESTR "=" ) ) )
2860                 {
2861                         struct berval   bv;
2862                         int             rc;
2863
2864                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
2865                         if ( si->si_base.bv_val ) {
2866                                 ch_free( si->si_base.bv_val );
2867                         }
2868                         ber_str2bv( val, 0, 0, &bv );
2869                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
2870                         if ( rc != LDAP_SUCCESS ) {
2871                                 snprintf( c->msg, sizeof( c->msg ),
2872                                         "Invalid base DN \"%s\": %d (%s)",
2873                                         val, rc, ldap_err2string( rc ) );
2874                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2875                                 return -1;
2876                         }
2877                         gots |= GOT_BASE;
2878                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
2879                                         STRLENOF( LOGBASESTR "=" ) ) )
2880                 {
2881                         struct berval   bv;
2882                         int             rc;
2883
2884                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
2885                         if ( si->si_logbase.bv_val ) {
2886                                 ch_free( si->si_logbase.bv_val );
2887                         }
2888                         ber_str2bv( val, 0, 0, &bv );
2889                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
2890                         if ( rc != LDAP_SUCCESS ) {
2891                                 snprintf( c->msg, sizeof( c->msg ),
2892                                         "Invalid logbase DN \"%s\": %d (%s)",
2893                                         val, rc, ldap_err2string( rc ) );
2894                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2895                                 return -1;
2896                         }
2897                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
2898                                         STRLENOF( SCOPESTR "=" ) ) )
2899                 {
2900                         int j;
2901                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
2902                         for ( j=0; !BER_BVISNULL(&scopes[j].key); j++ ) {
2903                                 if (!strcasecmp( val, scopes[j].key.bv_val )) {
2904                                         si->si_scope = scopes[j].val;
2905                                         break;
2906                                 }
2907                         }
2908                         if ( BER_BVISNULL(&scopes[j].key) ) {
2909                                 snprintf( c->msg, sizeof( c->msg ),
2910                                         "Error: parse_syncrepl_line: "
2911                                         "unknown scope \"%s\"", val);
2912                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2913                                 return -1;
2914                         }
2915                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
2916                                         STRLENOF( ATTRSONLYSTR ) ) )
2917                 {
2918                         si->si_attrsonly = 1;
2919                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
2920                                         STRLENOF( ATTRSSTR "=" ) ) )
2921                 {
2922                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
2923                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
2924                                 char *attr_fname;
2925                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2926                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
2927                                 if ( si->si_anlist == NULL ) {
2928                                         ch_free( attr_fname );
2929                                         return -1;
2930                                 }
2931                                 si->si_anfile = attr_fname;
2932                         } else {
2933                                 char *str, *s, *next;
2934                                 char delimstr[] = " ,\t";
2935                                 str = ch_strdup( val );
2936                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
2937                                                 s != NULL;
2938                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
2939                                 {
2940                                         if ( strlen(s) == 1 && *s == '*' ) {
2941                                                 si->si_allattrs = 1;
2942                                                 *(val + ( s - str )) = delimstr[0];
2943                                         }
2944                                         if ( strlen(s) == 1 && *s == '+' ) {
2945                                                 si->si_allopattrs = 1;
2946                                                 *(val + ( s - str )) = delimstr[0];
2947                                         }
2948                                 }
2949                                 ch_free( str );
2950                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
2951                                 if ( si->si_anlist == NULL ) {
2952                                         return -1;
2953                                 }
2954                         }
2955                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
2956                                         STRLENOF( EXATTRSSTR "=" ) ) )
2957                 {
2958                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
2959                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") )) {
2960                                 char *attr_fname;
2961                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2962                                 si->si_exanlist = file2anlist(
2963                                         si->si_exanlist, attr_fname, " ,\t" );
2964                                 if ( si->si_exanlist == NULL ) {
2965                                         ch_free( attr_fname );
2966                                         return -1;
2967                                 }
2968                                 ch_free( attr_fname );
2969                         } else {
2970                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
2971                                 if ( si->si_exanlist == NULL ) {
2972                                         return -1;
2973                                 }
2974                         }
2975                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
2976                                         STRLENOF( TYPESTR "=" ) ) )
2977                 {
2978                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
2979                         if ( !strncasecmp( val, "refreshOnly",
2980                                                 STRLENOF("refreshOnly") ) )
2981                         {
2982                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
2983                         } else if ( !strncasecmp( val, "refreshAndPersist",
2984                                                 STRLENOF("refreshAndPersist") ) )
2985                         {
2986                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
2987                                 si->si_interval = 60;
2988                         } else {
2989                                 snprintf( c->msg, sizeof( c->msg ),
2990                                         "Error: parse_syncrepl_line: "
2991                                         "unknown sync type \"%s\"", val);
2992                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2993                                 return -1;
2994                         }
2995                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
2996                                         STRLENOF( INTERVALSTR "=" ) ) )
2997                 {
2998                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
2999                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
3000                                 si->si_interval = 0;
3001                         } else if ( strchr( val, ':' ) != NULL ) {
3002                                 char *next, *ptr = val;
3003                                 unsigned dd, hh, mm, ss;
3004                                 
3005                                 /* NOTE: the test for ptr[ 0 ] == '-'
3006                                  * should go before the call to strtoul() */
3007                                 dd = strtoul( ptr, &next, 10 );
3008                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' ) {
3009                                         snprintf( c->msg, sizeof( c->msg ),
3010                                                 "Error: parse_syncrepl_line: "
3011                                                 "invalid interval \"%s\", unable to parse days", val );
3012                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3013                                         return -1;
3014                                 }
3015                                 ptr = next + 1;
3016                                 hh = strtoul( ptr, &next, 10 );
3017                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || hh > 24 ) {
3018                                         snprintf( c->msg, sizeof( c->msg ),
3019                                                 "Error: parse_syncrepl_line: "
3020                                                 "invalid interval \"%s\", unable to parse hours", val );
3021                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3022                                         return -1;
3023                                 }
3024                                 ptr = next + 1;
3025                                 mm = strtoul( ptr, &next, 10 );
3026                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || mm > 60 ) {
3027                                         snprintf( c->msg, sizeof( c->msg ),
3028                                                 "Error: parse_syncrepl_line: "
3029                                                 "invalid interval \"%s\", unable to parse minutes", val );
3030                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3031                                         return -1;
3032                                 }
3033                                 ptr = next + 1;
3034                                 ss = strtoul( ptr, &next, 10 );
3035                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != '\0' || ss > 60 ) {
3036                                         snprintf( c->msg, sizeof( c->msg ),
3037                                                 "Error: parse_syncrepl_line: "
3038                                                 "invalid interval \"%s\", unable to parse seconds", val );
3039                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3040                                         return -1;
3041                                 }
3042                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
3043                         } else {
3044                                 unsigned long   t;
3045
3046                                 if ( lutil_parse_time( val, &t ) != 0 ) {
3047                                         snprintf( c->msg, sizeof( c->msg ),
3048                                                 "Error: parse_syncrepl_line: "
3049                                                 "invalid interval \"%s\"", val );
3050                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3051                                         return -1;
3052                                 }
3053                                 si->si_interval = (time_t)t;
3054                         }
3055                         if ( si->si_interval < 0 ) {
3056                                 snprintf( c->msg, sizeof( c->msg ),
3057                                         "Error: parse_syncrepl_line: "
3058                                         "invalid interval \"%ld\"",
3059                                         (long) si->si_interval);
3060                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3061                                 return -1;
3062                         }
3063                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
3064                                         STRLENOF( RETRYSTR "=" ) ) )
3065                 {
3066                         char **retry_list;
3067                         int j, k, n;
3068
3069                         val = c->argv[ i ] + STRLENOF( RETRYSTR "=" );
3070                         retry_list = (char **) ch_calloc( 1, sizeof( char * ));
3071                         retry_list[0] = NULL;
3072
3073                         slap_str2clist( &retry_list, val, " ,\t" );
3074
3075                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3076                         n = k / 2;
3077                         if ( k % 2 ) {
3078                                 snprintf( c->msg, sizeof( c->msg ),
3079                                         "Error: incomplete syncrepl retry list" );
3080                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3081                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3082                                         ch_free( retry_list[k] );
3083                                 }
3084                                 ch_free( retry_list );
3085                                 return 1;
3086                         }
3087                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ));
3088                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ));
3089                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ));
3090                         for ( j = 0; j < n; j++ ) {
3091                                 unsigned long   t;
3092                                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3093                                         snprintf( c->msg, sizeof( c->msg ),
3094                                                 "Error: invalid retry interval \"%s\" (#%d)",
3095                                                 retry_list[j*2], j );
3096                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3097                                         /* do some cleanup */
3098                                         return 1;
3099                                 }
3100                                 si->si_retryinterval[j] = (time_t)t;
3101                                 if ( *retry_list[j*2+1] == '+' ) {
3102                                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3103                                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3104                                         j++;
3105                                         break;
3106                                 } else {
3107                                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3108                                                         || si->si_retrynum_init[j] <= 0 )
3109                                         {
3110                                                 snprintf( c->msg, sizeof( c->msg ),
3111                                                         "Error: invalid initial retry number \"%s\" (#%d)",
3112                                                         retry_list[j*2+1], j );
3113                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3114                                                 /* do some cleanup */
3115                                                 return 1;
3116                                         }
3117                                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3118                                                         || si->si_retrynum[j] <= 0 )
3119                                         {
3120                                                 snprintf( c->msg, sizeof( c->msg ),
3121                                                         "Error: invalid retry number \"%s\" (#%d)",
3122                                                         retry_list[j*2+1], j );
3123                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3124                                                 /* do some cleanup */
3125                                                 return 1;
3126                                         }
3127                                 }
3128                         }
3129                         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3130                         si->si_retrynum[j] = RETRYNUM_TAIL;
3131                         si->si_retryinterval[j] = 0;
3132                         
3133                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3134                                 ch_free( retry_list[k] );
3135                         }
3136                         ch_free( retry_list );
3137                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
3138                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
3139                 {
3140                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
3141                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
3142                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
3143                         {
3144                                 snprintf( c->msg, sizeof( c->msg ),
3145                                         "invalid manageDSAit value \"%s\".\n",
3146                                         val );
3147                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3148                                 return 1;
3149                         }
3150                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
3151                                         STRLENOF( SLIMITSTR "=") ) )
3152                 {
3153                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
3154                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3155                                 si->si_slimit = 0;
3156
3157                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
3158                                 snprintf( c->msg, sizeof( c->msg ),
3159                                         "invalid size limit value \"%s\".\n",
3160                                         val );
3161                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3162                                 return 1;
3163                         }
3164                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
3165                                         STRLENOF( TLIMITSTR "=" ) ) )
3166                 {
3167                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
3168                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3169                                 si->si_tlimit = 0;
3170
3171                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
3172                                 snprintf( c->msg, sizeof( c->msg ),
3173                                         "invalid time limit value \"%s\".\n",
3174                                         val );
3175                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3176                                 return 1;
3177                         }
3178                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
3179                                         STRLENOF( SYNCDATASTR "=" ) ) )
3180                 {
3181                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
3182                         si->si_syncdata = verb_to_mask( val, datamodes );
3183                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
3184                         snprintf( c->msg, sizeof( c->msg ),
3185                                 "Error: parse_syncrepl_line: "
3186                                 "unable to parse \"%s\"\n", c->argv[ i ] );
3187                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3188                         return -1;
3189                 }
3190         }
3191
3192         if ( gots != GOT_ALL ) {
3193                 snprintf( c->msg, sizeof( c->msg ),
3194                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
3195                         gots & GOT_ID ? "" : " "IDSTR,
3196                         gots & GOT_PROVIDER ? "" : " "PROVIDERSTR,
3197                         gots & GOT_BASE ? "" : " "SEARCHBASESTR );
3198                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3199                 return -1;
3200         }
3201
3202         return 0;
3203 }
3204
3205 static int
3206 add_syncrepl(
3207         ConfigArgs *c )
3208 {
3209         syncinfo_t *si;
3210         int     rc = 0;
3211
3212         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
3213                 snprintf( c->msg, sizeof(c->msg), "database %s does not support "
3214                         "operations required for syncrepl", c->be->be_type );
3215                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3216                 return 1;
3217         }
3218         if ( BER_BVISEMPTY( &c->be->be_rootdn )) {
3219                 strcpy( c->msg, "rootDN must be defined before syncrepl may be used" );
3220                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3221                 return 1;
3222         }
3223         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
3224
3225         if ( si == NULL ) {
3226                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
3227                 return 1;
3228         }
3229
3230         si->si_bindconf.sb_tls = SB_TLS_OFF;
3231         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
3232         si->si_schemachecking = 0;
3233         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
3234                 &si->si_filterstr );
3235         si->si_base.bv_val = NULL;
3236         si->si_scope = LDAP_SCOPE_SUBTREE;
3237         si->si_attrsonly = 0;
3238         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3239         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3240         si->si_attrs = NULL;
3241         si->si_allattrs = 0;
3242         si->si_allopattrs = 0;
3243         si->si_exattrs = NULL;
3244         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3245         si->si_interval = 86400;
3246         si->si_retryinterval = NULL;
3247         si->si_retrynum_init = NULL;
3248         si->si_retrynum = NULL;
3249         si->si_manageDSAit = 0;
3250         si->si_tlimit = 0;
3251         si->si_slimit = 0;
3252         si->si_conn_setup = 0;
3253
3254         si->si_presentlist = NULL;
3255         LDAP_LIST_INIT( &si->si_nonpresentlist );
3256         ldap_pvt_thread_mutex_init( &si->si_mutex );
3257
3258         rc = parse_syncrepl_line( c, si );
3259
3260         if ( rc == 0 ) {
3261                 si->si_be = c->be;
3262                 init_syncrepl( si );
3263                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq, si->si_interval,
3264                         do_syncrepl, si, "do_syncrepl", c->be->be_suffix[0].bv_val );
3265                 if ( !si->si_re )
3266                         rc = -1;
3267         }
3268         if ( rc < 0 ) {
3269                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
3270                 syncinfo_free( si );    
3271                 return 1;
3272         } else {
3273                 Debug( LDAP_DEBUG_CONFIG,
3274                         "Config: ** successfully added syncrepl \"%s\"\n",
3275                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
3276                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
3277                 if ( !si->si_schemachecking ) {
3278                         SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3279                 }
3280                 c->be->be_syncinfo = si;
3281                 return 0;
3282         }
3283 }
3284
3285 static void
3286 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
3287 {
3288         struct berval bc, uri;
3289         char buf[BUFSIZ*2], *ptr;
3290         int i;
3291
3292         /* FIXME: we're not checking for buf[] overflow! */
3293
3294         /* temporarily inhibit bindconf from printing URI */
3295         uri = si->si_bindconf.sb_uri;
3296         BER_BVZERO( &si->si_bindconf.sb_uri );
3297         bindconf_unparse( &si->si_bindconf, &bc );
3298         si->si_bindconf.sb_uri = uri;
3299
3300         ptr = buf;
3301         ptr += snprintf( ptr, sizeof( buf ), IDSTR "=%03ld " PROVIDERSTR "=%s",
3302                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
3303         if ( !BER_BVISNULL( &bc )) {
3304                 ptr = lutil_strcopy( ptr, bc.bv_val );
3305                 free( bc.bv_val );
3306         }
3307         if ( !BER_BVISEMPTY( &si->si_filterstr )) {
3308                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
3309                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
3310                 *ptr++ = '"';
3311         }
3312         if ( !BER_BVISNULL( &si->si_base )) {
3313                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
3314                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
3315                 *ptr++ = '"';
3316         }
3317         if ( !BER_BVISEMPTY( &si->si_logfilterstr )) {
3318                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
3319                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
3320                 *ptr++ = '"';
3321         }
3322         if ( !BER_BVISNULL( &si->si_logbase )) {
3323                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
3324                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
3325                 *ptr++ = '"';
3326         }
3327         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
3328                 if ( si->si_scope == scopes[i].val ) {
3329                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
3330                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
3331                         break;
3332                 }
3333         }
3334         if ( si->si_attrsonly ) {
3335                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
3336         }
3337         if ( si->si_anfile ) {
3338                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:" );
3339                 ptr = lutil_strcopy( ptr, si->si_anfile );
3340         } else if ( si->si_allattrs || si->si_allopattrs ||
3341                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) )) {
3342                 char *old;
3343                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
3344                 old = ptr;
3345                 ptr = anlist_unparse( si->si_anlist, ptr );
3346                 if ( si->si_allattrs ) {
3347                         if ( old != ptr ) *ptr++ = ',';
3348                         *ptr++ = '*';
3349                 }
3350                 if ( si->si_allopattrs ) {
3351                         if ( old != ptr ) *ptr++ = ',';
3352                         *ptr++ = '+';
3353                 }
3354                 *ptr++ = '"';
3355         }
3356         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3357                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3358                 ptr = anlist_unparse( si->si_exanlist, ptr );
3359         }
3360         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3361         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3362         
3363         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3364         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3365                 "refreshAndPersist" : "refreshOnly" );
3366
3367         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
3368                 int dd, hh, mm, ss;
3369
3370                 dd = si->si_interval;
3371                 ss = dd % 60;
3372                 dd /= 60;
3373                 mm = dd % 60;
3374                 dd /= 60;
3375                 hh = dd % 24;
3376                 dd /= 24;
3377                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
3378                 ptr += sprintf( ptr, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
3379         } else if ( si->si_retryinterval ) {
3380                 int space=0;
3381                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
3382                 for (i=0; si->si_retryinterval[i]; i++) {
3383                         if ( space ) *ptr++ = ' ';
3384                         space = 1;
3385                         ptr += sprintf( ptr, "%ld ", (long) si->si_retryinterval[i] );
3386                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
3387                                 *ptr++ = '+';
3388                         else
3389                                 ptr += sprintf( ptr, "%d", si->si_retrynum_init[i] );
3390                 }
3391                 *ptr++ = '"';
3392         }
3393
3394         if ( si->si_slimit ) {
3395                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
3396                 ptr += sprintf( ptr, "%d", si->si_slimit );
3397         }
3398
3399         if ( si->si_tlimit ) {
3400                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
3401                 ptr += sprintf( ptr, "%d", si->si_tlimit );
3402         }
3403
3404         if ( si->si_syncdata ) {
3405                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
3406                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
3407                         ptr = lutil_strcopy( ptr, bc.bv_val );
3408                 }
3409         }
3410         bc.bv_len = ptr - buf;
3411         bc.bv_val = buf;
3412         ber_dupbv( bv, &bc );
3413 }
3414
3415 int
3416 syncrepl_config( ConfigArgs *c )
3417 {
3418         if (c->op == SLAP_CONFIG_EMIT) {
3419                 if ( c->be->be_syncinfo ) {
3420                         struct berval bv;
3421                         syncrepl_unparse( c->be->be_syncinfo, &bv ); 
3422                         ber_bvarray_add( &c->rvalue_vals, &bv );
3423                         return 0;
3424                 }
3425                 return 1;
3426         } else if ( c->op == LDAP_MOD_DELETE ) {
3427                 struct re_s *re;
3428
3429                 if ( c->be->be_syncinfo ) {
3430                         re = c->be->be_syncinfo->si_re;
3431                         if ( re ) {
3432                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
3433                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
3434                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
3435                         }
3436                         syncinfo_free( c->be->be_syncinfo );
3437                         c->be->be_syncinfo = NULL;
3438                 }
3439                 SLAP_DBFLAGS( c->be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
3440                 return 0;
3441         }
3442         if ( SLAP_SHADOW( c->be ) ) {
3443                 Debug(LDAP_DEBUG_ANY, "%s: "
3444                         "syncrepl: database already shadowed.\n",
3445                         c->log, 0, 0);
3446                 return(1);
3447         } else if ( add_syncrepl( c ) ) {
3448                 return(1);
3449         }
3450         return config_sync_shadow( c );
3451 }