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