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