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