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