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