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