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