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