]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
ITS#5376
[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-2008 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         ber_int_t                               si_msgid;
88         Avlnode                         *si_presentlist;
89         LDAP                            *si_ld;
90         LDAP_LIST_HEAD(np, nonpresent_entry) si_nonpresentlist;
91         ldap_pvt_thread_mutex_t si_mutex;
92 } syncinfo_t;
93
94 static int syncuuid_cmp( const void *, const void * );
95 static void avl_ber_bvfree( void * );
96 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray, struct berval * );
97 static int syncrepl_message_to_op(
98                                         syncinfo_t *, Operation *, LDAPMessage * );
99 static int syncrepl_message_to_entry(
100                                         syncinfo_t *, Operation *, LDAPMessage *,
101                                         Modifications **, Entry **, int );
102 static int syncrepl_entry(
103                                         syncinfo_t *, Operation*, Entry*,
104                                         Modifications**,int, struct berval*,
105                                         struct sync_cookie *,
106                                         struct berval * );
107 static void syncrepl_updateCookie(
108                                         syncinfo_t *, Operation *, struct berval *,
109                                         struct sync_cookie * );
110 static struct berval * slap_uuidstr_from_normalized(
111                                         struct berval *, struct berval *, void * );
112
113 /* callback functions */
114 static int dn_callback( struct slap_op *, struct slap_rep * );
115 static int nonpresent_callback( struct slap_op *, struct slap_rep * );
116 static int null_callback( struct slap_op *, struct slap_rep * );
117
118 static AttributeDescription *sync_descs[4];
119
120 static void
121 init_syncrepl(syncinfo_t *si)
122 {
123         int i, j, k, l, n;
124         char **attrs, **exattrs;
125
126         if ( !sync_descs[0] ) {
127                 sync_descs[0] = slap_schema.si_ad_objectClass;
128                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
129                 sync_descs[2] = slap_schema.si_ad_entryCSN;
130                 sync_descs[3] = NULL;
131         }
132
133         if ( si->si_allattrs && si->si_allopattrs )
134                 attrs = NULL;
135         else
136                 attrs = anlist2attrs( si->si_anlist );
137
138         if ( attrs ) {
139                 if ( si->si_allattrs ) {
140                         i = 0;
141                         while ( attrs[i] ) {
142                                 if ( !is_at_operational( at_find( attrs[i] ))) {
143                                         for ( j = i; attrs[j] != NULL; j++ ) {
144                                                 if ( j == i )
145                                                         ch_free( attrs[i] );
146                                                 attrs[j] = attrs[j+1];
147                                         }
148                                 } else {
149                                         i++;
150                                 }
151                         }
152                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
153                         attrs[i] = ch_strdup("*");
154                         attrs[i + 1] = NULL;
155
156                 } else if ( si->si_allopattrs ) {
157                         i = 0;
158                         while ( attrs[i] ) {
159                                 if ( is_at_operational( at_find( attrs[i] ))) {
160                                         for ( j = i; attrs[j] != NULL; j++ ) {
161                                                 if ( j == i )
162                                                         ch_free( attrs[i] );
163                                                 attrs[j] = attrs[j+1];
164                                         }
165                                 } else {
166                                         i++;
167                                 }
168                         }
169                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
170                         attrs[i] = ch_strdup("+");
171                         attrs[i + 1] = NULL;
172                 }
173
174                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
175                         j = 0;
176                         while ( attrs[j] ) {
177                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val )) {
178                                         for ( k = j; attrs[k] != NULL; k++ ) {
179                                                 if ( k == j )
180                                                         ch_free( attrs[k] );
181                                                 attrs[k] = attrs[k+1];
182                                         }
183                                 } else {
184                                         j++;
185                                 }
186                         }
187                 }
188
189                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
190
191                 if ( si->si_allopattrs ) {
192                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ));
193                 } else {
194                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ));
195                 }
196
197                 if ( attrs == NULL ) {
198                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0, 0, 0 );
199                 }
200
201                 /* Add Attributes */
202                 if ( si->si_allopattrs ) {
203                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
204                 } else {
205                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
206                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
207                         }
208                 }
209                 attrs[ n ] = NULL;
210
211         } else {
212
213                 i = 0;
214                 if ( si->si_allattrs == si->si_allopattrs ) {
215                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
216                         attrs[i++] = ch_strdup( "*" );
217                         attrs[i++] = ch_strdup( "+" );
218                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
219                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
220                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
221                         attrs[i++] = ch_strdup( "*" );
222                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
223                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
224                         }
225                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
226                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
227                         attrs[i++] = ch_strdup( "+" );
228                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
229                 }
230                 attrs[i] = NULL;
231         }
232         
233         si->si_attrs = attrs;
234
235         exattrs = anlist2attrs( si->si_exanlist );
236
237         if ( exattrs ) {
238                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
239
240                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
241                         j = 0;
242                         while ( exattrs[j] != NULL ) {
243                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val )) {
244                                         ch_free( exattrs[j] );
245                                         for ( k = j; exattrs[k] != NULL; k++ ) {
246                                                 exattrs[k] = exattrs[k+1];
247                                         }
248                                 } else {
249                                         j++;
250                                 }
251                         }
252                 }
253
254                 for ( i = 0; exattrs[i] != NULL; i++ ) {
255                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
256                                 ObjectClass     *oc;
257                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
258                                         k = 0;
259                                         while ( oc->soc_required[k] ) {
260                                                 if ( !strcmp( exattrs[i],
261                                                          oc->soc_required[k]->sat_cname.bv_val )) {
262                                                         ch_free( exattrs[i] );
263                                                         for ( l = i; exattrs[l]; l++ ) {
264                                                                 exattrs[l] = exattrs[l+1];
265                                                         }
266                                                 } else {
267                                                         k++;
268                                                 }
269                                         }
270                                 }
271                         }
272                 }
273
274                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
275
276                 if ( i != n )
277                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *));
278         }
279
280         si->si_exattrs = exattrs;       
281 }
282
283 typedef struct logschema {
284         struct berval ls_dn;
285         struct berval ls_req;
286         struct berval ls_mod;
287         struct berval ls_newRdn;
288         struct berval ls_delRdn;
289         struct berval ls_newSup;
290 } logschema;
291
292 static logschema changelog_sc = {
293         BER_BVC("targetDN"),
294         BER_BVC("changeType"),
295         BER_BVC("changes"),
296         BER_BVC("newRDN"),
297         BER_BVC("deleteOldRDN"),
298         BER_BVC("newSuperior")
299 };
300
301 static logschema accesslog_sc = {
302         BER_BVC("reqDN"),
303         BER_BVC("reqType"),
304         BER_BVC("reqMod"),
305         BER_BVC("reqNewRDN"),
306         BER_BVC("reqDeleteOldRDN"),
307         BER_BVC("reqNewSuperior")
308 };
309
310 static int
311 ldap_sync_search(
312         syncinfo_t *si,
313         void *ctx )
314 {
315         BerElementBuffer berbuf;
316         BerElement *ber = (BerElement *)&berbuf;
317         LDAPControl c[2], *ctrls[3];
318         struct timeval timeout;
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, &si->si_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         struct berval   *psub;
638         Modifications   *modlist = NULL;
639
640         const char              *text;
641         int                             match;
642
643         struct timeval *tout_p = NULL;
644         struct timeval tout = { 0, 0 };
645
646         int             refreshDeletes = 0;
647         BerVarray syncUUIDs = NULL;
648         ber_tag_t si_tag;
649
650         if ( slapd_shutdown ) {
651                 rc = -2;
652                 goto done;
653         }
654
655         ber_init2( ber, NULL, LBER_USE_DER );
656         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
657
658         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2 rid %03d\n", si->si_rid, 0, 0 );
659
660         psub = &si->si_be->be_nsuffix[0];
661
662         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
663
664         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
665                 tout_p = &tout;
666         } else {
667                 tout_p = NULL;
668         }
669
670         while (( rc = ldap_result( si->si_ld, si->si_msgid, LDAP_MSG_ONE,
671                 tout_p, &res )) > 0 )
672         {
673                 if ( slapd_shutdown ) {
674                         rc = -2;
675                         goto done;
676                 }
677                 for( msg = ldap_first_message( si->si_ld, res );
678                         msg != NULL;
679                         msg = ldap_next_message( si->si_ld, msg ) )
680                 {
681                         if ( slapd_shutdown ) {
682                                 rc = -2;
683                                 goto done;
684                         }
685                         switch( ldap_msgtype( msg ) ) {
686                         case LDAP_RES_SEARCH_ENTRY:
687                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
688                                 /* we can't work without the control */
689                                 if ( !rctrls ) {
690                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: rid %03d"
691                                                 "got search entry without "
692                                                 "control\n", si->si_rid, 0, 0 );
693                                         rc = -1;
694                                         goto done;
695                                 }
696                                 rctrlp = *rctrls;
697                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
698                                 ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
699                                 /* FIXME: what if syncUUID is NULL or empty?
700                                  * (happens with back-sql...) */
701                                 if ( BER_BVISEMPTY( &syncUUID ) ) {
702                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: rid %03d "
703                                                 "got empty syncUUID\n", si->si_rid, 0, 0 );
704                                         ldap_controls_free( rctrls );
705                                         rc = -1;
706                                         goto done;
707                                 }
708                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
709                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
710                                         if ( !BER_BVISNULL( &cookie ) ) {
711                                                 ch_free( syncCookie.octet_str.bv_val );
712                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
713                                         }
714                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
715                                         {
716                                                 slap_parse_sync_cookie( &syncCookie, NULL );
717                                         }
718                                 }
719                                 rc = 0;
720                                 if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
721                                         modlist = NULL;
722                                         if (( rc = syncrepl_message_to_op( si, op, msg )) == LDAP_SUCCESS &&
723                                                 !BER_BVISNULL( &syncCookie.ctxcsn ) ) {
724                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
725                                         } else if ( rc == LDAP_NO_SUCH_OBJECT ) {
726                                                 rc = LDAP_SYNC_REFRESH_REQUIRED;
727                                                 si->si_logstate = SYNCLOG_FALLBACK;
728                                                 ldap_abandon_ext( si->si_ld, si->si_msgid, NULL, NULL );
729                                         }
730                                 } else if (( rc = syncrepl_message_to_entry( si, op, msg,
731                                         &modlist, &entry, syncstate )) == LDAP_SUCCESS ) {
732                                         if (( rc = syncrepl_entry( si, op, entry, &modlist,
733                                                 syncstate, &syncUUID, &syncCookie_req,
734                                                 &syncCookie.ctxcsn )) == LDAP_SUCCESS &&
735                                                 !BER_BVISNULL( &syncCookie.ctxcsn ) ) {
736                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
737                                         }
738                                 }
739                                 ldap_controls_free( rctrls );
740                                 if ( modlist ) {
741                                         slap_mods_free( modlist, 1 );
742                                 }
743                                 if ( rc )
744                                         goto done;
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         e->e_name = op->o_req_dn;
1532         e->e_nname = op->o_req_ndn;
1533
1534         while ( ber_remaining( ber ) ) {
1535                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1536                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1537                 {
1538                         break;
1539                 }
1540
1541                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1542
1543                 mod->sml_op = LDAP_MOD_REPLACE;
1544                 mod->sml_flags = 0;
1545                 mod->sml_next = NULL;
1546                 mod->sml_desc = NULL;
1547                 mod->sml_type = tmp.sml_type;
1548                 mod->sml_values = tmp.sml_values;
1549                 mod->sml_nvalues = NULL;
1550
1551                 *modtail = mod;
1552                 modtail = &mod->sml_next;
1553         }
1554
1555         if ( *modlist == NULL ) {
1556                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: rid %03d no attributes\n",
1557                         si->si_rid, 0, 0 );
1558                 rc = -1;
1559                 goto done;
1560         }
1561
1562         rc = slap_mods_check( *modlist, &text, txtbuf, textlen, NULL );
1563
1564         if ( rc != LDAP_SUCCESS ) {
1565                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: rid %03d mods check (%s)\n",
1566                         si->si_rid, text, 0 );
1567                 goto done;
1568         }
1569
1570         /* Strip out dynamically generated attrs */
1571         for ( modtail = modlist; *modtail ; ) {
1572                 mod = *modtail;
1573                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1574                         *modtail = mod->sml_next;
1575                         slap_mod_free( &mod->sml_mod, 0 );
1576                         ch_free( mod );
1577                 } else {
1578                         modtail = &mod->sml_next;
1579                 }
1580         }
1581
1582         /* Strip out attrs in exattrs list */
1583         for ( modtail = modlist; *modtail ; ) {
1584                 mod = *modtail;
1585                 if ( ldap_charray_inlist( si->si_exattrs,
1586                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1587                         *modtail = mod->sml_next;
1588                         slap_mod_free( &mod->sml_mod, 0 );
1589                         ch_free( mod );
1590                 } else {
1591                         modtail = &mod->sml_next;
1592                 }
1593         }
1594         
1595         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1596         if( rc != LDAP_SUCCESS ) {
1597                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: rid %03d mods2entry (%s)\n",
1598                         si->si_rid, text, 0 );
1599         }
1600
1601 done:
1602         ber_free( ber, 0 );
1603         if ( rc != LDAP_SUCCESS ) {
1604                 if ( e ) {
1605                         entry_free( e );
1606                         e = NULL;
1607                 }
1608         }
1609         *entry = e;
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
1673         struct berval pdn = BER_BVNULL;
1674         dninfo dni = {0};
1675         int     retry = 1;
1676
1677         switch( syncstate ) {
1678         case LDAP_SYNC_PRESENT:
1679                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1680                                         si->si_rid,
1681                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1682                 break;
1683         case LDAP_SYNC_ADD:
1684                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1685                                         si->si_rid,
1686                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1687                 break;
1688         case LDAP_SYNC_DELETE:
1689                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1690                                         si->si_rid,
1691                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1692                 break;
1693         case LDAP_SYNC_MODIFY:
1694                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: rid %03d %s\n",
1695                                         si->si_rid,
1696                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1697                 break;
1698         default:
1699                 Debug( LDAP_DEBUG_ANY, "syncrepl_entry: rid %03d %s\n",
1700                                         si->si_rid,
1701                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1702         }
1703
1704         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1705                 if ( !si->si_refreshPresent && !si->si_refreshDone ) {
1706                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1707                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1708                                 syncuuid_cmp, avl_dup_error );
1709                 }
1710         }
1711
1712         if ( syncstate == LDAP_SYNC_PRESENT ) {
1713                 return 0;
1714         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1715                 if ( entry == NULL ) {
1716                         return 0;
1717                 }
1718         }
1719
1720         f.f_choice = LDAP_FILTER_EQUALITY;
1721         f.f_ava = &ava;
1722         ava.aa_desc = slap_schema.si_ad_entryUUID;
1723         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1724         ava.aa_value = *syncUUID;
1725         op->ors_filter = &f;
1726
1727         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
1728         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1729                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1730         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1731         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1732                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
1733         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1734         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1735
1736         op->o_tag = LDAP_REQ_SEARCH;
1737         op->ors_scope = LDAP_SCOPE_SUBTREE;
1738         op->ors_deref = LDAP_DEREF_NEVER;
1739
1740         /* get the entry for this UUID */
1741         op->o_req_dn = si->si_base;
1742         op->o_req_ndn = si->si_base;
1743
1744         op->o_time = slap_get_time();
1745         op->ors_tlimit = SLAP_NO_LIMIT;
1746         op->ors_slimit = 1;
1747
1748         op->ors_attrs = slap_anlist_all_attributes;
1749         op->ors_attrsonly = 0;
1750
1751         /* set callback function */
1752         op->o_callback = &cb;
1753         cb.sc_response = dn_callback;
1754         cb.sc_private = &dni;
1755         dni.new_entry = entry;
1756
1757         if ( limits_check( op, &rs_search ) == 0 ) {
1758                 rc = be->be_search( op, &rs_search );
1759                 Debug( LDAP_DEBUG_SYNC,
1760                                 "syncrepl_entry: rid %03d be_search (%d)\n", 
1761                                 si->si_rid, rc, 0 );
1762         }
1763
1764         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1765                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1766         }
1767
1768         cb.sc_response = null_callback;
1769         cb.sc_private = si;
1770
1771         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1772                 Debug( LDAP_DEBUG_SYNC,
1773                                 "syncrepl_entry: rid %03d %s\n",
1774                                 si->si_rid, entry->e_name.bv_val, 0 );
1775         } else {
1776                 Debug( LDAP_DEBUG_SYNC,
1777                                 "syncrepl_entry: rid %03d %s\n",
1778                                 si->si_rid, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
1779         }
1780
1781         if ( syncstate != LDAP_SYNC_DELETE ) {
1782                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1783
1784                 if ( a == NULL ) {
1785                         /* add if missing */
1786                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1787                                 &syncUUID_strrep, syncUUID );
1788
1789                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1790                         /* replace only if necessary */
1791                         if ( a->a_nvals != a->a_vals ) {
1792                                 ber_memfree( a->a_nvals[0].bv_val );
1793                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1794                         }
1795                         ber_memfree( a->a_vals[0].bv_val );
1796                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1797                 }
1798                 /* Don't save the contextCSN on the inooming context entry,
1799                  * we'll write it when syncrepl_updateCookie eventually
1800                  * gets called. (ITS#4622)
1801                  */
1802                 if ( syncstate == LDAP_SYNC_ADD && dn_match( &entry->e_nname,
1803                         &be->be_nsuffix[0] )) {
1804                         Attribute **ap;
1805                         for ( ap = &entry->e_attrs; *ap; ap=&(*ap)->a_next ) {
1806                                 a = *ap;
1807                                 if ( a->a_desc == slap_schema.si_ad_contextCSN ) {
1808                                         *ap = a->a_next;
1809                                         attr_free( a );
1810                                         break;
1811                                 }
1812                         }
1813                 }
1814         }
1815
1816         slap_op_time( &op->o_time, &op->o_tincr );
1817         switch ( syncstate ) {
1818         case LDAP_SYNC_ADD:
1819         case LDAP_SYNC_MODIFY:
1820                 {
1821                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
1822                         if ( a )
1823                                 op->o_csn = a->a_vals[0];
1824                 }
1825 retry_add:;
1826                 if ( BER_BVISNULL( &dni.dn )) {
1827
1828                         op->o_req_dn = entry->e_name;
1829                         op->o_req_ndn = entry->e_nname;
1830                         op->o_tag = LDAP_REQ_ADD;
1831                         op->ora_e = entry;
1832
1833                         rc = be->be_add( op, &rs_add );
1834                         Debug( LDAP_DEBUG_SYNC,
1835                                         "syncrepl_entry: rid %03d be_add (%d)\n", 
1836                                         si->si_rid, rc, 0 );
1837                         switch ( rs_add.sr_err ) {
1838                         case LDAP_SUCCESS:
1839                                 be_entry_release_w( op, entry );
1840                                 entry = NULL;
1841                                 break;
1842
1843                         case LDAP_REFERRAL:
1844                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1845                          * only if the suffix entry is not present */
1846                         case LDAP_NO_SUCH_OBJECT:
1847                                 rc = syncrepl_add_glue( op, entry );
1848                                 entry = NULL;
1849                                 break;
1850
1851                         /* if an entry was added via syncrepl_add_glue(),
1852                          * it likely has no entryUUID, so the previous
1853                          * be_search() doesn't find it.  In this case,
1854                          * give syncrepl a chance to modify it. Also
1855                          * allow for entries that were recreated with the
1856                          * same DN but a different entryUUID.
1857                          */
1858                         case LDAP_ALREADY_EXISTS:
1859                                 if ( retry ) {
1860                                         Operation       op2 = *op;
1861                                         SlapReply       rs2 = { 0 };
1862                                         slap_callback   cb2 = { 0 };
1863
1864                                         op2.o_tag = LDAP_REQ_SEARCH;
1865                                         op2.o_req_dn = entry->e_name;
1866                                         op2.o_req_ndn = entry->e_nname;
1867                                         op2.ors_scope = LDAP_SCOPE_BASE;
1868                                         op2.ors_deref = LDAP_DEREF_NEVER;
1869                                         op2.ors_attrs = slap_anlist_all_attributes;
1870                                         op2.ors_attrsonly = 0;
1871                                         op2.ors_limit = NULL;
1872                                         op2.ors_slimit = 1;
1873                                         op2.ors_tlimit = SLAP_NO_LIMIT;
1874
1875                                         f.f_choice = LDAP_FILTER_PRESENT;
1876                                         f.f_desc = slap_schema.si_ad_objectClass;
1877                                         op2.ors_filter = &f;
1878                                         op2.ors_filterstr = generic_filterstr;
1879
1880                                         op2.o_callback = &cb2;
1881                                         cb2.sc_response = dn_callback;
1882                                         cb2.sc_private = &dni;
1883
1884                                         rc = be->be_search( &op2, &rs2 );
1885                                         if ( rc ) goto done;
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                                 break;
1898                         }
1899                         goto done;
1900                 }
1901                 /* FALLTHRU */
1902                 op->o_req_dn = dni.dn;
1903                 op->o_req_ndn = dni.ndn;
1904                 if ( dni.renamed ) {
1905                         struct berval noldp, newp, nnewp;
1906
1907                         op->o_tag = LDAP_REQ_MODRDN;
1908                         dnRdn( &entry->e_name, &op->orr_newrdn );
1909                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
1910
1911                         dnParent( &dni.ndn, &noldp );
1912                         dnParent( &entry->e_nname, &nnewp );
1913                         if ( !dn_match( &noldp, &nnewp )) {
1914                                 dnParent( &entry->e_name, &newp );
1915                                 op->orr_newSup = &newp;
1916                                 op->orr_nnewSup = &nnewp;
1917                         } else {
1918                                 op->orr_newSup = NULL;
1919                                 op->orr_nnewSup = NULL;
1920                         }
1921                         op->orr_deleteoldrdn = 0;
1922                         rc = be->be_modrdn( op, &rs_modify );
1923                         Debug( LDAP_DEBUG_SYNC,
1924                                         "syncrepl_entry: rid %03d be_modrdn (%d)\n", 
1925                                         si->si_rid, rc, 0 );
1926                         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
1927                                 op->o_req_dn = entry->e_name;
1928                                 op->o_req_ndn = entry->e_nname;
1929                         } else {
1930                                 goto done;
1931                         }
1932                         if ( dni.wasChanged )
1933                                 slap_op_time( &op->o_time, &op->o_tincr );
1934                 }
1935                 if ( dni.wasChanged ) {
1936                         Modifications *mod, *modhead = NULL;
1937                         Modifications *modtail = NULL;
1938                         int i;
1939
1940                         op->o_tag = LDAP_REQ_MODIFY;
1941
1942                         assert( *modlist != NULL );
1943
1944                         /* Delete all the old attrs */
1945                         for ( i = 0; i < dni.attrs; i++ ) {
1946                                 mod = ch_malloc( sizeof( Modifications ) );
1947                                 mod->sml_op = LDAP_MOD_DELETE;
1948                                 mod->sml_flags = 0;
1949                                 mod->sml_desc = dni.ads[i];
1950                                 mod->sml_type = mod->sml_desc->ad_cname;
1951                                 mod->sml_values = NULL;
1952                                 mod->sml_nvalues = NULL;
1953                                 if ( !modhead ) modhead = mod;
1954                                 if ( modtail ) {
1955                                         modtail->sml_next = mod;
1956                                 }
1957                                 modtail = mod;
1958                         }
1959
1960                         /* Append passed in list to ours */
1961                         if ( modtail ) {
1962                                 modtail->sml_next = *modlist;
1963                                 *modlist = modhead;
1964                         } else {
1965                                 mod = *modlist;
1966                         }
1967
1968                         /* Find end of this list */
1969                         for ( ; mod != NULL; mod = mod->sml_next ) {
1970                                 modtail = mod;
1971                         }
1972
1973                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1974                         mod->sml_op = LDAP_MOD_REPLACE;
1975                         mod->sml_flags = 0;
1976                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1977                         mod->sml_type = mod->sml_desc->ad_cname;
1978                         ber_dupbv( &uuid_bv, &syncUUID_strrep );
1979                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1980                         ber_dupbv( &uuid_bv, syncUUID );
1981                         ber_bvarray_add( &mod->sml_nvalues, &uuid_bv );
1982                         modtail->sml_next = mod;
1983                                         
1984                         op->o_tag = LDAP_REQ_MODIFY;
1985                         op->orm_modlist = *modlist;
1986
1987                         rc = be->be_modify( op, &rs_modify );
1988                         Debug( LDAP_DEBUG_SYNC,
1989                                         "syncrepl_entry: rid %03d be_modify (%d)\n", 
1990                                         si->si_rid, rc, 0 );
1991                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1992                                 Debug( LDAP_DEBUG_ANY,
1993                                         "syncrepl_entry: rid %03d be_modify failed (%d)\n",
1994                                         si->si_rid, rs_modify.sr_err, 0 );
1995                         }
1996                 }
1997                 goto done;
1998         case LDAP_SYNC_DELETE :
1999                 if ( !BER_BVISNULL( &dni.dn )) {
2000                         op->o_req_dn = dni.dn;
2001                         op->o_req_ndn = dni.ndn;
2002                         op->o_tag = LDAP_REQ_DELETE;
2003                         rc = be->be_delete( op, &rs_delete );
2004                         Debug( LDAP_DEBUG_SYNC,
2005                                         "syncrepl_entry: rid %03d be_delete (%d)\n", 
2006                                         si->si_rid, rc, 0 );
2007
2008                         while ( rs_delete.sr_err == LDAP_SUCCESS
2009                                 && op->o_delete_glue_parent ) {
2010                                 op->o_delete_glue_parent = 0;
2011                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
2012                                         slap_callback cb = { NULL };
2013                                         cb.sc_response = slap_null_cb;
2014                                         dnParent( &op->o_req_ndn, &pdn );
2015                                         op->o_req_dn = pdn;
2016                                         op->o_req_ndn = pdn;
2017                                         op->o_callback = &cb;
2018                                         op->o_bd->be_delete( op, &rs_delete );
2019                                 } else {
2020                                         break;
2021                                 }
2022                         }
2023                 }
2024                 goto done;
2025
2026         default :
2027                 Debug( LDAP_DEBUG_ANY,
2028                         "syncrepl_entry: rid %03d unknown syncstate\n", si->si_rid, 0, 0 );
2029                 goto done;
2030         }
2031
2032 done :
2033         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2034                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2035                 BER_BVZERO( &syncUUID_strrep );
2036         }
2037         if ( dni.ads ) {
2038                 op->o_tmpfree( dni.ads, op->o_tmpmemctx );
2039         }
2040         if ( !BER_BVISNULL( &dni.ndn ) ) {
2041                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2042         }
2043         if ( !BER_BVISNULL( &dni.dn ) ) {
2044                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2045         }
2046         if ( entry )
2047                 entry_free( entry );
2048         BER_BVZERO( &op->o_csn );
2049         return rc;
2050 }
2051
2052 static struct berval gcbva[] = {
2053         BER_BVC("top"),
2054         BER_BVC("glue"),
2055         BER_BVNULL
2056 };
2057
2058 #define NP_DELETE_ONE   2
2059
2060 static void
2061 syncrepl_del_nonpresent(
2062         Operation *op,
2063         syncinfo_t *si,
2064         BerVarray uuids,
2065         struct berval *cookiecsn )
2066 {
2067         Backend* be = op->o_bd;
2068         slap_callback   cb = { NULL };
2069         SlapReply       rs_search = {REP_RESULT};
2070         SlapReply       rs_delete = {REP_RESULT};
2071         SlapReply       rs_modify = {REP_RESULT};
2072         struct nonpresent_entry *np_list, *np_prev;
2073         int rc;
2074         AttributeName   an[2];
2075
2076         struct berval pdn = BER_BVNULL;
2077         struct berval csn;
2078
2079         op->o_req_dn = si->si_base;
2080         op->o_req_ndn = si->si_base;
2081
2082         cb.sc_response = nonpresent_callback;
2083         cb.sc_private = si;
2084
2085         op->o_callback = &cb;
2086         op->o_tag = LDAP_REQ_SEARCH;
2087         op->ors_scope = si->si_scope;
2088         op->ors_deref = LDAP_DEREF_NEVER;
2089         op->o_time = slap_get_time();
2090         op->ors_tlimit = SLAP_NO_LIMIT;
2091
2092
2093         if ( uuids ) {
2094                 Filter uf;
2095 #ifdef LDAP_COMP_MATCH
2096                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
2097 #else
2098                 AttributeAssertion eq = { NULL, BER_BVNULL };
2099 #endif
2100                 int i;
2101
2102                 op->ors_attrsonly = 1;
2103                 op->ors_attrs = slap_anlist_no_attrs;
2104                 op->ors_limit = NULL;
2105                 op->ors_filter = &uf;
2106
2107                 uf.f_ava = &eq;
2108                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2109                 uf.f_next = NULL;
2110                 uf.f_choice = LDAP_FILTER_EQUALITY;
2111                 si->si_refreshDelete |= NP_DELETE_ONE;
2112
2113                 for (i=0; uuids[i].bv_val; i++) {
2114                         op->ors_slimit = 1;
2115                         uf.f_av_value = uuids[i];
2116                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2117                         rc = be->be_search( op, &rs_search );
2118                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2119                 }
2120                 si->si_refreshDelete ^= NP_DELETE_ONE;
2121         } else {
2122                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2123                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2124                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2125                 op->ors_attrs = an;
2126                 op->ors_slimit = SLAP_NO_LIMIT;
2127                 op->ors_attrsonly = 0;
2128                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2129                 op->ors_filterstr = si->si_filterstr;
2130                 op->o_nocaching = 1;
2131
2132                 if ( limits_check( op, &rs_search ) == 0 ) {
2133                         rc = be->be_search( op, &rs_search );
2134                 }
2135                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
2136         }
2137
2138         op->o_nocaching = 0;
2139
2140         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2141
2142                 if ( cookiecsn && !BER_BVISNULL( cookiecsn ))
2143                         csn = *cookiecsn;
2144                 else
2145                         csn = si->si_syncCookie.ctxcsn;
2146
2147                 slap_queue_csn( op, &csn );
2148
2149                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2150                 while ( np_list != NULL ) {
2151                         LDAP_LIST_REMOVE( np_list, npe_link );
2152                         np_prev = np_list;
2153                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2154                         op->o_tag = LDAP_REQ_DELETE;
2155                         op->o_callback = &cb;
2156                         cb.sc_response = null_callback;
2157                         cb.sc_private = si;
2158                         op->o_req_dn = *np_prev->npe_name;
2159                         op->o_req_ndn = *np_prev->npe_nname;
2160                         rc = op->o_bd->be_delete( op, &rs_delete );
2161                         Debug( LDAP_DEBUG_SYNC,
2162                                 "syncrepl_del_nonpresent: rid %03d be_delete %s (%d)\n", 
2163                                 si->si_rid, op->o_req_dn.bv_val, rc );
2164
2165                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2166                                 Modifications mod1, mod2;
2167                                 mod1.sml_op = LDAP_MOD_REPLACE;
2168                                 mod1.sml_flags = 0;
2169                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2170                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2171                                 mod1.sml_values = &gcbva[0];
2172                                 mod1.sml_nvalues = NULL;
2173                                 mod1.sml_next = &mod2;
2174
2175                                 mod2.sml_op = LDAP_MOD_REPLACE;
2176                                 mod2.sml_flags = 0;
2177                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2178                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2179                                 mod2.sml_values = &gcbva[1];
2180                                 mod2.sml_nvalues = NULL;
2181                                 mod2.sml_next = NULL;
2182
2183                                 op->o_tag = LDAP_REQ_MODIFY;
2184                                 op->orm_modlist = &mod1;
2185
2186                                 rc = be->be_modify( op, &rs_modify );
2187                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2188                         }
2189
2190                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2191                                         op->o_delete_glue_parent ) {
2192                                 op->o_delete_glue_parent = 0;
2193                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
2194                                         slap_callback cb = { NULL };
2195                                         cb.sc_response = slap_null_cb;
2196                                         dnParent( &op->o_req_ndn, &pdn );
2197                                         op->o_req_dn = pdn;
2198                                         op->o_req_ndn = pdn;
2199                                         op->o_callback = &cb;
2200                                         /* give it a root privil ? */
2201                                         op->o_bd->be_delete( op, &rs_delete );
2202                                 } else {
2203                                         break;
2204                             }
2205                         }
2206
2207                         op->o_delete_glue_parent = 0;
2208
2209                         ber_bvfree( np_prev->npe_name );
2210                         ber_bvfree( np_prev->npe_nname );
2211                         ch_free( np_prev );
2212                 }
2213
2214                 slap_graduate_commit_csn( op );
2215                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2216                 BER_BVZERO( &op->o_csn );
2217         }
2218
2219         return;
2220 }
2221
2222 int
2223 syncrepl_add_glue(
2224         Operation* op,
2225         Entry *e )
2226 {
2227         Backend *be = op->o_bd;
2228         slap_callback cb = { NULL };
2229         Attribute       *a;
2230         int     rc;
2231         int suffrdns;
2232         int i;
2233         struct berval dn = BER_BVNULL;
2234         struct berval ndn = BER_BVNULL;
2235         Entry   *glue;
2236         SlapReply       rs_add = {REP_RESULT};
2237         struct berval   ptr, nptr;
2238         char            *comma;
2239
2240         op->o_tag = LDAP_REQ_ADD;
2241         op->o_callback = &cb;
2242         cb.sc_response = null_callback;
2243         cb.sc_private = NULL;
2244
2245         dn = e->e_name;
2246         ndn = e->e_nname;
2247
2248         /* count RDNs in suffix */
2249         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2250                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2251                         comma++;
2252                         ptr.bv_len -= comma - ptr.bv_val;
2253                         ptr.bv_val = comma;
2254                         i++;
2255                 }
2256                 suffrdns = i;
2257         } else {
2258                 /* suffix is "" */
2259                 suffrdns = 0;
2260         }
2261
2262         /* Start with BE suffix */
2263         ptr = dn;
2264         for ( i = 0; i < suffrdns; i++ ) {
2265                 comma = ber_bvrchr( &ptr, ',' );
2266                 if ( comma != NULL ) {
2267                         ptr.bv_len = comma - ptr.bv_val;
2268                 } else {
2269                         ptr.bv_len = 0;
2270                         break;
2271                 }
2272         }
2273         
2274         if ( !BER_BVISEMPTY( &ptr ) ) {
2275                 dn.bv_len -= ptr.bv_len + 1;
2276                 dn.bv_val += ptr.bv_len + 1;
2277         }
2278
2279         /* the normalizedDNs are always the same length, no counting
2280          * required.
2281          */
2282         nptr = ndn;
2283         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2284                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2285                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2286
2287                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2288
2289         } else {
2290                 nptr.bv_len = 0;
2291         }
2292
2293         while ( ndn.bv_val > e->e_nname.bv_val ) {
2294                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
2295                 ber_dupbv( &glue->e_name, &dn );
2296                 ber_dupbv( &glue->e_nname, &ndn );
2297
2298                 a = ch_calloc( 1, sizeof( Attribute ));
2299                 a->a_desc = slap_schema.si_ad_objectClass;
2300
2301                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
2302                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2303                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2304                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2305
2306                 a->a_nvals = a->a_vals;
2307
2308                 a->a_next = glue->e_attrs;
2309                 glue->e_attrs = a;
2310
2311                 a = ch_calloc( 1, sizeof( Attribute ));
2312                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
2313
2314                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
2315                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2316                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2317
2318                 a->a_nvals = a->a_vals;
2319
2320                 a->a_next = glue->e_attrs;
2321                 glue->e_attrs = a;
2322
2323                 op->o_req_dn = glue->e_name;
2324                 op->o_req_ndn = glue->e_nname;
2325                 op->ora_e = glue;
2326                 rc = be->be_add ( op, &rs_add );
2327                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2328                         be_entry_release_w( op, glue );
2329                 } else {
2330                 /* incl. ALREADY EXIST */
2331                         entry_free( glue );
2332                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
2333                                 entry_free( e );
2334                                 return rc;
2335                         }
2336                 }
2337
2338                 /* Move to next child */
2339                 comma = ber_bvrchr( &ptr, ',' );
2340                 if ( comma == NULL ) {
2341                         break;
2342                 }
2343                 ptr.bv_len = comma - ptr.bv_val;
2344                 
2345                 dn.bv_val = ++comma;
2346                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2347
2348                 comma = ber_bvrchr( &nptr, ',' );
2349                 assert( comma != NULL );
2350                 nptr.bv_len = comma - nptr.bv_val;
2351
2352                 ndn.bv_val = ++comma;
2353                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2354         }
2355
2356         op->o_req_dn = e->e_name;
2357         op->o_req_ndn = e->e_nname;
2358         op->ora_e = e;
2359         rc = be->be_add ( op, &rs_add );
2360         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2361                 be_entry_release_w( op, e );
2362         } else {
2363                 entry_free( e );
2364         }
2365
2366         return rc;
2367 }
2368
2369 static void
2370 syncrepl_updateCookie(
2371         syncinfo_t *si,
2372         Operation *op,
2373         struct berval *pdn,
2374         struct sync_cookie *syncCookie )
2375 {
2376         Backend *be = op->o_bd;
2377         Modifications mod = { { 0 } };
2378         struct berval vals[ 2 ];
2379
2380         int rc, dbflags;
2381
2382         slap_callback cb = { NULL };
2383         SlapReply       rs_modify = {REP_RESULT};
2384
2385         slap_sync_cookie_free( &si->si_syncCookie, 0 );
2386         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2387
2388         mod.sml_op = LDAP_MOD_REPLACE;
2389         mod.sml_desc = slap_schema.si_ad_contextCSN;
2390         mod.sml_type = mod.sml_desc->ad_cname;
2391         mod.sml_values = vals;
2392         vals[0] = si->si_syncCookie.ctxcsn;
2393         vals[1].bv_val = NULL;
2394         vals[1].bv_len = 0;
2395
2396         slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
2397
2398         op->o_tag = LDAP_REQ_MODIFY;
2399
2400         assert( si->si_rid < 1000 );
2401
2402         cb.sc_response = null_callback;
2403         cb.sc_private = si;
2404
2405         op->o_callback = &cb;
2406         op->o_req_dn = op->o_bd->be_suffix[0];
2407         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2408
2409         /* update contextCSN */
2410         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2411         op->orm_modlist = &mod;
2412         dbflags = SLAP_DBFLAGS(op->o_bd);
2413         SLAP_DBFLAGS(op->o_bd) |= SLAP_DBFLAG_NOLASTMOD;
2414         rc = be->be_modify( op, &rs_modify );
2415         SLAP_DBFLAGS(op->o_bd) = dbflags;
2416         op->o_msgid = 0;
2417
2418         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2419                 Debug( LDAP_DEBUG_ANY,
2420                         "syncrepl_updateCookie: rid %03d be_modify failed (%d)\n",
2421                         si->si_rid, rs_modify.sr_err, 0 );
2422         }
2423
2424         slap_graduate_commit_csn( op );
2425         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2426         BER_BVZERO( &op->o_csn );
2427         if ( mod.sml_next ) slap_mods_free( mod.sml_next, 1 );
2428
2429         return;
2430 }
2431
2432 static int
2433 dn_callback(
2434         Operation*      op,
2435         SlapReply*      rs )
2436 {
2437         dninfo *dni = op->o_callback->sc_private;
2438
2439         if ( rs->sr_type == REP_SEARCH ) {
2440                 if ( !BER_BVISNULL( &dni->dn ) ) {
2441                         Debug( LDAP_DEBUG_ANY,
2442                                 "dn_callback: consistency error - "
2443                                 "entryUUID is not unique\n", 0, 0, 0 );
2444                 } else {
2445                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2446                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2447                         /* If there is a new entry, see if it differs from the old.
2448                          * We compare the non-normalized values so that cosmetic changes
2449                          * in the provider are always propagated.
2450                          */
2451                         if ( dni->new_entry ) {
2452                                 Attribute *old, *new;
2453                                 int i;
2454
2455                                 /* Did the DN change? Note that we don't explicitly try to
2456                                  * discover if the deleteOldRdn argument applies here. It
2457                                  * would save an unnecessary Modify if we detected it, but
2458                                  * that's a fair amount of trouble to compare the two attr
2459                                  * lists in detail. (Just test normalized DN; we ignore
2460                                  * insignificant changes here.)
2461                                  */
2462                                 if ( !dn_match( &rs->sr_entry->e_nname,
2463                                                 &dni->new_entry->e_nname ) )
2464                                 {
2465                                         dni->renamed = 1;
2466                                 }
2467
2468                                 for ( i = 0, old = rs->sr_entry->e_attrs;
2469                                                 old;
2470                                                 i++, old = old->a_next )
2471                                         ;
2472
2473                                 dni->attrs = i;
2474
2475                                 /* We assume that attributes are saved in the same order
2476                                  * in the remote and local databases. So if we walk through
2477                                  * the attributeDescriptions one by one they should match in
2478                                  * lock step. If not, we signal a change. Otherwise we test
2479                                  * all the values...
2480                                  */
2481                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2482                                                 old && new;
2483                                                 old = old->a_next, new = new->a_next )
2484                                 {
2485                                         if ( old->a_desc != new->a_desc ) {
2486                                                 dni->wasChanged = 1;
2487                                                 break;
2488                                         }
2489                                         for ( i = 0; ; i++ ) {
2490                                                 int nold, nnew;
2491                                                 nold = BER_BVISNULL( &old->a_vals[i] );
2492                                                 nnew = BER_BVISNULL( &new->a_vals[i] );
2493                                                 /* If both are empty, stop looking */
2494                                                 if ( nold && nnew ) {
2495                                                         break;
2496                                                 }
2497                                                 /* If they are different, stop looking */
2498                                                 if ( nold != nnew ) {
2499                                                         dni->wasChanged = 1;
2500                                                         break;
2501                                                 }
2502                                                 if ( ber_bvcmp( &old->a_vals[i], &new->a_vals[i] )) {
2503                                                         dni->wasChanged = 1;
2504                                                         break;
2505                                                 }
2506                                         }
2507                                         if ( dni->wasChanged ) break;
2508                                 }
2509                                 if ( dni->wasChanged ) {
2510                                         dni->ads = op->o_tmpalloc( dni->attrs *
2511                                                 sizeof(AttributeDescription *), op->o_tmpmemctx );
2512                                         i = 0;
2513                                         for ( old = rs->sr_entry->e_attrs; old; old = old->a_next ) {
2514                                                 dni->ads[i] = old->a_desc;
2515                                                 i++;
2516                                         }
2517                                 }
2518                         }
2519                 }
2520         } else if ( rs->sr_type == REP_RESULT ) {
2521                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2522                         Debug( LDAP_DEBUG_ANY,
2523                                 "dn_callback: consistency error - "
2524                                 "entryUUID is not unique\n", 0, 0, 0 );
2525                 }
2526         }
2527
2528         return LDAP_SUCCESS;
2529 }
2530
2531 static int
2532 nonpresent_callback(
2533         Operation*      op,
2534         SlapReply*      rs )
2535 {
2536         syncinfo_t *si = op->o_callback->sc_private;
2537         Attribute *a;
2538         int count = 0;
2539         struct berval* present_uuid = NULL;
2540         struct nonpresent_entry *np_entry;
2541
2542         if ( rs->sr_type == REP_RESULT ) {
2543                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2544                 si->si_presentlist = NULL;
2545
2546         } else if ( rs->sr_type == REP_SEARCH ) {
2547                 if ( !(si->si_refreshDelete & NP_DELETE_ONE )) {
2548                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2549
2550                         if ( a == NULL ) return 0;
2551
2552                         present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2553                                 syncuuid_cmp );
2554                 }
2555
2556                 if ( present_uuid == NULL ) {
2557                         np_entry = (struct nonpresent_entry *)
2558                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2559                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2560                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2561                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2562
2563                 } else {
2564                         avl_delete( &si->si_presentlist,
2565                                         &a->a_nvals[0], syncuuid_cmp );
2566                         ch_free( present_uuid->bv_val );
2567                         ch_free( present_uuid );
2568                 }
2569         }
2570         return LDAP_SUCCESS;
2571 }
2572
2573 static int
2574 null_callback(
2575         Operation*      op,
2576         SlapReply*      rs )
2577 {
2578         if ( rs->sr_err != LDAP_SUCCESS &&
2579                 rs->sr_err != LDAP_REFERRAL &&
2580                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2581                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2582                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2583         {
2584                 Debug( LDAP_DEBUG_ANY,
2585                         "null_callback: error code 0x%x\n",
2586                         rs->sr_err, 0, 0 );
2587         }
2588         return LDAP_SUCCESS;
2589 }
2590
2591 static struct berval *
2592 slap_uuidstr_from_normalized(
2593         struct berval* uuidstr,
2594         struct berval* normalized,
2595         void *ctx )
2596 {
2597         struct berval *new;
2598         unsigned char nibble;
2599         int i, d = 0;
2600
2601         if ( normalized == NULL ) return NULL;
2602         if ( normalized->bv_len != 16 ) return NULL;
2603
2604         if ( uuidstr ) {
2605                 new = uuidstr;
2606         } else {
2607                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2608                 if ( new == NULL ) {
2609                         return NULL;
2610                 }
2611         }
2612
2613         new->bv_len = 36;
2614
2615         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2616                 if ( new != uuidstr ) {
2617                         slap_sl_free( new, ctx );
2618                 }
2619                 return NULL;
2620         }
2621
2622         for ( i = 0; i < 16; i++ ) {
2623                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2624                         new->bv_val[(i<<1)+d] = '-';
2625                         d += 1;
2626                 }
2627
2628                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2629                 if ( nibble < 10 ) {
2630                         new->bv_val[(i<<1)+d] = nibble + '0';
2631                 } else {
2632                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2633                 }
2634
2635                 nibble = (normalized->bv_val[i]) & 0xF;
2636                 if ( nibble < 10 ) {
2637                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2638                 } else {
2639                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2640                 }
2641         }
2642
2643         new->bv_val[new->bv_len] = '\0';
2644         return new;
2645 }
2646
2647 static int
2648 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2649 {
2650         const struct berval *uuid1 = v_uuid1;
2651         const struct berval *uuid2 = v_uuid2;
2652         int rc = uuid1->bv_len - uuid2->bv_len;
2653         if ( rc ) return rc;
2654         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2655 }
2656
2657 static void
2658 avl_ber_bvfree( void *v_bv )
2659 {
2660         struct berval   *bv = (struct berval *)v_bv;
2661         
2662         if( v_bv == NULL ) return;
2663         if ( !BER_BVISNULL( bv ) ) {
2664                 ch_free( bv->bv_val );
2665         }
2666         ch_free( (char *) bv );
2667 }
2668
2669 void
2670 syncinfo_free( syncinfo_t *sie )
2671 {
2672         if ( sie->si_ld ) {
2673                 if ( sie->si_conn_setup ) {
2674                         ber_socket_t s;
2675                         ldap_get_option( sie->si_ld, LDAP_OPT_DESC, &s );
2676                         connection_client_stop( s );
2677                         sie->si_conn_setup = 0;
2678                 }
2679                 ldap_unbind_ext( sie->si_ld, NULL, NULL );
2680         }
2681
2682         ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
2683
2684         bindconf_free( &sie->si_bindconf );
2685
2686         if ( sie->si_filterstr.bv_val ) {
2687                 ch_free( sie->si_filterstr.bv_val );
2688         }
2689         if ( sie->si_base.bv_val ) {
2690                 ch_free( sie->si_base.bv_val );
2691         }
2692         if ( sie->si_attrs ) {
2693                 int i = 0;
2694                 while ( sie->si_attrs[i] != NULL ) {
2695                         ch_free( sie->si_attrs[i] );
2696                         i++;
2697                 }
2698                 ch_free( sie->si_attrs );
2699         }
2700         if ( sie->si_exattrs ) {
2701                 int i = 0;
2702                 while ( sie->si_exattrs[i] != NULL ) {
2703                         ch_free( sie->si_exattrs[i] );
2704                         i++;
2705                 }
2706                 ch_free( sie->si_exattrs );
2707         }
2708         if ( sie->si_anlist ) {
2709                 int i = 0;
2710                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2711                         ch_free( sie->si_anlist[i].an_name.bv_val );
2712                         i++;
2713                 }
2714                 ch_free( sie->si_anlist );
2715         }
2716         if ( sie->si_exanlist ) {
2717                 int i = 0;
2718                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2719                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2720                         i++;
2721                 }
2722                 ch_free( sie->si_exanlist );
2723         }
2724         if ( sie->si_retryinterval ) {
2725                 ch_free( sie->si_retryinterval );
2726         }
2727         if ( sie->si_retrynum ) {
2728                 ch_free( sie->si_retrynum );
2729         }
2730         if ( sie->si_retrynum_init ) {
2731                 ch_free( sie->si_retrynum_init );
2732         }
2733         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2734         if ( sie->si_presentlist ) {
2735             avl_free( sie->si_presentlist, avl_ber_bvfree );
2736         }
2737         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2738                 struct nonpresent_entry* npe;
2739                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2740                 LDAP_LIST_REMOVE( npe, npe_link );
2741                 if ( npe->npe_name ) {
2742                         if ( npe->npe_name->bv_val ) {
2743                                 ch_free( npe->npe_name->bv_val );
2744                         }
2745                         ch_free( npe->npe_name );
2746                 }
2747                 if ( npe->npe_nname ) {
2748                         if ( npe->npe_nname->bv_val ) {
2749                                 ch_free( npe->npe_nname->bv_val );
2750                         }
2751                         ch_free( npe->npe_nname );
2752                 }
2753                 ch_free( npe );
2754         }
2755         ch_free( sie );
2756 }
2757
2758
2759
2760 /* NOTE: used & documented in slapd.conf(5) */
2761 #define IDSTR                   "rid"
2762 #define PROVIDERSTR             "provider"
2763 #define SCHEMASTR               "schemachecking"
2764 #define FILTERSTR               "filter"
2765 #define SEARCHBASESTR           "searchbase"
2766 #define SCOPESTR                "scope"
2767 #define ATTRSONLYSTR            "attrsonly"
2768 #define ATTRSSTR                "attrs"
2769 #define TYPESTR                 "type"
2770 #define INTERVALSTR             "interval"
2771 #define RETRYSTR                "retry"
2772 #define SLIMITSTR               "sizelimit"
2773 #define TLIMITSTR               "timelimit"
2774 #define SYNCDATASTR             "syncdata"
2775
2776 /* FIXME: undocumented */
2777 #define LOGBASESTR      "logbase"
2778 #define LOGFILTERSTR    "logfilter"
2779 #define OLDAUTHCSTR             "bindprincipal"
2780 #define EXATTRSSTR              "exattrs"
2781 #define MANAGEDSAITSTR          "manageDSAit"
2782
2783 /* FIXME: unused */
2784 #define LASTMODSTR              "lastmod"
2785 #define LMGENSTR                "gen"
2786 #define LMNOSTR                 "no"
2787 #define LMREQSTR                "req"
2788 #define SRVTABSTR               "srvtab"
2789 #define SUFFIXSTR               "suffix"
2790
2791 /* mandatory */
2792 #define GOT_ID                  0x0001
2793 #define GOT_PROVIDER            0x0002
2794 #define GOT_BASE                0x0004
2795
2796 /* check */
2797 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER|GOT_BASE)
2798
2799 static struct {
2800         struct berval key;
2801         int val;
2802 } scopes[] = {
2803         { BER_BVC("base"), LDAP_SCOPE_BASE },
2804         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
2805         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
2806         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
2807         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
2808         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
2809         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
2810         { BER_BVNULL, 0 }
2811 };
2812
2813 static slap_verbmasks datamodes[] = {
2814         { BER_BVC("default"), SYNCDATA_DEFAULT },
2815         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
2816         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
2817         { BER_BVNULL, 0 }
2818 };
2819
2820 static int
2821 parse_syncrepl_line(
2822         ConfigArgs      *c,
2823         syncinfo_t      *si )
2824 {
2825         int     gots = 0;
2826         int     i;
2827         char    *val;
2828
2829         for ( i = 1; i < c->argc; i++ ) {
2830                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
2831                                         STRLENOF( IDSTR "=" ) ) )
2832                 {
2833                         int tmp;
2834                         /* '\0' string terminator accounts for '=' */
2835                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
2836                         if ( lutil_atoi( &tmp, val ) != 0 ) {
2837                                 snprintf( c->msg, sizeof( c->msg ),
2838                                         "Error: parse_syncrepl_line: "
2839                                         "unable to parse syncrepl id \"%s\"", val );
2840                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2841                                 return -1;
2842                         }
2843                         if ( tmp >= 1000 || tmp < 0 ) {
2844                                 snprintf( c->msg, sizeof( c->msg ),
2845                                         "Error: parse_syncrepl_line: "
2846                                         "syncrepl id %d is out of range [0..999]", tmp );
2847                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2848                                 return -1;
2849                         }
2850                         si->si_rid = tmp;
2851                         gots |= GOT_ID;
2852                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
2853                                         STRLENOF( PROVIDERSTR "=" ) ) )
2854                 {
2855                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
2856                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
2857                         gots |= GOT_PROVIDER;
2858                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
2859                                         STRLENOF( SCHEMASTR "=" ) ) )
2860                 {
2861                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
2862                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) )) {
2863                                 si->si_schemachecking = 1;
2864                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
2865                                 si->si_schemachecking = 0;
2866                         } else {
2867                                 si->si_schemachecking = 1;
2868                         }
2869                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
2870                                         STRLENOF( FILTERSTR "=" ) ) )
2871                 {
2872                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
2873                         if ( si->si_filterstr.bv_val )
2874                                 ch_free( si->si_filterstr.bv_val );
2875                         ber_str2bv( val, 0, 1, &si->si_filterstr );
2876                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
2877                                         STRLENOF( LOGFILTERSTR "=" ) ) )
2878                 {
2879                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
2880                         if ( si->si_logfilterstr.bv_val )
2881                                 ch_free( si->si_logfilterstr.bv_val );
2882                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
2883                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
2884                                         STRLENOF( SEARCHBASESTR "=" ) ) )
2885                 {
2886                         struct berval   bv;
2887                         int             rc;
2888
2889                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
2890                         if ( si->si_base.bv_val ) {
2891                                 ch_free( si->si_base.bv_val );
2892                         }
2893                         ber_str2bv( val, 0, 0, &bv );
2894                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
2895                         if ( rc != LDAP_SUCCESS ) {
2896                                 snprintf( c->msg, sizeof( c->msg ),
2897                                         "Invalid base DN \"%s\": %d (%s)",
2898                                         val, rc, ldap_err2string( rc ) );
2899                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2900                                 return -1;
2901                         }
2902                         if ( select_backend( &si->si_base, 0, 0 ) != c->be ) {
2903                                 ber_memfree( si->si_base.bv_val );
2904                                 snprintf( c->msg, sizeof( c->msg ),
2905                                         "Base DN \"%s\" is not within the database naming context",
2906                                         val );
2907                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2908                                 return -1;
2909                         }
2910                         gots |= GOT_BASE;
2911                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
2912                                         STRLENOF( LOGBASESTR "=" ) ) )
2913                 {
2914                         struct berval   bv;
2915                         int             rc;
2916
2917                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
2918                         if ( si->si_logbase.bv_val ) {
2919                                 ch_free( si->si_logbase.bv_val );
2920                         }
2921                         ber_str2bv( val, 0, 0, &bv );
2922                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
2923                         if ( rc != LDAP_SUCCESS ) {
2924                                 snprintf( c->msg, sizeof( c->msg ),
2925                                         "Invalid logbase DN \"%s\": %d (%s)",
2926                                         val, rc, ldap_err2string( rc ) );
2927                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2928                                 return -1;
2929                         }
2930                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
2931                                         STRLENOF( SCOPESTR "=" ) ) )
2932                 {
2933                         int j;
2934                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
2935                         for ( j=0; !BER_BVISNULL(&scopes[j].key); j++ ) {
2936                                 if (!strcasecmp( val, scopes[j].key.bv_val )) {
2937                                         si->si_scope = scopes[j].val;
2938                                         break;
2939                                 }
2940                         }
2941                         if ( BER_BVISNULL(&scopes[j].key) ) {
2942                                 snprintf( c->msg, sizeof( c->msg ),
2943                                         "Error: parse_syncrepl_line: "
2944                                         "unknown scope \"%s\"", val);
2945                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2946                                 return -1;
2947                         }
2948                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
2949                                         STRLENOF( ATTRSONLYSTR ) ) )
2950                 {
2951                         si->si_attrsonly = 1;
2952                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
2953                                         STRLENOF( ATTRSSTR "=" ) ) )
2954                 {
2955                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
2956                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
2957                                 char *attr_fname;
2958                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2959                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
2960                                 if ( si->si_anlist == NULL ) {
2961                                         ch_free( attr_fname );
2962                                         return -1;
2963                                 }
2964                                 si->si_anfile = attr_fname;
2965                         } else {
2966                                 char *str, *s, *next;
2967                                 char delimstr[] = " ,\t";
2968                                 str = ch_strdup( val );
2969                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
2970                                                 s != NULL;
2971                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
2972                                 {
2973                                         if ( strlen(s) == 1 && *s == '*' ) {
2974                                                 si->si_allattrs = 1;
2975                                                 *(val + ( s - str )) = delimstr[0];
2976                                         }
2977                                         if ( strlen(s) == 1 && *s == '+' ) {
2978                                                 si->si_allopattrs = 1;
2979                                                 *(val + ( s - str )) = delimstr[0];
2980                                         }
2981                                 }
2982                                 ch_free( str );
2983                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
2984                                 if ( si->si_anlist == NULL ) {
2985                                         return -1;
2986                                 }
2987                         }
2988                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
2989                                         STRLENOF( EXATTRSSTR "=" ) ) )
2990                 {
2991                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
2992                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") )) {
2993                                 char *attr_fname;
2994                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2995                                 si->si_exanlist = file2anlist(
2996                                         si->si_exanlist, attr_fname, " ,\t" );
2997                                 if ( si->si_exanlist == NULL ) {
2998                                         ch_free( attr_fname );
2999                                         return -1;
3000                                 }
3001                                 ch_free( attr_fname );
3002                         } else {
3003                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
3004                                 if ( si->si_exanlist == NULL ) {
3005                                         return -1;
3006                                 }
3007                         }
3008                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
3009                                         STRLENOF( TYPESTR "=" ) ) )
3010                 {
3011                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
3012                         if ( !strncasecmp( val, "refreshOnly",
3013                                                 STRLENOF("refreshOnly") ) )
3014                         {
3015                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3016                         } else if ( !strncasecmp( val, "refreshAndPersist",
3017                                                 STRLENOF("refreshAndPersist") ) )
3018                         {
3019                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
3020                                 si->si_interval = 60;
3021                         } else {
3022                                 snprintf( c->msg, sizeof( c->msg ),
3023                                         "Error: parse_syncrepl_line: "
3024                                         "unknown sync type \"%s\"", val);
3025                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3026                                 return -1;
3027                         }
3028                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
3029                                         STRLENOF( INTERVALSTR "=" ) ) )
3030                 {
3031                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
3032                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
3033                                 si->si_interval = 0;
3034                         } else if ( strchr( val, ':' ) != NULL ) {
3035                                 char *next, *ptr = val;
3036                                 unsigned dd, hh, mm, ss;
3037                                 
3038                                 /* NOTE: the test for ptr[ 0 ] == '-'
3039                                  * should go before the call to strtoul() */
3040                                 dd = strtoul( ptr, &next, 10 );
3041                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' ) {
3042                                         snprintf( c->msg, sizeof( c->msg ),
3043                                                 "Error: parse_syncrepl_line: "
3044                                                 "invalid interval \"%s\", unable to parse days", val );
3045                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3046                                         return -1;
3047                                 }
3048                                 ptr = next + 1;
3049                                 hh = strtoul( ptr, &next, 10 );
3050                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || hh > 24 ) {
3051                                         snprintf( c->msg, sizeof( c->msg ),
3052                                                 "Error: parse_syncrepl_line: "
3053                                                 "invalid interval \"%s\", unable to parse hours", val );
3054                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3055                                         return -1;
3056                                 }
3057                                 ptr = next + 1;
3058                                 mm = strtoul( ptr, &next, 10 );
3059                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || mm > 60 ) {
3060                                         snprintf( c->msg, sizeof( c->msg ),
3061                                                 "Error: parse_syncrepl_line: "
3062                                                 "invalid interval \"%s\", unable to parse minutes", val );
3063                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3064                                         return -1;
3065                                 }
3066                                 ptr = next + 1;
3067                                 ss = strtoul( ptr, &next, 10 );
3068                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != '\0' || ss > 60 ) {
3069                                         snprintf( c->msg, sizeof( c->msg ),
3070                                                 "Error: parse_syncrepl_line: "
3071                                                 "invalid interval \"%s\", unable to parse seconds", val );
3072                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3073                                         return -1;
3074                                 }
3075                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
3076                         } else {
3077                                 unsigned long   t;
3078
3079                                 if ( lutil_parse_time( val, &t ) != 0 ) {
3080                                         snprintf( c->msg, sizeof( c->msg ),
3081                                                 "Error: parse_syncrepl_line: "
3082                                                 "invalid interval \"%s\"", val );
3083                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3084                                         return -1;
3085                                 }
3086                                 si->si_interval = (time_t)t;
3087                         }
3088                         if ( si->si_interval < 0 ) {
3089                                 snprintf( c->msg, sizeof( c->msg ),
3090                                         "Error: parse_syncrepl_line: "
3091                                         "invalid interval \"%ld\"",
3092                                         (long) si->si_interval);
3093                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3094                                 return -1;
3095                         }
3096                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
3097                                         STRLENOF( RETRYSTR "=" ) ) )
3098                 {
3099                         char **retry_list;
3100                         int j, k, n;
3101
3102                         val = c->argv[ i ] + STRLENOF( RETRYSTR "=" );
3103                         retry_list = (char **) ch_calloc( 1, sizeof( char * ));
3104                         retry_list[0] = NULL;
3105
3106                         slap_str2clist( &retry_list, val, " ,\t" );
3107
3108                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3109                         n = k / 2;
3110                         if ( k % 2 ) {
3111                                 snprintf( c->msg, sizeof( c->msg ),
3112                                         "Error: incomplete syncrepl retry list" );
3113                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3114                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3115                                         ch_free( retry_list[k] );
3116                                 }
3117                                 ch_free( retry_list );
3118                                 return 1;
3119                         }
3120                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ));
3121                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ));
3122                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ));
3123                         for ( j = 0; j < n; j++ ) {
3124                                 unsigned long   t;
3125                                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3126                                         snprintf( c->msg, sizeof( c->msg ),
3127                                                 "Error: invalid retry interval \"%s\" (#%d)",
3128                                                 retry_list[j*2], j );
3129                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3130                                         /* do some cleanup */
3131                                         return 1;
3132                                 }
3133                                 si->si_retryinterval[j] = (time_t)t;
3134                                 if ( *retry_list[j*2+1] == '+' ) {
3135                                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3136                                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3137                                         j++;
3138                                         break;
3139                                 } else {
3140                                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3141                                                         || si->si_retrynum_init[j] <= 0 )
3142                                         {
3143                                                 snprintf( c->msg, sizeof( c->msg ),
3144                                                         "Error: invalid initial retry number \"%s\" (#%d)",
3145                                                         retry_list[j*2+1], j );
3146                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3147                                                 /* do some cleanup */
3148                                                 return 1;
3149                                         }
3150                                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3151                                                         || si->si_retrynum[j] <= 0 )
3152                                         {
3153                                                 snprintf( c->msg, sizeof( c->msg ),
3154                                                         "Error: invalid retry number \"%s\" (#%d)",
3155                                                         retry_list[j*2+1], j );
3156                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3157                                                 /* do some cleanup */
3158                                                 return 1;
3159                                         }
3160                                 }
3161                         }
3162                         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3163                         si->si_retrynum[j] = RETRYNUM_TAIL;
3164                         si->si_retryinterval[j] = 0;
3165                         
3166                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3167                                 ch_free( retry_list[k] );
3168                         }
3169                         ch_free( retry_list );
3170                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
3171                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
3172                 {
3173                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
3174                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
3175                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
3176                         {
3177                                 snprintf( c->msg, sizeof( c->msg ),
3178                                         "invalid manageDSAit value \"%s\".\n",
3179                                         val );
3180                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3181                                 return 1;
3182                         }
3183                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
3184                                         STRLENOF( SLIMITSTR "=") ) )
3185                 {
3186                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
3187                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3188                                 si->si_slimit = 0;
3189
3190                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
3191                                 snprintf( c->msg, sizeof( c->msg ),
3192                                         "invalid size limit value \"%s\".\n",
3193                                         val );
3194                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3195                                 return 1;
3196                         }
3197                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
3198                                         STRLENOF( TLIMITSTR "=" ) ) )
3199                 {
3200                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
3201                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3202                                 si->si_tlimit = 0;
3203
3204                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
3205                                 snprintf( c->msg, sizeof( c->msg ),
3206                                         "invalid time limit value \"%s\".\n",
3207                                         val );
3208                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3209                                 return 1;
3210                         }
3211                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
3212                                         STRLENOF( SYNCDATASTR "=" ) ) )
3213                 {
3214                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
3215                         si->si_syncdata = verb_to_mask( val, datamodes );
3216                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
3217                         snprintf( c->msg, sizeof( c->msg ),
3218                                 "Error: parse_syncrepl_line: "
3219                                 "unable to parse \"%s\"\n", c->argv[ i ] );
3220                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3221                         return -1;
3222                 }
3223         }
3224
3225         if ( gots != GOT_ALL ) {
3226                 snprintf( c->msg, sizeof( c->msg ),
3227                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
3228                         gots & GOT_ID ? "" : " "IDSTR,
3229                         gots & GOT_PROVIDER ? "" : " "PROVIDERSTR,
3230                         gots & GOT_BASE ? "" : " "SEARCHBASESTR );
3231                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3232                 return -1;
3233         }
3234
3235         return 0;
3236 }
3237
3238 static int
3239 add_syncrepl(
3240         ConfigArgs *c )
3241 {
3242         syncinfo_t *si;
3243         int     rc = 0;
3244
3245         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
3246                 snprintf( c->msg, sizeof(c->msg), "database %s does not support "
3247                         "operations required for syncrepl", c->be->be_type );
3248                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3249                 return 1;
3250         }
3251         if ( BER_BVISEMPTY( &c->be->be_rootdn )) {
3252                 strcpy( c->msg, "rootDN must be defined before syncrepl may be used" );
3253                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3254                 return 1;
3255         }
3256         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
3257
3258         if ( si == NULL ) {
3259                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
3260                 return 1;
3261         }
3262
3263         si->si_bindconf.sb_tls = SB_TLS_OFF;
3264         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
3265         si->si_schemachecking = 0;
3266         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
3267                 &si->si_filterstr );
3268         si->si_base.bv_val = NULL;
3269         si->si_scope = LDAP_SCOPE_SUBTREE;
3270         si->si_attrsonly = 0;
3271         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3272         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3273         si->si_attrs = NULL;
3274         si->si_allattrs = 0;
3275         si->si_allopattrs = 0;
3276         si->si_exattrs = NULL;
3277         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3278         si->si_interval = 86400;
3279         si->si_retryinterval = NULL;
3280         si->si_retrynum_init = NULL;
3281         si->si_retrynum = NULL;
3282         si->si_manageDSAit = 0;
3283         si->si_tlimit = 0;
3284         si->si_slimit = 0;
3285         si->si_conn_setup = 0;
3286
3287         si->si_presentlist = NULL;
3288         LDAP_LIST_INIT( &si->si_nonpresentlist );
3289         ldap_pvt_thread_mutex_init( &si->si_mutex );
3290
3291         rc = parse_syncrepl_line( c, si );
3292
3293         if ( rc == 0 ) {
3294                 si->si_be = c->be;
3295                 init_syncrepl( si );
3296                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq, si->si_interval,
3297                         do_syncrepl, si, "do_syncrepl", c->be->be_suffix[0].bv_val );
3298                 if ( !si->si_re )
3299                         rc = -1;
3300         }
3301         if ( rc < 0 ) {
3302                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
3303                 syncinfo_free( si );    
3304                 return 1;
3305         } else {
3306                 Debug( LDAP_DEBUG_CONFIG,
3307                         "Config: ** successfully added syncrepl \"%s\"\n",
3308                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
3309                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
3310                 if ( !si->si_schemachecking ) {
3311                         SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3312                 }
3313                 c->be->be_syncinfo = si;
3314                 return 0;
3315         }
3316 }
3317
3318 static void
3319 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
3320 {
3321         struct berval bc, uri;
3322         char buf[BUFSIZ*2], *ptr;
3323         int i;
3324
3325         /* FIXME: we're not checking for buf[] overflow! */
3326
3327         /* temporarily inhibit bindconf from printing URI */
3328         uri = si->si_bindconf.sb_uri;
3329         BER_BVZERO( &si->si_bindconf.sb_uri );
3330         bindconf_unparse( &si->si_bindconf, &bc );
3331         si->si_bindconf.sb_uri = uri;
3332
3333         ptr = buf;
3334         ptr += snprintf( ptr, sizeof( buf ), IDSTR "=%03d " PROVIDERSTR "=%s",
3335                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
3336         if ( !BER_BVISNULL( &bc )) {
3337                 ptr = lutil_strcopy( ptr, bc.bv_val );
3338                 free( bc.bv_val );
3339         }
3340         if ( !BER_BVISEMPTY( &si->si_filterstr )) {
3341                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
3342                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
3343                 *ptr++ = '"';
3344         }
3345         if ( !BER_BVISNULL( &si->si_base )) {
3346                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
3347                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
3348                 *ptr++ = '"';
3349         }
3350         if ( !BER_BVISEMPTY( &si->si_logfilterstr )) {
3351                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
3352                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
3353                 *ptr++ = '"';
3354         }
3355         if ( !BER_BVISNULL( &si->si_logbase )) {
3356                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
3357                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
3358                 *ptr++ = '"';
3359         }
3360         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
3361                 if ( si->si_scope == scopes[i].val ) {
3362                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
3363                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
3364                         break;
3365                 }
3366         }
3367         if ( si->si_attrsonly ) {
3368                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
3369         }
3370         if ( si->si_anfile ) {
3371                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:" );
3372                 ptr = lutil_strcopy( ptr, si->si_anfile );
3373         } else if ( si->si_allattrs || si->si_allopattrs ||
3374                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) )) {
3375                 char *old;
3376                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
3377                 old = ptr;
3378                 ptr = anlist_unparse( si->si_anlist, ptr );
3379                 if ( si->si_allattrs ) {
3380                         if ( old != ptr ) *ptr++ = ',';
3381                         *ptr++ = '*';
3382                 }
3383                 if ( si->si_allopattrs ) {
3384                         if ( old != ptr ) *ptr++ = ',';
3385                         *ptr++ = '+';
3386                 }
3387                 *ptr++ = '"';
3388         }
3389         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3390                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3391                 ptr = anlist_unparse( si->si_exanlist, ptr );
3392         }
3393         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3394         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3395         
3396         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3397         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3398                 "refreshAndPersist" : "refreshOnly" );
3399
3400         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
3401                 int dd, hh, mm, ss;
3402
3403                 dd = si->si_interval;
3404                 ss = dd % 60;
3405                 dd /= 60;
3406                 mm = dd % 60;
3407                 dd /= 60;
3408                 hh = dd % 24;
3409                 dd /= 24;
3410                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
3411                 ptr += sprintf( ptr, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
3412         } else if ( si->si_retryinterval ) {
3413                 int space=0;
3414                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
3415                 for (i=0; si->si_retryinterval[i]; i++) {
3416                         if ( space ) *ptr++ = ' ';
3417                         space = 1;
3418                         ptr += sprintf( ptr, "%ld ", (long) si->si_retryinterval[i] );
3419                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
3420                                 *ptr++ = '+';
3421                         else
3422                                 ptr += sprintf( ptr, "%d", si->si_retrynum_init[i] );
3423                 }
3424                 *ptr++ = '"';
3425         }
3426
3427         if ( si->si_slimit ) {
3428                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
3429                 ptr += sprintf( ptr, "%d", si->si_slimit );
3430         }
3431
3432         if ( si->si_tlimit ) {
3433                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
3434                 ptr += sprintf( ptr, "%d", si->si_tlimit );
3435         }
3436
3437         if ( si->si_syncdata ) {
3438                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
3439                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
3440                         ptr = lutil_strcopy( ptr, bc.bv_val );
3441                 }
3442         }
3443         bc.bv_len = ptr - buf;
3444         bc.bv_val = buf;
3445         ber_dupbv( bv, &bc );
3446 }
3447
3448 int
3449 syncrepl_config( ConfigArgs *c )
3450 {
3451         if (c->op == SLAP_CONFIG_EMIT) {
3452                 if ( c->be->be_syncinfo ) {
3453                         struct berval bv;
3454                         syncrepl_unparse( c->be->be_syncinfo, &bv ); 
3455                         ber_bvarray_add( &c->rvalue_vals, &bv );
3456                         return 0;
3457                 }
3458                 return 1;
3459         } else if ( c->op == LDAP_MOD_DELETE ) {
3460                 struct re_s *re;
3461
3462                 if ( c->be->be_syncinfo ) {
3463                         re = c->be->be_syncinfo->si_re;
3464                         if ( re ) {
3465                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
3466                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
3467                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
3468                         }
3469                         syncinfo_free( c->be->be_syncinfo );
3470                         c->be->be_syncinfo = NULL;
3471                 }
3472                 SLAP_DBFLAGS( c->be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
3473                 return 0;
3474         }
3475         if ( SLAP_SHADOW( c->be ) ) {
3476                 Debug(LDAP_DEBUG_ANY, "%s: "
3477                         "syncrepl: database already shadowed.\n",
3478                         c->log, 0, 0);
3479                 return(1);
3480         } else if ( add_syncrepl( c ) ) {
3481                 return(1);
3482         }
3483         return config_sync_shadow( c );
3484 }