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