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