]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
Fix prev commit, cleanup fakeroot entry before freeing
[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 );
1255                 if ( !be->be_syncinfo ) {
1256                         SLAP_DBFLAGS( be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
1257                         if ( cs ) {
1258                                 ber_bvarray_free( cs->cs_vals );
1259                                 ldap_pvt_thread_mutex_destroy( &cs->cs_mutex );
1260                                 ch_free( cs );
1261                         }
1262                 }
1263         }
1264         return NULL;
1265 }
1266
1267 static slap_verbmasks modops[] = {
1268         { BER_BVC("add"), LDAP_REQ_ADD },
1269         { BER_BVC("delete"), LDAP_REQ_DELETE },
1270         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1271         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1272         { BER_BVNULL, 0 }
1273 };
1274
1275 static Modifications *
1276 syncrepl_accesslog_mods(
1277         syncinfo_t *si,
1278         struct berval *vals
1279 )
1280 {
1281         char *colon;
1282         const char *text;
1283         AttributeDescription *ad;
1284         struct berval bv, bv2;
1285         short op;
1286         Modifications *mod = NULL, *modlist = NULL, **modtail;
1287         int i;
1288
1289         modtail = &modlist;
1290
1291         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1292                 ad = NULL;
1293                 bv = vals[i];
1294
1295                 colon = ber_bvchr( &bv, ':' );
1296                 if ( !colon ) {
1297                         /* Invalid */
1298                         continue;
1299                 }
1300
1301                 bv.bv_len = colon - bv.bv_val;
1302                 if ( slap_bv2ad( &bv, &ad, &text ) ) {
1303                         /* Invalid */
1304                         continue;
1305                 }
1306
1307                 /* Ignore dynamically generated attrs */
1308                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1309                         continue;
1310                 }
1311
1312                 /* Ignore excluded attrs */
1313                 if ( ldap_charray_inlist( si->si_exattrs,
1314                         ad->ad_type->sat_cname.bv_val ) )
1315                 {
1316                         continue;
1317                 }
1318
1319                 switch(colon[1]) {
1320                 case '+':       op = LDAP_MOD_ADD; break;
1321                 case '-':       op = LDAP_MOD_DELETE; break;
1322                 case '=':       op = LDAP_MOD_REPLACE; break;
1323                 case '#':       op = LDAP_MOD_INCREMENT; break;
1324                 default:        continue;
1325                 }
1326
1327                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1328                         mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
1329                         mod->sml_flags = 0;
1330                         mod->sml_op = op;
1331                         mod->sml_next = NULL;
1332                         mod->sml_desc = ad;
1333                         mod->sml_type = ad->ad_cname;
1334                         mod->sml_values = NULL;
1335                         mod->sml_nvalues = NULL;
1336
1337                         *modtail = mod;
1338                         modtail = &mod->sml_next;
1339                 }
1340                 if ( colon[2] == ' ' ) {
1341                         bv.bv_val = colon + 3;
1342                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1343                         ber_dupbv( &bv2, &bv );
1344                         ber_bvarray_add( &mod->sml_values, &bv2 );
1345                 }
1346         }
1347         return modlist;
1348 }
1349
1350 static Modifications *
1351 syncrepl_changelog_mods(
1352         syncinfo_t *si,
1353         struct berval *vals
1354 )
1355 {
1356         return NULL;    /* FIXME */
1357 }
1358
1359 static int
1360 syncrepl_message_to_op(
1361         syncinfo_t      *si,
1362         Operation       *op,
1363         LDAPMessage     *msg
1364 )
1365 {
1366         BerElement      *ber = NULL;
1367         Modifications   *modlist = NULL;
1368         logschema *ls;
1369         SlapReply rs = { REP_RESULT };
1370         slap_callback cb = { NULL, null_callback, NULL, NULL };
1371
1372         const char      *text;
1373         char txtbuf[SLAP_TEXT_BUFLEN];
1374         size_t textlen = sizeof txtbuf;
1375
1376         struct berval   bdn, dn = BER_BVNULL, ndn;
1377         struct berval   bv, *bvals = NULL;
1378         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1379                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1380                 psup = BER_BVNULL, nsup = BER_BVNULL;
1381         int             rc, deleteOldRdn = 0, freeReqDn = 0;
1382
1383         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1384                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1385                         "Message type should be entry (%d)",
1386                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1387                 return -1;
1388         }
1389
1390         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1391                 ls = &accesslog_sc;
1392         else
1393                 ls = &changelog_sc;
1394
1395         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1396
1397         if ( rc != LDAP_SUCCESS ) {
1398                 Debug( LDAP_DEBUG_ANY,
1399                         "syncrepl_message_to_op: %s dn get failed (%d)",
1400                         si->si_ridtxt, rc, 0 );
1401                 return rc;
1402         }
1403
1404         op->o_tag = LBER_DEFAULT;
1405         op->o_bd = si->si_wbe;
1406
1407         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ) )
1408                 == LDAP_SUCCESS ) {
1409                 if ( bv.bv_val == NULL )
1410                         break;
1411
1412                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn ) ) {
1413                         bdn = bvals[0];
1414                         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1415                         ber_dupbv( &op->o_req_dn, &dn );
1416                         ber_dupbv( &op->o_req_ndn, &ndn );
1417                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1418                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1419                         freeReqDn = 1;
1420                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req ) ) {
1421                         int i = verb_to_mask( bvals[0].bv_val, modops );
1422                         if ( i < 0 ) {
1423                                 Debug( LDAP_DEBUG_ANY,
1424                                         "syncrepl_message_to_op: %s unknown op %s",
1425                                         si->si_ridtxt, bvals[0].bv_val, 0 );
1426                                 ch_free( bvals );
1427                                 rc = -1;
1428                                 goto done;
1429                         }
1430                         op->o_tag = modops[i].mask;
1431                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod ) ) {
1432                         /* Parse attribute into modlist */
1433                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG ) {
1434                                 modlist = syncrepl_accesslog_mods( si, bvals );
1435                         } else {
1436                                 modlist = syncrepl_changelog_mods( si, bvals );
1437                         }
1438                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn ) ) {
1439                         rdn = bvals[0];
1440                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn ) ) {
1441                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ) ) {
1442                                 deleteOldRdn = 1;
1443                         }
1444                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup ) ) {
1445                         sup = bvals[0];
1446                 } else if ( !ber_bvstrcasecmp( &bv,
1447                         &slap_schema.si_ad_entryCSN->ad_cname ) )
1448                 {
1449                         slap_queue_csn( op, bvals );
1450                 }
1451                 ch_free( bvals );
1452         }
1453
1454         /* If we didn't get a mod type or a target DN, bail out */
1455         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn ) ) {
1456                 rc = -1;
1457                 goto done;
1458         }
1459
1460         op->o_callback = &cb;
1461         slap_op_time( &op->o_time, &op->o_tincr );
1462
1463         switch( op->o_tag ) {
1464         case LDAP_REQ_ADD:
1465         case LDAP_REQ_MODIFY:
1466                 /* If we didn't get required data, bail */
1467                 if ( !modlist ) goto done;
1468
1469                 rc = slap_mods_check( op, modlist, &text, txtbuf, textlen, NULL );
1470
1471                 if ( rc != LDAP_SUCCESS ) {
1472                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1473                                 "mods check (%s)\n",
1474                                 si->si_ridtxt, text, 0 );
1475                         goto done;
1476                 }
1477
1478                 if ( op->o_tag == LDAP_REQ_ADD ) {
1479                         Entry *e = entry_alloc();
1480                         op->ora_e = e;
1481                         op->ora_e->e_name = op->o_req_dn;
1482                         op->ora_e->e_nname = op->o_req_ndn;
1483                         freeReqDn = 0;
1484                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1485                         if( rc != LDAP_SUCCESS ) {
1486                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1487                                 "mods2entry (%s)\n",
1488                                         si->si_ridtxt, text, 0 );
1489                         } else {
1490                                 rc = op->o_bd->be_add( op, &rs );
1491                                 Debug( LDAP_DEBUG_SYNC,
1492                                         "syncrepl_message_to_op: %s be_add %s (%d)\n", 
1493                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1494                         }
1495                         if ( e == op->ora_e )
1496                                 be_entry_release_w( op, op->ora_e );
1497                 } else {
1498                         op->orm_modlist = modlist;
1499                         op->o_bd = si->si_wbe;
1500                         rc = op->o_bd->be_modify( op, &rs );
1501                         Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1502                                 "syncrepl_message_to_op: %s be_modify %s (%d)\n", 
1503                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
1504                         op->o_bd = si->si_be;
1505                 }
1506                 break;
1507         case LDAP_REQ_MODRDN:
1508                 if ( BER_BVISNULL( &rdn ) ) goto done;
1509
1510                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ) ) {
1511                         goto done;
1512                 }
1513                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ) ) {
1514                         goto done;
1515                 }
1516                 if ( !BER_BVISNULL( &sup ) ) {
1517                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ) ) {
1518                                 goto done;
1519                         }
1520                         op->orr_newSup = &psup;
1521                         op->orr_nnewSup = &nsup;
1522                 } else {
1523                         op->orr_newSup = NULL;
1524                         op->orr_nnewSup = NULL;
1525                 }
1526                 op->orr_newrdn = prdn;
1527                 op->orr_nnewrdn = nrdn;
1528                 op->orr_deleteoldrdn = deleteOldRdn;
1529                 op->orr_modlist = NULL;
1530                 if ( slap_modrdn2mods( op, &rs ) ) {
1531                         goto done;
1532                 }
1533
1534                 /* Append modlist for operational attrs */
1535                 {
1536                         Modifications *m;
1537
1538                         for ( m = op->orr_modlist; m->sml_next; m = m->sml_next )
1539                                 ;
1540                         m->sml_next = modlist;
1541                         modlist = NULL;
1542                 }
1543                 rc = op->o_bd->be_modrdn( op, &rs );
1544                 slap_mods_free( op->orr_modlist, 1 );
1545                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1546                         "syncrepl_message_to_op: %s be_modrdn %s (%d)\n", 
1547                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1548                 break;
1549         case LDAP_REQ_DELETE:
1550                 rc = op->o_bd->be_delete( op, &rs );
1551                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1552                         "syncrepl_message_to_op: %s be_delete %s (%d)\n", 
1553                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1554                 break;
1555         }
1556 done:
1557         slap_graduate_commit_csn( op );
1558         op->o_bd = si->si_be;
1559         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
1560         BER_BVZERO( &op->o_csn );
1561         if ( modlist ) {
1562                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1563         }
1564         if ( !BER_BVISNULL( &rdn ) ) {
1565                 if ( !BER_BVISNULL( &nsup ) ) {
1566                         ch_free( nsup.bv_val );
1567                 }
1568                 if ( !BER_BVISNULL( &psup ) ) {
1569                         ch_free( psup.bv_val );
1570                 }
1571                 if ( !BER_BVISNULL( &nrdn ) ) {
1572                         ch_free( nrdn.bv_val );
1573                 }
1574                 if ( !BER_BVISNULL( &prdn ) ) {
1575                         ch_free( prdn.bv_val );
1576                 }
1577         }
1578         if ( freeReqDn ) {
1579                 ch_free( op->o_req_ndn.bv_val );
1580                 ch_free( op->o_req_dn.bv_val );
1581         }
1582         ber_free( ber, 0 );
1583         return rc;
1584 }
1585
1586 static int
1587 syncrepl_message_to_entry(
1588         syncinfo_t      *si,
1589         Operation       *op,
1590         LDAPMessage     *msg,
1591         Modifications   **modlist,
1592         Entry                   **entry,
1593         int             syncstate
1594 )
1595 {
1596         Entry           *e = NULL;
1597         BerElement      *ber = NULL;
1598         Modifications   tmp;
1599         Modifications   *mod;
1600         Modifications   **modtail = modlist;
1601
1602         const char      *text;
1603         char txtbuf[SLAP_TEXT_BUFLEN];
1604         size_t textlen = sizeof txtbuf;
1605
1606         struct berval   bdn = BER_BVNULL, dn, ndn;
1607         int             rc, is_ctx;
1608
1609         *modlist = NULL;
1610
1611         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1612                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s "
1613                         "Message type should be entry (%d)",
1614                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1615                 return -1;
1616         }
1617
1618         op->o_tag = LDAP_REQ_ADD;
1619
1620         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1621         if ( rc != LDAP_SUCCESS ) {
1622                 Debug( LDAP_DEBUG_ANY,
1623                         "syncrepl_message_to_entry: %s dn get failed (%d)",
1624                         si->si_ridtxt, rc, 0 );
1625                 return rc;
1626         }
1627
1628         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1629                 /* NOTE: this could be done even before decoding the DN,
1630                  * although encoding errors wouldn't be detected */
1631                 rc = LDAP_SUCCESS;
1632                 goto done;
1633         }
1634
1635         if ( entry == NULL ) {
1636                 rc = -1;
1637                 goto done;
1638         }
1639
1640         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1641         ber_dupbv( &op->o_req_dn, &dn );
1642         ber_dupbv( &op->o_req_ndn, &ndn );
1643         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1644         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1645
1646         is_ctx = dn_match( &op->o_req_ndn, &op->o_bd->be_nsuffix[0] );
1647
1648         e = entry_alloc();
1649         e->e_name = op->o_req_dn;
1650         e->e_nname = op->o_req_ndn;
1651
1652         while ( ber_remaining( ber ) ) {
1653                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1654                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1655                 {
1656                         break;
1657                 }
1658
1659                 /* Drop all updates to the contextCSN of the context entry
1660                  * (ITS#4622, etc.)
1661                  */
1662                 if ( is_ctx && !strcasecmp( tmp.sml_type.bv_val,
1663                         slap_schema.si_ad_contextCSN->ad_cname.bv_val )) {
1664                         ber_bvarray_free( tmp.sml_values );
1665                         continue;
1666                 }
1667
1668                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ) );
1669
1670                 mod->sml_op = LDAP_MOD_REPLACE;
1671                 mod->sml_flags = 0;
1672                 mod->sml_next = NULL;
1673                 mod->sml_desc = NULL;
1674                 mod->sml_type = tmp.sml_type;
1675                 mod->sml_values = tmp.sml_values;
1676                 mod->sml_nvalues = NULL;
1677
1678                 *modtail = mod;
1679                 modtail = &mod->sml_next;
1680         }
1681
1682         if ( *modlist == NULL ) {
1683                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s no attributes\n",
1684                         si->si_ridtxt, 0, 0 );
1685                 rc = -1;
1686                 goto done;
1687         }
1688
1689         rc = slap_mods_check( op, *modlist, &text, txtbuf, textlen, NULL );
1690
1691         if ( rc != LDAP_SUCCESS ) {
1692                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods check (%s)\n",
1693                         si->si_ridtxt, text, 0 );
1694                 goto done;
1695         }
1696
1697         /* Strip out dynamically generated attrs */
1698         for ( modtail = modlist; *modtail ; ) {
1699                 mod = *modtail;
1700                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1701                         *modtail = mod->sml_next;
1702                         slap_mod_free( &mod->sml_mod, 0 );
1703                         ch_free( mod );
1704                 } else {
1705                         modtail = &mod->sml_next;
1706                 }
1707         }
1708
1709         /* Strip out attrs in exattrs list */
1710         for ( modtail = modlist; *modtail ; ) {
1711                 mod = *modtail;
1712                 if ( ldap_charray_inlist( si->si_exattrs,
1713                         mod->sml_desc->ad_type->sat_cname.bv_val ) )
1714                 {
1715                         *modtail = mod->sml_next;
1716                         slap_mod_free( &mod->sml_mod, 0 );
1717                         ch_free( mod );
1718                 } else {
1719                         modtail = &mod->sml_next;
1720                 }
1721         }
1722
1723         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1724         if( rc != LDAP_SUCCESS ) {
1725                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods2entry (%s)\n",
1726                         si->si_ridtxt, text, 0 );
1727         }
1728
1729 done:
1730         ber_free( ber, 0 );
1731         if ( rc != LDAP_SUCCESS ) {
1732                 if ( e ) {
1733                         entry_free( e );
1734                         e = NULL;
1735                 }
1736         }
1737         *entry = e;
1738
1739         return rc;
1740 }
1741
1742 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1743
1744 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1745  * entry if a previous refresh was interrupted before sending us a new
1746  * context state. We try to compare the new entry to the existing entry
1747  * and ignore the new entry if they are the same.
1748  *
1749  * Also, we may get an update where the entryDN has changed, due to
1750  * a ModDn on the provider. We detect this as well, so we can issue
1751  * the corresponding operation locally.
1752  *
1753  * In the case of a modify, we get a list of all the attributes
1754  * in the original entry. Rather than deleting the entry and re-adding it,
1755  * we issue a Modify request that deletes all the attributes and adds all
1756  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1757  * entry.
1758  *
1759  * We otherwise distinguish ModDN from Modify; in the case of
1760  * a ModDN we just use the CSN, modifyTimestamp and modifiersName
1761  * operational attributes from the entry, and do a regular ModDN.
1762  */
1763 typedef struct dninfo {
1764         Entry *new_entry;
1765         struct berval dn;
1766         struct berval ndn;
1767         int renamed;    /* Was an existing entry renamed? */
1768         int delOldRDN;  /* Was old RDN deleted? */
1769         Modifications **modlist;        /* the modlist we received */
1770         Modifications *mods;    /* the modlist we compared */
1771 } dninfo;
1772
1773 static int
1774 syncrepl_entry(
1775         syncinfo_t* si,
1776         Operation *op,
1777         Entry* entry,
1778         Modifications** modlist,
1779         int syncstate,
1780         struct berval* syncUUID )
1781 {
1782         Backend *be = op->o_bd;
1783         slap_callback   cb = { NULL, NULL, NULL, NULL };
1784         struct berval   *syncuuid_bv = NULL;
1785         struct berval   syncUUID_strrep = BER_BVNULL;
1786         struct berval   uuid_bv = BER_BVNULL;
1787
1788         SlapReply       rs_search = {REP_RESULT};
1789         SlapReply       rs_delete = {REP_RESULT};
1790         SlapReply       rs_add = {REP_RESULT};
1791         SlapReply       rs_modify = {REP_RESULT};
1792         Filter f = {0};
1793 #ifdef LDAP_COMP_MATCH
1794         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1795 #else
1796         AttributeAssertion ava = { NULL, BER_BVNULL };
1797 #endif
1798         int rc = LDAP_SUCCESS;
1799
1800         struct berval pdn = BER_BVNULL;
1801         dninfo dni = {0};
1802         int     retry = 1;
1803
1804         switch( syncstate ) {
1805         case LDAP_SYNC_PRESENT:
1806                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1807                                         si->si_ridtxt,
1808                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1809                 break;
1810         case LDAP_SYNC_ADD:
1811                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1812                                         si->si_ridtxt,
1813                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1814                 break;
1815         case LDAP_SYNC_DELETE:
1816                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1817                                         si->si_ridtxt,
1818                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1819                 break;
1820         case LDAP_SYNC_MODIFY:
1821                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s %s\n",
1822                                         si->si_ridtxt,
1823                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1824                 break;
1825         default:
1826                 Debug( LDAP_DEBUG_ANY, "syncrepl_entry: %s %s\n",
1827                                         si->si_ridtxt,
1828                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1829         }
1830
1831         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ) ) {
1832                 if ( !si->si_refreshPresent ) {
1833                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1834                         if ( avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1835                                 syncuuid_cmp, avl_dup_error ) )
1836                         {
1837                                 ber_bvfree( syncuuid_bv );
1838                                 syncuuid_bv = NULL;
1839                         }
1840                 }
1841         }
1842
1843         if ( syncstate == LDAP_SYNC_PRESENT ) {
1844                 return 0;
1845         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1846                 if ( entry == NULL ) {
1847                         return 0;
1848                 }
1849         }
1850
1851         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1852         if ( syncstate != LDAP_SYNC_DELETE ) {
1853                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1854
1855                 if ( a == NULL ) {
1856                         /* add if missing */
1857                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1858                                 &syncUUID_strrep, syncUUID );
1859
1860                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1861                         /* replace only if necessary */
1862                         if ( a->a_nvals != a->a_vals ) {
1863                                 ber_memfree( a->a_nvals[0].bv_val );
1864                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1865                         }
1866                         ber_memfree( a->a_vals[0].bv_val );
1867                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1868                 }
1869         }
1870
1871         f.f_choice = LDAP_FILTER_EQUALITY;
1872         f.f_ava = &ava;
1873         ava.aa_desc = slap_schema.si_ad_entryUUID;
1874         ava.aa_value = *syncUUID;
1875
1876         if ( syncuuid_bv ) {
1877                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s inserted UUID %s\n",
1878                         si->si_ridtxt, syncUUID_strrep.bv_val, 0 );
1879         }
1880         op->ors_filter = &f;
1881
1882         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
1883         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1884                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1885         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1886         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1887                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
1888         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1889         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1890
1891         op->o_tag = LDAP_REQ_SEARCH;
1892         op->ors_scope = LDAP_SCOPE_SUBTREE;
1893         op->ors_deref = LDAP_DEREF_NEVER;
1894
1895         /* get the entry for this UUID */
1896         op->o_req_dn = si->si_base;
1897         op->o_req_ndn = si->si_base;
1898
1899         op->o_time = slap_get_time();
1900         op->ors_tlimit = SLAP_NO_LIMIT;
1901         op->ors_slimit = 1;
1902
1903         op->ors_attrs = slap_anlist_all_attributes;
1904         op->ors_attrsonly = 0;
1905
1906         /* set callback function */
1907         op->o_callback = &cb;
1908         cb.sc_response = dn_callback;
1909         cb.sc_private = &dni;
1910         dni.new_entry = entry;
1911         dni.modlist = modlist;
1912
1913         if ( limits_check( op, &rs_search ) == 0 ) {
1914                 rc = be->be_search( op, &rs_search );
1915                 Debug( LDAP_DEBUG_SYNC,
1916                                 "syncrepl_entry: %s be_search (%d)\n", 
1917                                 si->si_ridtxt, rc, 0 );
1918         }
1919
1920         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1921                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1922         }
1923
1924         cb.sc_response = null_callback;
1925         cb.sc_private = si;
1926
1927         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1928                 Debug( LDAP_DEBUG_SYNC,
1929                                 "syncrepl_entry: %s %s\n",
1930                                 si->si_ridtxt, entry->e_name.bv_val, 0 );
1931         } else {
1932                 Debug( LDAP_DEBUG_SYNC,
1933                                 "syncrepl_entry: %s %s\n",
1934                                 si->si_ridtxt, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
1935         }
1936
1937         slap_op_time( &op->o_time, &op->o_tincr );
1938         switch ( syncstate ) {
1939         case LDAP_SYNC_ADD:
1940         case LDAP_SYNC_MODIFY:
1941                 {
1942                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
1943                         if ( a ) {
1944                                 /* FIXME: op->o_csn is assumed to be
1945                                  * on the thread's slab; this needs
1946                                  * to be cleared ASAP.
1947                                  * What happens if already present?
1948                                  */
1949                                 assert( BER_BVISNULL( &op->o_csn ) );
1950                                 op->o_csn = a->a_vals[0];
1951                         }
1952                 }
1953 retry_add:;
1954                 if ( BER_BVISNULL( &dni.dn ) ) {
1955
1956                         op->o_req_dn = entry->e_name;
1957                         op->o_req_ndn = entry->e_nname;
1958                         op->o_tag = LDAP_REQ_ADD;
1959                         op->ora_e = entry;
1960                         op->o_bd = si->si_wbe;
1961
1962                         rc = op->o_bd->be_add( op, &rs_add );
1963                         Debug( LDAP_DEBUG_SYNC,
1964                                         "syncrepl_entry: %s be_add (%d)\n", 
1965                                         si->si_ridtxt, rc, 0 );
1966                         switch ( rs_add.sr_err ) {
1967                         case LDAP_SUCCESS:
1968                                 if ( op->ora_e == entry ) {
1969                                         be_entry_release_w( op, entry );
1970                                 }
1971                                 entry = NULL;
1972                                 break;
1973
1974                         case LDAP_REFERRAL:
1975                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1976                          * only if the suffix entry is not present */
1977                         case LDAP_NO_SUCH_OBJECT:
1978                                 rc = syncrepl_add_glue( op, entry );
1979                                 entry = NULL;
1980                                 break;
1981
1982                         /* if an entry was added via syncrepl_add_glue(),
1983                          * it likely has no entryUUID, so the previous
1984                          * be_search() doesn't find it.  In this case,
1985                          * give syncrepl a chance to modify it. Also
1986                          * allow for entries that were recreated with the
1987                          * same DN but a different entryUUID.
1988                          */
1989                         case LDAP_ALREADY_EXISTS:
1990                                 if ( retry ) {
1991                                         Operation       op2 = *op;
1992                                         SlapReply       rs2 = { 0 };
1993                                         slap_callback   cb2 = { 0 };
1994
1995                                         op2.o_bd = be;
1996                                         op2.o_tag = LDAP_REQ_SEARCH;
1997                                         op2.o_req_dn = entry->e_name;
1998                                         op2.o_req_ndn = entry->e_nname;
1999                                         op2.ors_scope = LDAP_SCOPE_BASE;
2000                                         op2.ors_deref = LDAP_DEREF_NEVER;
2001                                         op2.ors_attrs = slap_anlist_all_attributes;
2002                                         op2.ors_attrsonly = 0;
2003                                         op2.ors_limit = NULL;
2004                                         op2.ors_slimit = 1;
2005                                         op2.ors_tlimit = SLAP_NO_LIMIT;
2006
2007                                         f.f_choice = LDAP_FILTER_PRESENT;
2008                                         f.f_desc = slap_schema.si_ad_objectClass;
2009                                         op2.ors_filter = &f;
2010                                         op2.ors_filterstr = generic_filterstr;
2011
2012                                         op2.o_callback = &cb2;
2013                                         cb2.sc_response = dn_callback;
2014                                         cb2.sc_private = &dni;
2015
2016                                         rc = be->be_search( &op2, &rs2 );
2017                                         if ( rc ) goto done;
2018
2019                                         retry = 0;
2020                                         slap_op_time( &op->o_time, &op->o_tincr );
2021                                         goto retry_add;
2022                                 }
2023                                 /* FALLTHRU */
2024
2025                         default:
2026                                 Debug( LDAP_DEBUG_ANY,
2027                                         "syncrepl_entry: %s be_add failed (%d)\n",
2028                                         si->si_ridtxt, rs_add.sr_err, 0 );
2029                                 break;
2030                         }
2031                         op->o_bd = be;
2032                         goto done;
2033                 }
2034                 /* FALLTHRU */
2035                 op->o_req_dn = dni.dn;
2036                 op->o_req_ndn = dni.ndn;
2037                 if ( dni.renamed ) {
2038                         struct berval noldp, newp, nnewp;
2039
2040                         op->o_tag = LDAP_REQ_MODRDN;
2041                         dnRdn( &entry->e_name, &op->orr_newrdn );
2042                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
2043
2044                         dnParent( &dni.ndn, &noldp );
2045                         dnParent( &entry->e_nname, &nnewp );
2046                         if ( !dn_match( &noldp, &nnewp ) ) {
2047                                 dnParent( &entry->e_name, &newp );
2048                                 op->orr_newSup = &newp;
2049                                 op->orr_nnewSup = &nnewp;
2050                         } else {
2051                                 op->orr_newSup = NULL;
2052                                 op->orr_nnewSup = NULL;
2053                         }
2054                         op->orr_deleteoldrdn = dni.delOldRDN;
2055                         op->orr_modlist = NULL;
2056                         if ( ( rc = slap_modrdn2mods( op, &rs_modify ) ) ) {
2057                                 goto done;
2058                         }
2059
2060                         /* RDNs must be NUL-terminated for back-ldap */
2061                         noldp = op->orr_newrdn;
2062                         ber_dupbv_x( &op->orr_newrdn, &noldp, op->o_tmpmemctx );
2063                         noldp = op->orr_nnewrdn;
2064                         ber_dupbv_x( &op->orr_nnewrdn, &noldp, op->o_tmpmemctx );
2065
2066                         /* Setup opattrs too */
2067                         {
2068                                 AttributeDescription *opattrs[] = {
2069                                         slap_schema.si_ad_entryCSN,
2070                                         slap_schema.si_ad_modifiersName,
2071                                         slap_schema.si_ad_modifyTimestamp,
2072                                         NULL
2073                                 };
2074                                 Modifications *mod, **modtail, **ml;
2075                                 int i;
2076
2077                                 for ( mod = op->orr_modlist;
2078                                         mod->sml_next;
2079                                         mod = mod->sml_next )
2080                                         ;
2081                                 modtail = &mod->sml_next;
2082
2083                                 /* pull mod off incoming modlist, append to orr_modlist */
2084                                 for ( i = 0; opattrs[i]; i++ ) {
2085                                         for ( ml = modlist; *ml; ml = &(*ml)->sml_next )
2086                                         {
2087                                                 if ( (*ml)->sml_desc == opattrs[i] ) {
2088                                                         mod = *ml;
2089                                                         *ml = mod->sml_next;
2090                                                         mod->sml_next = NULL;
2091                                                         *modtail = mod;
2092                                                         modtail = &mod->sml_next;
2093                                                         break;
2094                                                 }
2095                                         }
2096                                 }
2097                         }
2098                         op->o_bd = si->si_wbe;
2099                         rc = op->o_bd->be_modrdn( op, &rs_modify );
2100                         op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
2101                         op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
2102
2103                         slap_mods_free( op->orr_modlist, 1 );
2104                         Debug( LDAP_DEBUG_SYNC,
2105                                         "syncrepl_entry: %s be_modrdn (%d)\n", 
2106                                         si->si_ridtxt, rc, 0 );
2107                         op->o_bd = be;
2108                         goto done;
2109                 }
2110                 if ( dni.mods ) {
2111                         op->o_tag = LDAP_REQ_MODIFY;
2112                         op->orm_modlist = dni.mods;
2113                         op->orm_no_opattrs = 1;
2114                         op->o_bd = si->si_wbe;
2115
2116                         rc = op->o_bd->be_modify( op, &rs_modify );
2117                         slap_mods_free( op->orm_modlist, 1 );
2118                         Debug( LDAP_DEBUG_SYNC,
2119                                         "syncrepl_entry: %s be_modify (%d)\n", 
2120                                         si->si_ridtxt, rc, 0 );
2121                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2122                                 Debug( LDAP_DEBUG_ANY,
2123                                         "syncrepl_entry: %s be_modify failed (%d)\n",
2124                                         si->si_ridtxt, rs_modify.sr_err, 0 );
2125                         }
2126                         op->o_bd = be;
2127                 } else {
2128                         Debug( LDAP_DEBUG_SYNC,
2129                                         "syncrepl_entry: %s entry unchanged, ignored (%s)\n", 
2130                                         si->si_ridtxt, op->o_req_dn.bv_val, 0 );
2131                 }
2132                 goto done;
2133         case LDAP_SYNC_DELETE :
2134                 if ( !BER_BVISNULL( &dni.dn ) ) {
2135                         op->o_req_dn = dni.dn;
2136                         op->o_req_ndn = dni.ndn;
2137                         op->o_tag = LDAP_REQ_DELETE;
2138                         op->o_bd = si->si_wbe;
2139                         rc = op->o_bd->be_delete( op, &rs_delete );
2140                         Debug( LDAP_DEBUG_SYNC,
2141                                         "syncrepl_entry: %s be_delete (%d)\n", 
2142                                         si->si_ridtxt, rc, 0 );
2143
2144                         while ( rs_delete.sr_err == LDAP_SUCCESS
2145                                 && op->o_delete_glue_parent ) {
2146                                 op->o_delete_glue_parent = 0;
2147                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2148                                         slap_callback cb = { NULL };
2149                                         cb.sc_response = slap_null_cb;
2150                                         dnParent( &op->o_req_ndn, &pdn );
2151                                         op->o_req_dn = pdn;
2152                                         op->o_req_ndn = pdn;
2153                                         op->o_callback = &cb;
2154                                         op->o_bd->be_delete( op, &rs_delete );
2155                                 } else {
2156                                         break;
2157                                 }
2158                         }
2159                         op->o_bd = be;
2160                 }
2161                 goto done;
2162
2163         default :
2164                 Debug( LDAP_DEBUG_ANY,
2165                         "syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
2166                 goto done;
2167         }
2168
2169 done:
2170         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2171                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2172                 BER_BVZERO( &syncUUID_strrep );
2173         }
2174         if ( !BER_BVISNULL( &dni.ndn ) ) {
2175                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2176         }
2177         if ( !BER_BVISNULL( &dni.dn ) ) {
2178                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2179         }
2180         if ( entry )
2181                 entry_free( entry );
2182         BER_BVZERO( &op->o_csn );
2183         return rc;
2184 }
2185
2186 static struct berval gcbva[] = {
2187         BER_BVC("top"),
2188         BER_BVC("glue"),
2189         BER_BVNULL
2190 };
2191
2192 #define NP_DELETE_ONE   2
2193
2194 static void
2195 syncrepl_del_nonpresent(
2196         Operation *op,
2197         syncinfo_t *si,
2198         BerVarray uuids,
2199         struct berval *cookiecsn )
2200 {
2201         Backend* be = op->o_bd;
2202         slap_callback   cb = { NULL };
2203         SlapReply       rs_search = {REP_RESULT};
2204         SlapReply       rs_delete = {REP_RESULT};
2205         SlapReply       rs_modify = {REP_RESULT};
2206         struct nonpresent_entry *np_list, *np_prev;
2207         int rc;
2208         AttributeName   an[2];
2209
2210         struct berval pdn = BER_BVNULL;
2211         struct berval csn;
2212
2213         op->o_req_dn = si->si_base;
2214         op->o_req_ndn = si->si_base;
2215
2216         cb.sc_response = nonpresent_callback;
2217         cb.sc_private = si;
2218
2219         op->o_callback = &cb;
2220         op->o_tag = LDAP_REQ_SEARCH;
2221         op->ors_scope = si->si_scope;
2222         op->ors_deref = LDAP_DEREF_NEVER;
2223         op->o_time = slap_get_time();
2224         op->ors_tlimit = SLAP_NO_LIMIT;
2225
2226
2227         if ( uuids ) {
2228                 Filter uf;
2229 #ifdef LDAP_COMP_MATCH
2230                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
2231 #else
2232                 AttributeAssertion eq = { NULL, BER_BVNULL };
2233 #endif
2234                 int i;
2235
2236                 op->ors_attrsonly = 1;
2237                 op->ors_attrs = slap_anlist_no_attrs;
2238                 op->ors_limit = NULL;
2239                 op->ors_filter = &uf;
2240
2241                 uf.f_ava = &eq;
2242                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2243                 uf.f_next = NULL;
2244                 uf.f_choice = LDAP_FILTER_EQUALITY;
2245                 si->si_refreshDelete |= NP_DELETE_ONE;
2246
2247                 for (i=0; uuids[i].bv_val; i++) {
2248                         op->ors_slimit = 1;
2249                         slap_uuidstr_from_normalized( &uf.f_av_value, &uuids[i],
2250                                 op->o_tmpmemctx );
2251                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2252                         op->o_tmpfree( uf.f_av_value.bv_val, op->o_tmpmemctx );
2253                         uf.f_av_value = uuids[i];
2254                         rc = be->be_search( op, &rs_search );
2255                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2256                 }
2257                 si->si_refreshDelete ^= NP_DELETE_ONE;
2258         } else {
2259                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2260                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2261                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2262                 op->ors_attrs = an;
2263                 op->ors_slimit = SLAP_NO_LIMIT;
2264                 op->ors_attrsonly = 0;
2265                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2266                 op->ors_filterstr = si->si_filterstr;
2267                 op->o_nocaching = 1;
2268
2269                 if ( limits_check( op, &rs_search ) == 0 ) {
2270                         rc = be->be_search( op, &rs_search );
2271                 }
2272                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
2273         }
2274
2275         op->o_nocaching = 0;
2276
2277         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2278
2279                 if ( cookiecsn && !BER_BVISNULL( cookiecsn ) ) {
2280                         csn = *cookiecsn;
2281                 } else {
2282                         csn = si->si_syncCookie.ctxcsn[0];
2283                 }
2284
2285                 op->o_bd = si->si_wbe;
2286                 slap_queue_csn( op, &csn );
2287
2288                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2289                 while ( np_list != NULL ) {
2290                         LDAP_LIST_REMOVE( np_list, npe_link );
2291                         np_prev = np_list;
2292                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2293                         op->o_tag = LDAP_REQ_DELETE;
2294                         op->o_callback = &cb;
2295                         cb.sc_response = null_callback;
2296                         cb.sc_private = si;
2297                         op->o_req_dn = *np_prev->npe_name;
2298                         op->o_req_ndn = *np_prev->npe_nname;
2299                         rc = op->o_bd->be_delete( op, &rs_delete );
2300                         Debug( LDAP_DEBUG_SYNC,
2301                                 "syncrepl_del_nonpresent: %s be_delete %s (%d)\n", 
2302                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
2303
2304                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2305                                 Modifications mod1, mod2;
2306                                 mod1.sml_op = LDAP_MOD_REPLACE;
2307                                 mod1.sml_flags = 0;
2308                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2309                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2310                                 mod1.sml_values = &gcbva[0];
2311                                 mod1.sml_nvalues = NULL;
2312                                 mod1.sml_next = &mod2;
2313
2314                                 mod2.sml_op = LDAP_MOD_REPLACE;
2315                                 mod2.sml_flags = 0;
2316                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2317                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2318                                 mod2.sml_values = &gcbva[1];
2319                                 mod2.sml_nvalues = NULL;
2320                                 mod2.sml_next = NULL;
2321
2322                                 op->o_tag = LDAP_REQ_MODIFY;
2323                                 op->orm_modlist = &mod1;
2324
2325                                 rc = op->o_bd->be_modify( op, &rs_modify );
2326                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2327                         }
2328
2329                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2330                                         op->o_delete_glue_parent ) {
2331                                 op->o_delete_glue_parent = 0;
2332                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2333                                         slap_callback cb = { NULL };
2334                                         cb.sc_response = slap_null_cb;
2335                                         dnParent( &op->o_req_ndn, &pdn );
2336                                         op->o_req_dn = pdn;
2337                                         op->o_req_ndn = pdn;
2338                                         op->o_callback = &cb;
2339                                         /* give it a root privil ? */
2340                                         op->o_bd->be_delete( op, &rs_delete );
2341                                 } else {
2342                                         break;
2343                                 }
2344                         }
2345
2346                         op->o_delete_glue_parent = 0;
2347
2348                         ber_bvfree( np_prev->npe_name );
2349                         ber_bvfree( np_prev->npe_nname );
2350                         ch_free( np_prev );
2351                 }
2352
2353                 slap_graduate_commit_csn( op );
2354                 op->o_bd = be;
2355
2356                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2357                 BER_BVZERO( &op->o_csn );
2358         }
2359
2360         return;
2361 }
2362
2363 int
2364 syncrepl_add_glue(
2365         Operation* op,
2366         Entry *e )
2367 {
2368         Backend *be = op->o_bd;
2369         slap_callback cb = { NULL };
2370         Attribute       *a;
2371         int     rc;
2372         int suffrdns;
2373         int i;
2374         struct berval dn = BER_BVNULL;
2375         struct berval ndn = BER_BVNULL;
2376         Entry   *glue;
2377         SlapReply       rs_add = {REP_RESULT};
2378         struct berval   ptr, nptr;
2379         char            *comma;
2380
2381         op->o_tag = LDAP_REQ_ADD;
2382         op->o_callback = &cb;
2383         cb.sc_response = null_callback;
2384         cb.sc_private = NULL;
2385
2386         dn = e->e_name;
2387         ndn = e->e_nname;
2388
2389         /* count RDNs in suffix */
2390         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2391                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2392                         comma++;
2393                         ptr.bv_len -= comma - ptr.bv_val;
2394                         ptr.bv_val = comma;
2395                         i++;
2396                 }
2397                 suffrdns = i;
2398         } else {
2399                 /* suffix is "" */
2400                 suffrdns = 0;
2401         }
2402
2403         /* Start with BE suffix */
2404         ptr = dn;
2405         for ( i = 0; i < suffrdns; i++ ) {
2406                 comma = ber_bvrchr( &ptr, ',' );
2407                 if ( comma != NULL ) {
2408                         ptr.bv_len = comma - ptr.bv_val;
2409                 } else {
2410                         ptr.bv_len = 0;
2411                         break;
2412                 }
2413         }
2414         
2415         if ( !BER_BVISEMPTY( &ptr ) ) {
2416                 dn.bv_len -= ptr.bv_len + 1;
2417                 dn.bv_val += ptr.bv_len + 1;
2418         }
2419
2420         /* the normalizedDNs are always the same length, no counting
2421          * required.
2422          */
2423         nptr = ndn;
2424         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2425                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2426                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2427
2428                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2429
2430         } else {
2431                 nptr.bv_len = 0;
2432         }
2433
2434         while ( ndn.bv_val > e->e_nname.bv_val ) {
2435                 glue = entry_alloc();
2436                 ber_dupbv( &glue->e_name, &dn );
2437                 ber_dupbv( &glue->e_nname, &ndn );
2438
2439                 a = attr_alloc( slap_schema.si_ad_objectClass );
2440
2441                 a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
2442                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2443                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2444                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2445
2446                 a->a_nvals = a->a_vals;
2447
2448                 a->a_next = glue->e_attrs;
2449                 glue->e_attrs = a;
2450
2451                 a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
2452
2453                 a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
2454                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2455                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2456
2457                 a->a_nvals = a->a_vals;
2458
2459                 a->a_next = glue->e_attrs;
2460                 glue->e_attrs = a;
2461
2462                 op->o_req_dn = glue->e_name;
2463                 op->o_req_ndn = glue->e_nname;
2464                 op->ora_e = glue;
2465                 rc = be->be_add ( op, &rs_add );
2466                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2467                         if ( op->ora_e == glue )
2468                                 be_entry_release_w( op, glue );
2469                 } else {
2470                 /* incl. ALREADY EXIST */
2471                         entry_free( glue );
2472                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
2473                                 entry_free( e );
2474                                 return rc;
2475                         }
2476                 }
2477
2478                 /* Move to next child */
2479                 comma = ber_bvrchr( &ptr, ',' );
2480                 if ( comma == NULL ) {
2481                         break;
2482                 }
2483                 ptr.bv_len = comma - ptr.bv_val;
2484                 
2485                 dn.bv_val = ++comma;
2486                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2487
2488                 comma = ber_bvrchr( &nptr, ',' );
2489                 assert( comma != NULL );
2490                 nptr.bv_len = comma - nptr.bv_val;
2491
2492                 ndn.bv_val = ++comma;
2493                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2494         }
2495
2496         op->o_req_dn = e->e_name;
2497         op->o_req_ndn = e->e_nname;
2498         op->ora_e = e;
2499         rc = be->be_add ( op, &rs_add );
2500         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2501                 if ( op->ora_e == e )
2502                         be_entry_release_w( op, e );
2503         } else {
2504                 entry_free( e );
2505         }
2506
2507         return rc;
2508 }
2509
2510 static int
2511 syncrepl_updateCookie(
2512         syncinfo_t *si,
2513         Operation *op,
2514         struct berval *pdn,
2515         struct sync_cookie *syncCookie )
2516 {
2517         Backend *be = op->o_bd;
2518         Modifications mod[2];
2519         struct berval first = BER_BVNULL;
2520
2521         int rc, i, j;
2522
2523         slap_callback cb = { NULL };
2524         SlapReply       rs_modify = {REP_RESULT};
2525
2526         mod[0].sml_op = LDAP_MOD_DELETE;
2527         mod[0].sml_desc = slap_schema.si_ad_contextCSN;
2528         mod[0].sml_type = mod[0].sml_desc->ad_cname;
2529         mod[0].sml_values = NULL;
2530         mod[0].sml_nvalues = NULL;
2531         mod[0].sml_next = &mod[1];
2532
2533         mod[1].sml_op = LDAP_MOD_ADD;
2534         mod[1].sml_desc = slap_schema.si_ad_contextCSN;
2535         mod[1].sml_type = mod[0].sml_desc->ad_cname;
2536         mod[1].sml_values = NULL;
2537         mod[1].sml_nvalues = NULL;
2538         mod[1].sml_next = NULL;
2539
2540         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
2541
2542         for ( i=0; i<syncCookie->numcsns; i++ ) {
2543                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
2544                         if ( syncCookie->sids[i] != si->si_cookieState->cs_sids[j] )
2545                                 continue;
2546                         if ( ber_bvcmp( &syncCookie->ctxcsn[i],
2547                                 &si->si_cookieState->cs_vals[j] ) > 0 ) {
2548                                 ber_bvarray_add_x( &mod[0].sml_values,
2549                                         &si->si_cookieState->cs_vals[j], op->o_tmpmemctx );
2550                                 ber_bvarray_add_x( &mod[1].sml_values,
2551                                         &syncCookie->ctxcsn[i], op->o_tmpmemctx );
2552                                 if ( BER_BVISNULL( &first ))
2553                                         first = syncCookie->ctxcsn[i];
2554                         }
2555                         break;
2556                 }
2557                 /* there was no match for this SID, it's a new CSN */
2558                 if ( j == si->si_cookieState->cs_num ) {
2559                         ber_bvarray_add_x( &mod[1].sml_values,
2560                                 &syncCookie->ctxcsn[i], op->o_tmpmemctx );
2561                         if ( BER_BVISNULL( &first ))
2562                                 first = syncCookie->ctxcsn[i];
2563                 }
2564         }
2565         op->o_bd = si->si_wbe;
2566         slap_queue_csn( op, &first );
2567
2568         op->o_tag = LDAP_REQ_MODIFY;
2569
2570         cb.sc_response = null_callback;
2571         cb.sc_private = si;
2572
2573         op->o_callback = &cb;
2574         op->o_req_dn = op->o_bd->be_suffix[0];
2575         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2576
2577         /* update contextCSN */
2578         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2579
2580         if ( mod[0].sml_values )
2581                 op->orm_modlist = mod;
2582         else
2583                 op->orm_modlist = &mod[1];
2584
2585         op->orm_no_opattrs = 1;
2586         rc = op->o_bd->be_modify( op, &rs_modify );
2587         op->o_msgid = 0;
2588
2589         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
2590                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
2591                 slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2592                 /* If we replaced any old values */
2593                 if ( mod[0].sml_values ) {
2594                         for ( i=0; !BER_BVISNULL( &mod[0].sml_values[i] ); i++ ) {
2595                                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
2596                                         if ( mod[0].sml_values[i].bv_val !=
2597                                                 si->si_cookieState->cs_vals[j].bv_val )
2598                                                 continue;
2599                                         ber_bvreplace( &si->si_cookieState->cs_vals[j],
2600                                                 &mod[1].sml_values[i] );
2601                                         break;
2602                                 }
2603                         }
2604                 } else {
2605                         /* Else we just added */
2606                         si->si_cookieState->cs_num += syncCookie->numcsns;
2607                         value_add( &si->si_cookieState->cs_vals, syncCookie->ctxcsn );
2608                         free( si->si_cookieState->cs_sids );
2609                         si->si_cookieState->cs_sids = slap_parse_csn_sids(
2610                                 si->si_cookieState->cs_vals, si->si_cookieState->cs_num );
2611                 }
2612
2613                 si->si_cookieState->cs_age++;
2614                 si->si_cookieAge = si->si_cookieState->cs_age;
2615         } else {
2616                 Debug( LDAP_DEBUG_ANY,
2617                         "syncrepl_updateCookie: %s be_modify failed (%d)\n",
2618                         si->si_ridtxt, rs_modify.sr_err, 0 );
2619         }
2620         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
2621
2622         slap_graduate_commit_csn( op );
2623         op->o_bd = be;
2624         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2625         BER_BVZERO( &op->o_csn );
2626         if ( mod[1].sml_next ) slap_mods_free( mod[1].sml_next, 1 );
2627         op->o_tmpfree( mod[1].sml_values, op->o_tmpmemctx );
2628         op->o_tmpfree( mod[0].sml_values, op->o_tmpmemctx );
2629
2630         return rc;
2631 }
2632
2633 static void
2634 attr_cmp( Operation *op, Attribute *old, Attribute *new,
2635         Modifications ***mret, Modifications ***mcur )
2636 {
2637         int i, j;
2638         Modifications *mod, **modtail;
2639
2640         modtail = *mret;
2641
2642         if ( old ) {
2643                 int n, o, d, a, *adds, *dels;
2644                 /* count old and new */
2645                 for ( o=0; old->a_vals[o].bv_val; o++ ) ;
2646                 for ( n=0; new->a_vals[n].bv_val; n++ ) ;
2647
2648                 adds = op->o_tmpalloc( sizeof(int) * n, op->o_tmpmemctx );
2649                 dels = op->o_tmpalloc( sizeof(int) * o, op->o_tmpmemctx );
2650                 d = 0;
2651                 a = 0;
2652                 i = 0;
2653                 j = 0;
2654
2655                 while ( i < o && j < n ) {
2656                         int k;
2657                         if ( bvmatch( &old->a_vals[i], &new->a_vals[j] ) ) {
2658                                 i++;
2659                                 j++;
2660                                 continue;
2661                         }
2662                         for ( k = j + 1; k<n; k++ ) {
2663                                 if ( bvmatch( &old->a_vals[i], &new->a_vals[k] ) ) {
2664                                         break;
2665                                 }
2666                         }
2667                         /* an old value was deleted */
2668                         if ( k == n ) {
2669                                 dels[d++] = i++;
2670                                 continue;
2671                         }
2672                         for ( k = i + 1; k < o; k++ ) {
2673                                 if ( bvmatch( &old->a_vals[k], &new->a_vals[j] ) ) {
2674                                         break;
2675                                 }
2676                         }
2677                         if ( k == o ) {
2678                                 adds[a++] = j++;
2679                         }
2680                 }
2681                 while ( i < o )
2682                         dels[d++] = i++;
2683                 while ( j < n )
2684                         adds[a++] = j++;
2685
2686                 /* all old values were deleted, just use the replace op */
2687                 if ( d == o ) {
2688                         i = j-1;
2689                 } else if ( d ) {
2690                 /* delete some values */
2691                         mod = ch_malloc( sizeof( Modifications ) );
2692                         mod->sml_op = LDAP_MOD_DELETE;
2693                         mod->sml_flags = 0;
2694                         mod->sml_desc = old->a_desc;
2695                         mod->sml_type = mod->sml_desc->ad_cname;
2696                         mod->sml_values = ch_malloc( ( d + 1 ) * sizeof(struct berval) );
2697                         if ( old->a_vals != old->a_nvals ) {
2698                                 mod->sml_nvalues = ch_malloc( ( d + 1 ) * sizeof(struct berval) );
2699                         } else {
2700                                 mod->sml_nvalues = NULL;
2701                         }
2702                         for ( i = 0; i < d; i++ ) {
2703                                 ber_dupbv( &mod->sml_values[i], &old->a_vals[dels[i]] );
2704                                 if ( mod->sml_nvalues ) {
2705                                         ber_dupbv( &mod->sml_nvalues[i], &old->a_nvals[dels[i]] );
2706                                 }
2707                         }
2708                         BER_BVZERO( &mod->sml_values[i] );
2709                         if ( mod->sml_nvalues ) {
2710                                 BER_BVZERO( &mod->sml_nvalues[i] );
2711                         }
2712                         *modtail = mod;
2713                         modtail = &mod->sml_next;
2714                         i = j;
2715                 }
2716                 op->o_tmpfree( dels, op->o_tmpmemctx );
2717                 /* some values were added */
2718                 if ( a && d < o ) {
2719                         mod = ch_malloc( sizeof( Modifications ) );
2720                         mod->sml_op = LDAP_MOD_ADD;
2721                         mod->sml_flags = 0;
2722                         mod->sml_desc = old->a_desc;
2723                         mod->sml_type = mod->sml_desc->ad_cname;
2724                         mod->sml_values = ch_malloc( ( a + 1 ) * sizeof(struct berval) );
2725                         if ( old->a_vals != old->a_nvals ) {
2726                                 mod->sml_nvalues = ch_malloc( ( a + 1 ) * sizeof(struct berval) );
2727                         } else {
2728                                 mod->sml_nvalues = NULL;
2729                         }
2730                         for ( i = 0; i < a; i++ ) {
2731                                 ber_dupbv( &mod->sml_values[i], &new->a_vals[adds[i]] );
2732                                 if ( mod->sml_nvalues ) {
2733                                         ber_dupbv( &mod->sml_nvalues[i], &new->a_nvals[adds[i]] );
2734                                 }
2735                         }
2736                         BER_BVZERO( &mod->sml_values[i] );
2737                         if ( mod->sml_nvalues ) {
2738                                 BER_BVZERO( &mod->sml_nvalues[i] );
2739                         }
2740                         *modtail = mod;
2741                         modtail = &mod->sml_next;
2742                         i = j;
2743                 }
2744                 op->o_tmpfree( adds, op->o_tmpmemctx );
2745         } else {
2746                 /* new attr, just use the new mod */
2747                 i = 0;
2748                 j = 1;
2749         }
2750         /* advance to next element */
2751         mod = **mcur;
2752         if ( mod ) {
2753                 if ( i != j ) {
2754                         **mcur = mod->sml_next;
2755                         *modtail = mod;
2756                         modtail = &mod->sml_next;
2757                 } else {
2758                         *mcur = &mod->sml_next;
2759                 }
2760         }
2761         *mret = modtail;
2762 }
2763
2764 static int
2765 dn_callback(
2766         Operation*      op,
2767         SlapReply*      rs )
2768 {
2769         dninfo *dni = op->o_callback->sc_private;
2770
2771         if ( rs->sr_type == REP_SEARCH ) {
2772                 if ( !BER_BVISNULL( &dni->dn ) ) {
2773                         Debug( LDAP_DEBUG_ANY,
2774                                 "dn_callback : consistency error - "
2775                                 "entryUUID is not unique\n", 0, 0, 0 );
2776                 } else {
2777                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2778                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2779                         /* If there is a new entry, see if it differs from the old.
2780                          * We compare the non-normalized values so that cosmetic changes
2781                          * in the provider are always propagated.
2782                          */
2783                         if ( dni->new_entry ) {
2784                                 Modifications **modtail, **ml;
2785                                 Attribute *old, *new;
2786                                 int i, is_ctx;
2787
2788                                 is_ctx = dn_match( &rs->sr_entry->e_nname,
2789                                         &op->o_bd->be_nsuffix[0] );
2790
2791                                 /* Did the DN change?
2792                                  */
2793                                 if ( !dn_match( &rs->sr_entry->e_name,
2794                                                 &dni->new_entry->e_name ) )
2795                                 {
2796                                         struct berval oldRDN, oldVal;
2797                                         AttributeDescription *ad = NULL;
2798                                         Attribute *a;
2799
2800                                         dni->renamed = 1;
2801                                         /* See if the oldRDN was deleted */
2802                                         dnRdn( &rs->sr_entry->e_nname, &oldRDN );
2803                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
2804                                         oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
2805                                                 oldRDN.bv_val );
2806                                         oldRDN.bv_len -= oldVal.bv_len + 2;
2807                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
2808                                         a = attr_find( dni->new_entry->e_attrs, ad );
2809                                         if ( !a || value_find_ex( ad,
2810                                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
2811                                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
2812                                                 SLAP_MR_VALUE_OF_SYNTAX, a->a_nvals,
2813                                                 &oldVal, op->o_tmpmemctx ) != LDAP_SUCCESS )
2814                                         {
2815                                                 dni->delOldRDN = 1;
2816                                         }
2817                                         /* OK, this was just a modDN, we're done */
2818                                         return LDAP_SUCCESS;
2819                                 }
2820
2821                                 modtail = &dni->mods;
2822                                 ml = dni->modlist;
2823
2824                                 /* Make sure new entry is actually newer than old entry */
2825                                 old = attr_find( rs->sr_entry->e_attrs,
2826                                         slap_schema.si_ad_entryCSN );
2827                                 new = attr_find( dni->new_entry->e_attrs,
2828                                         slap_schema.si_ad_entryCSN );
2829                                 if ( new && old && ber_bvcmp( &old->a_vals[0],
2830                                         &new->a_vals[0] ) >= 0 ) {
2831                                         Debug( LDAP_DEBUG_SYNC,
2832                                                 "dn_callback : new entry is older than ours "
2833                                                 "%s ours %s, new %s\n",
2834                                                 rs->sr_entry->e_name.bv_val,
2835                                                 old->a_vals[0].bv_val,
2836                                                 new->a_vals[0].bv_val );
2837                                         return LDAP_SUCCESS;
2838                                 }
2839
2840                                 /* We assume that attributes are saved in the same order
2841                                  * in the remote and local databases. So if we walk through
2842                                  * the attributeDescriptions one by one they should match in
2843                                  * lock step. If not, look for an add or delete.
2844                                  */
2845                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2846                                                 old && new; )
2847                                 {
2848                                         /* If we've seen this before, use its mod now */
2849                                         if ( new->a_flags & SLAP_ATTR_IXADD ) {
2850                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2851                                                 new = new->a_next;
2852                                                 continue;
2853                                         }
2854                                         /* Skip contextCSN */
2855                                         if ( is_ctx && old->a_desc ==
2856                                                 slap_schema.si_ad_contextCSN ) {
2857                                                 old = old->a_next;
2858                                                 continue;
2859                                         }
2860
2861                                         if ( old->a_desc != new->a_desc ) {
2862                                                 Modifications *mod;
2863                                                 Attribute *tmp;
2864
2865                                                 /* If it's just been re-added later,
2866                                                  * remember that we've seen it.
2867                                                  */
2868                                                 tmp = attr_find( new, old->a_desc );
2869                                                 if ( tmp ) {
2870                                                         tmp->a_flags |= SLAP_ATTR_IXADD;
2871                                                 } else {
2872                                                         /* If it's a new attribute, pull it in.
2873                                                          */
2874                                                         tmp = attr_find( old, new->a_desc );
2875                                                         if ( !tmp ) {
2876                                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2877                                                                 new = new->a_next;
2878                                                                 continue;
2879                                                         }
2880                                                         /* Delete old attr */
2881                                                         mod = ch_malloc( sizeof( Modifications ) );
2882                                                         mod->sml_op = LDAP_MOD_DELETE;
2883                                                         mod->sml_flags = 0;
2884                                                         mod->sml_desc = old->a_desc;
2885                                                         mod->sml_type = mod->sml_desc->ad_cname;
2886                                                         mod->sml_values = NULL;
2887                                                         mod->sml_nvalues = NULL;
2888                                                         *modtail = mod;
2889                                                         modtail = &mod->sml_next;
2890                                                 }
2891                                                 old = old->a_next;
2892                                                 continue;
2893                                         }
2894                                         /* kludge - always update modifiersName so that it
2895                                          * stays co-located with the other mod opattrs. But only
2896                                          * if we know there are other valid mods.
2897                                          */
2898                                         if ( old->a_desc == slap_schema.si_ad_modifiersName &&
2899                                                 dni->mods )
2900                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2901                                         else
2902                                                 attr_cmp( op, old, new, &modtail, &ml );
2903                                         new = new->a_next;
2904                                         old = old->a_next;
2905                                 }
2906                                 *modtail = *ml;
2907                                 *ml = NULL;
2908                         }
2909                 }
2910         } else if ( rs->sr_type == REP_RESULT ) {
2911                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2912                         Debug( LDAP_DEBUG_ANY,
2913                                 "dn_callback : consistency error - "
2914                                 "entryUUID is not unique\n", 0, 0, 0 );
2915                 }
2916         }
2917
2918         return LDAP_SUCCESS;
2919 }
2920
2921 static int
2922 nonpresent_callback(
2923         Operation*      op,
2924         SlapReply*      rs )
2925 {
2926         syncinfo_t *si = op->o_callback->sc_private;
2927         Attribute *a;
2928         int count = 0;
2929         struct berval* present_uuid = NULL;
2930         struct nonpresent_entry *np_entry;
2931
2932         if ( rs->sr_type == REP_RESULT ) {
2933                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2934                 si->si_presentlist = NULL;
2935
2936         } else if ( rs->sr_type == REP_SEARCH ) {
2937                 if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
2938                         char buf[sizeof("rid=000 not")];
2939
2940                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2941
2942                         if ( a ) {
2943                                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2944                                         syncuuid_cmp );
2945                         }
2946
2947                         if ( slap_debug & LDAP_DEBUG_SYNC ) {
2948                                 sprintf( buf, "%s %s", si->si_ridtxt,
2949                                         present_uuid ? "got" : "not" );
2950                         }
2951
2952                         Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %s UUID %s, dn %s\n",
2953                                 buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
2954
2955                         if ( a == NULL ) return 0;
2956                 }
2957
2958                 if ( present_uuid == NULL ) {
2959                         np_entry = (struct nonpresent_entry *)
2960                                 ch_calloc( 1, sizeof( struct nonpresent_entry ) );
2961                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2962                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2963                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2964
2965                 } else {
2966                         avl_delete( &si->si_presentlist,
2967                                         &a->a_nvals[0], syncuuid_cmp );
2968                         ch_free( present_uuid->bv_val );
2969                         ch_free( present_uuid );
2970                 }
2971         }
2972         return LDAP_SUCCESS;
2973 }
2974
2975 static int
2976 null_callback(
2977         Operation*      op,
2978         SlapReply*      rs )
2979 {
2980         if ( rs->sr_err != LDAP_SUCCESS &&
2981                 rs->sr_err != LDAP_REFERRAL &&
2982                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2983                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2984                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2985         {
2986                 Debug( LDAP_DEBUG_ANY,
2987                         "null_callback : error code 0x%x\n",
2988                         rs->sr_err, 0, 0 );
2989         }
2990         return LDAP_SUCCESS;
2991 }
2992
2993 static struct berval *
2994 slap_uuidstr_from_normalized(
2995         struct berval* uuidstr,
2996         struct berval* normalized,
2997         void *ctx )
2998 {
2999         struct berval *new;
3000         unsigned char nibble;
3001         int i, d = 0;
3002
3003         if ( normalized == NULL ) return NULL;
3004         if ( normalized->bv_len != 16 ) return NULL;
3005
3006         if ( uuidstr ) {
3007                 new = uuidstr;
3008         } else {
3009                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3010                 if ( new == NULL ) {
3011                         return NULL;
3012                 }
3013         }
3014
3015         new->bv_len = 36;
3016
3017         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3018                 if ( new != uuidstr ) {
3019                         slap_sl_free( new, ctx );
3020                 }
3021                 return NULL;
3022         }
3023
3024         for ( i = 0; i < 16; i++ ) {
3025                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
3026                         new->bv_val[(i<<1)+d] = '-';
3027                         d += 1;
3028                 }
3029
3030                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
3031                 if ( nibble < 10 ) {
3032                         new->bv_val[(i<<1)+d] = nibble + '0';
3033                 } else {
3034                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
3035                 }
3036
3037                 nibble = (normalized->bv_val[i]) & 0xF;
3038                 if ( nibble < 10 ) {
3039                         new->bv_val[(i<<1)+d+1] = nibble + '0';
3040                 } else {
3041                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
3042                 }
3043         }
3044
3045         new->bv_val[new->bv_len] = '\0';
3046         return new;
3047 }
3048
3049 static int
3050 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
3051 {
3052         const struct berval *uuid1 = v_uuid1;
3053         const struct berval *uuid2 = v_uuid2;
3054         int rc = uuid1->bv_len - uuid2->bv_len;
3055         if ( rc ) return rc;
3056         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
3057 }
3058
3059 static void
3060 avl_ber_bvfree( void *v_bv )
3061 {
3062         struct berval   *bv = (struct berval *)v_bv;
3063         
3064         if( v_bv == NULL ) return;
3065         if ( !BER_BVISNULL( bv ) ) {
3066                 ch_free( bv->bv_val );
3067         }
3068         ch_free( (char *) bv );
3069 }
3070
3071 void
3072 syncinfo_free( syncinfo_t *sie )
3073 {
3074         if ( sie->si_ld ) {
3075                 if ( sie->si_conn_setup ) {
3076                         ber_socket_t s;
3077                         ldap_get_option( sie->si_ld, LDAP_OPT_DESC, &s );
3078                         connection_client_stop( s );
3079                         sie->si_conn_setup = 0;
3080                 }
3081                 ldap_unbind_ext( sie->si_ld, NULL, NULL );
3082         }
3083
3084         /* re-fetch it, in case it was already removed */
3085         sie->si_re = ldap_pvt_runqueue_find( &slapd_rq, do_syncrepl, sie );
3086         if ( sie->si_re ) {
3087                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, sie->si_re ) )
3088                         ldap_pvt_runqueue_stoptask( &slapd_rq, sie->si_re );
3089                 ldap_pvt_runqueue_remove( &slapd_rq, sie->si_re );
3090         }
3091
3092         ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
3093
3094         bindconf_free( &sie->si_bindconf );
3095
3096         if ( sie->si_filterstr.bv_val ) {
3097                 ch_free( sie->si_filterstr.bv_val );
3098         }
3099         if ( sie->si_logfilterstr.bv_val ) {
3100                 ch_free( sie->si_logfilterstr.bv_val );
3101         }
3102         if ( sie->si_base.bv_val ) {
3103                 ch_free( sie->si_base.bv_val );
3104         }
3105         if ( sie->si_logbase.bv_val ) {
3106                 ch_free( sie->si_logbase.bv_val );
3107         }
3108         if ( sie->si_attrs ) {
3109                 int i = 0;
3110                 while ( sie->si_attrs[i] != NULL ) {
3111                         ch_free( sie->si_attrs[i] );
3112                         i++;
3113                 }
3114                 ch_free( sie->si_attrs );
3115         }
3116         if ( sie->si_exattrs ) {
3117                 int i = 0;
3118                 while ( sie->si_exattrs[i] != NULL ) {
3119                         ch_free( sie->si_exattrs[i] );
3120                         i++;
3121                 }
3122                 ch_free( sie->si_exattrs );
3123         }
3124         if ( sie->si_anlist ) {
3125                 int i = 0;
3126                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
3127                         ch_free( sie->si_anlist[i].an_name.bv_val );
3128                         i++;
3129                 }
3130                 ch_free( sie->si_anlist );
3131         }
3132         if ( sie->si_exanlist ) {
3133                 int i = 0;
3134                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
3135                         ch_free( sie->si_exanlist[i].an_name.bv_val );
3136                         i++;
3137                 }
3138                 ch_free( sie->si_exanlist );
3139         }
3140         if ( sie->si_retryinterval ) {
3141                 ch_free( sie->si_retryinterval );
3142         }
3143         if ( sie->si_retrynum ) {
3144                 ch_free( sie->si_retrynum );
3145         }
3146         if ( sie->si_retrynum_init ) {
3147                 ch_free( sie->si_retrynum_init );
3148         }
3149         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
3150         if ( sie->si_presentlist ) {
3151             avl_free( sie->si_presentlist, avl_ber_bvfree );
3152         }
3153         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
3154                 struct nonpresent_entry* npe;
3155                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
3156                 LDAP_LIST_REMOVE( npe, npe_link );
3157                 if ( npe->npe_name ) {
3158                         if ( npe->npe_name->bv_val ) {
3159                                 ch_free( npe->npe_name->bv_val );
3160                         }
3161                         ch_free( npe->npe_name );
3162                 }
3163                 if ( npe->npe_nname ) {
3164                         if ( npe->npe_nname->bv_val ) {
3165                                 ch_free( npe->npe_nname->bv_val );
3166                         }
3167                         ch_free( npe->npe_nname );
3168                 }
3169                 ch_free( npe );
3170         }
3171         ch_free( sie );
3172 }
3173
3174
3175
3176 /* NOTE: used & documented in slapd.conf(5) */
3177 #define IDSTR                   "rid"
3178 #define PROVIDERSTR             "provider"
3179 #define SCHEMASTR               "schemachecking"
3180 #define FILTERSTR               "filter"
3181 #define SEARCHBASESTR           "searchbase"
3182 #define SCOPESTR                "scope"
3183 #define ATTRSONLYSTR            "attrsonly"
3184 #define ATTRSSTR                "attrs"
3185 #define TYPESTR                 "type"
3186 #define INTERVALSTR             "interval"
3187 #define RETRYSTR                "retry"
3188 #define SLIMITSTR               "sizelimit"
3189 #define TLIMITSTR               "timelimit"
3190 #define SYNCDATASTR             "syncdata"
3191 #define LOGBASESTR              "logbase"
3192 #define LOGFILTERSTR    "logfilter"
3193
3194 /* FIXME: undocumented */
3195 #define EXATTRSSTR              "exattrs"
3196 #define MANAGEDSAITSTR          "manageDSAit"
3197
3198 /* mandatory */
3199 #define GOT_ID                  0x0001
3200 #define GOT_PROVIDER    0x0002
3201 #define GOT_BASE                0x0004
3202
3203 /* check */
3204 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER|GOT_BASE)
3205
3206 static struct {
3207         struct berval key;
3208         int val;
3209 } scopes[] = {
3210         { BER_BVC("base"), LDAP_SCOPE_BASE },
3211         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
3212         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
3213         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
3214         { BER_BVC("subord"), LDAP_SCOPE_SUBORDINATE },
3215         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
3216         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
3217         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
3218         { BER_BVNULL, 0 }
3219 };
3220
3221 static slap_verbmasks datamodes[] = {
3222         { BER_BVC("default"), SYNCDATA_DEFAULT },
3223         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
3224         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
3225         { BER_BVNULL, 0 }
3226 };
3227
3228 static int
3229 parse_syncrepl_line(
3230         ConfigArgs      *c,
3231         syncinfo_t      *si )
3232 {
3233         int     gots = 0;
3234         int     i;
3235         char    *val;
3236
3237         for ( i = 1; i < c->argc; i++ ) {
3238                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
3239                                         STRLENOF( IDSTR "=" ) ) )
3240                 {
3241                         int tmp;
3242                         /* '\0' string terminator accounts for '=' */
3243                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
3244                         if ( lutil_atoi( &tmp, val ) != 0 ) {
3245                                 snprintf( c->msg, sizeof( c->msg ),
3246                                         "Error: parse_syncrepl_line: "
3247                                         "unable to parse syncrepl id \"%s\"", val );
3248                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3249                                 return -1;
3250                         }
3251                         if ( tmp >= 1000 || tmp < 0 ) {
3252                                 snprintf( c->msg, sizeof( c->msg ),
3253                                         "Error: parse_syncrepl_line: "
3254                                         "syncrepl id %d is out of range [0..999]", tmp );
3255                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3256                                 return -1;
3257                         }
3258                         si->si_rid = tmp;
3259                         sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
3260                         gots |= GOT_ID;
3261                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
3262                                         STRLENOF( PROVIDERSTR "=" ) ) )
3263                 {
3264                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
3265                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
3266                         gots |= GOT_PROVIDER;
3267                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
3268                                         STRLENOF( SCHEMASTR "=" ) ) )
3269                 {
3270                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
3271                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
3272                                 si->si_schemachecking = 1;
3273                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
3274                                 si->si_schemachecking = 0;
3275                         } else {
3276                                 si->si_schemachecking = 1;
3277                         }
3278                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
3279                                         STRLENOF( FILTERSTR "=" ) ) )
3280                 {
3281                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
3282                         if ( si->si_filterstr.bv_val )
3283                                 ch_free( si->si_filterstr.bv_val );
3284                         ber_str2bv( val, 0, 1, &si->si_filterstr );
3285                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
3286                                         STRLENOF( LOGFILTERSTR "=" ) ) )
3287                 {
3288                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
3289                         if ( si->si_logfilterstr.bv_val )
3290                                 ch_free( si->si_logfilterstr.bv_val );
3291                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
3292                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
3293                                         STRLENOF( SEARCHBASESTR "=" ) ) )
3294                 {
3295                         struct berval   bv;
3296                         int             rc;
3297
3298                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
3299                         if ( si->si_base.bv_val ) {
3300                                 ch_free( si->si_base.bv_val );
3301                         }
3302                         ber_str2bv( val, 0, 0, &bv );
3303                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
3304                         if ( rc != LDAP_SUCCESS ) {
3305                                 snprintf( c->msg, sizeof( c->msg ),
3306                                         "Invalid base DN \"%s\": %d (%s)",
3307                                         val, rc, ldap_err2string( rc ) );
3308                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3309                                 return -1;
3310                         }
3311                         gots |= GOT_BASE;
3312                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
3313                                         STRLENOF( LOGBASESTR "=" ) ) )
3314                 {
3315                         struct berval   bv;
3316                         int             rc;
3317
3318                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
3319                         if ( si->si_logbase.bv_val ) {
3320                                 ch_free( si->si_logbase.bv_val );
3321                         }
3322                         ber_str2bv( val, 0, 0, &bv );
3323                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
3324                         if ( rc != LDAP_SUCCESS ) {
3325                                 snprintf( c->msg, sizeof( c->msg ),
3326                                         "Invalid logbase DN \"%s\": %d (%s)",
3327                                         val, rc, ldap_err2string( rc ) );
3328                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3329                                 return -1;
3330                         }
3331                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
3332                                         STRLENOF( SCOPESTR "=" ) ) )
3333                 {
3334                         int j;
3335                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
3336                         for ( j = 0; !BER_BVISNULL(&scopes[j].key); j++ ) {
3337                                 if (!strcasecmp( val, scopes[j].key.bv_val ) ) {
3338                                         si->si_scope = scopes[j].val;
3339                                         break;
3340                                 }
3341                         }
3342                         if ( BER_BVISNULL(&scopes[j].key) ) {
3343                                 snprintf( c->msg, sizeof( c->msg ),
3344                                         "Error: parse_syncrepl_line: "
3345                                         "unknown scope \"%s\"", val);
3346                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3347                                 return -1;
3348                         }
3349                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
3350                                         STRLENOF( ATTRSONLYSTR ) ) )
3351                 {
3352                         si->si_attrsonly = 1;
3353                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
3354                                         STRLENOF( ATTRSSTR "=" ) ) )
3355                 {
3356                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
3357                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
3358                                 char *attr_fname;
3359                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
3360                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
3361                                 if ( si->si_anlist == NULL ) {
3362                                         ch_free( attr_fname );
3363                                         return -1;
3364                                 }
3365                                 si->si_anfile = attr_fname;
3366                         } else {
3367                                 char *str, *s, *next;
3368                                 char delimstr[] = " ,\t";
3369                                 str = ch_strdup( val );
3370                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
3371                                                 s != NULL;
3372                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
3373                                 {
3374                                         if ( strlen(s) == 1 && *s == '*' ) {
3375                                                 si->si_allattrs = 1;
3376                                                 val[ s - str ] = delimstr[0];
3377                                         }
3378                                         if ( strlen(s) == 1 && *s == '+' ) {
3379                                                 si->si_allopattrs = 1;
3380                                                 val [ s - str ] = delimstr[0];
3381                                         }
3382                                 }
3383                                 ch_free( str );
3384                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
3385                                 if ( si->si_anlist == NULL ) {
3386                                         return -1;
3387                                 }
3388                         }
3389                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
3390                                         STRLENOF( EXATTRSSTR "=" ) ) )
3391                 {
3392                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
3393                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
3394                                 char *attr_fname;
3395                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
3396                                 si->si_exanlist = file2anlist(
3397                                         si->si_exanlist, attr_fname, " ,\t" );
3398                                 if ( si->si_exanlist == NULL ) {
3399                                         ch_free( attr_fname );
3400                                         return -1;
3401                                 }
3402                                 ch_free( attr_fname );
3403                         } else {
3404                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
3405                                 if ( si->si_exanlist == NULL ) {
3406                                         return -1;
3407                                 }
3408                         }
3409                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
3410                                         STRLENOF( TYPESTR "=" ) ) )
3411                 {
3412                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
3413                         if ( !strncasecmp( val, "refreshOnly",
3414                                                 STRLENOF("refreshOnly") ) )
3415                         {
3416                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3417                         } else if ( !strncasecmp( val, "refreshAndPersist",
3418                                                 STRLENOF("refreshAndPersist") ) )
3419                         {
3420                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
3421                                 si->si_interval = 60;
3422                         } else {
3423                                 snprintf( c->msg, sizeof( c->msg ),
3424                                         "Error: parse_syncrepl_line: "
3425                                         "unknown sync type \"%s\"", val);
3426                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3427                                 return -1;
3428                         }
3429                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
3430                                         STRLENOF( INTERVALSTR "=" ) ) )
3431                 {
3432                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
3433                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
3434                                 si->si_interval = 0;
3435                         } else if ( strchr( val, ':' ) != NULL ) {
3436                                 char *next, *ptr = val;
3437                                 unsigned dd, hh, mm, ss;
3438
3439                                 /* NOTE: the test for ptr[ 0 ] == '-'
3440                                  * should go before the call to strtoul() */
3441                                 dd = strtoul( ptr, &next, 10 );
3442                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' ) {
3443                                         snprintf( c->msg, sizeof( c->msg ),
3444                                                 "Error: parse_syncrepl_line: "
3445                                                 "invalid interval \"%s\", unable to parse days", val );
3446                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3447                                         return -1;
3448                                 }
3449                                 ptr = next + 1;
3450                                 hh = strtoul( ptr, &next, 10 );
3451                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || hh > 24 ) {
3452                                         snprintf( c->msg, sizeof( c->msg ),
3453                                                 "Error: parse_syncrepl_line: "
3454                                                 "invalid interval \"%s\", unable to parse hours", val );
3455                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3456                                         return -1;
3457                                 }
3458                                 ptr = next + 1;
3459                                 mm = strtoul( ptr, &next, 10 );
3460                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || mm > 60 ) {
3461                                         snprintf( c->msg, sizeof( c->msg ),
3462                                                 "Error: parse_syncrepl_line: "
3463                                                 "invalid interval \"%s\", unable to parse minutes", val );
3464                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3465                                         return -1;
3466                                 }
3467                                 ptr = next + 1;
3468                                 ss = strtoul( ptr, &next, 10 );
3469                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != '\0' || ss > 60 ) {
3470                                         snprintf( c->msg, sizeof( c->msg ),
3471                                                 "Error: parse_syncrepl_line: "
3472                                                 "invalid interval \"%s\", unable to parse seconds", val );
3473                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3474                                         return -1;
3475                                 }
3476                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
3477                         } else {
3478                                 unsigned long   t;
3479
3480                                 if ( lutil_parse_time( val, &t ) != 0 ) {
3481                                         snprintf( c->msg, sizeof( c->msg ),
3482                                                 "Error: parse_syncrepl_line: "
3483                                                 "invalid interval \"%s\"", val );
3484                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3485                                         return -1;
3486                                 }
3487                                 si->si_interval = (time_t)t;
3488                         }
3489                         if ( si->si_interval < 0 ) {
3490                                 snprintf( c->msg, sizeof( c->msg ),
3491                                         "Error: parse_syncrepl_line: "
3492                                         "invalid interval \"%ld\"",
3493                                         (long) si->si_interval);
3494                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3495                                 return -1;
3496                         }
3497                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
3498                                         STRLENOF( RETRYSTR "=" ) ) )
3499                 {
3500                         char **retry_list;
3501                         int j, k, n;
3502
3503                         val = c->argv[ i ] + STRLENOF( RETRYSTR "=" );
3504                         retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
3505                         retry_list[0] = NULL;
3506
3507                         slap_str2clist( &retry_list, val, " ,\t" );
3508
3509                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3510                         n = k / 2;
3511                         if ( k % 2 ) {
3512                                 snprintf( c->msg, sizeof( c->msg ),
3513                                         "Error: incomplete syncrepl retry list" );
3514                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3515                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3516                                         ch_free( retry_list[k] );
3517                                 }
3518                                 ch_free( retry_list );
3519                                 return 1;
3520                         }
3521                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
3522                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
3523                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
3524                         for ( j = 0; j < n; j++ ) {
3525                                 unsigned long   t;
3526                                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3527                                         snprintf( c->msg, sizeof( c->msg ),
3528                                                 "Error: invalid retry interval \"%s\" (#%d)",
3529                                                 retry_list[j*2], j );
3530                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3531                                         /* do some cleanup */
3532                                         return 1;
3533                                 }
3534                                 si->si_retryinterval[j] = (time_t)t;
3535                                 if ( *retry_list[j*2+1] == '+' ) {
3536                                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3537                                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3538                                         j++;
3539                                         break;
3540                                 } else {
3541                                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3542                                                         || si->si_retrynum_init[j] <= 0 )
3543                                         {
3544                                                 snprintf( c->msg, sizeof( c->msg ),
3545                                                         "Error: invalid initial retry number \"%s\" (#%d)",
3546                                                         retry_list[j*2+1], j );
3547                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3548                                                 /* do some cleanup */
3549                                                 return 1;
3550                                         }
3551                                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3552                                                         || si->si_retrynum[j] <= 0 )
3553                                         {
3554                                                 snprintf( c->msg, sizeof( c->msg ),
3555                                                         "Error: invalid retry number \"%s\" (#%d)",
3556                                                         retry_list[j*2+1], j );
3557                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3558                                                 /* do some cleanup */
3559                                                 return 1;
3560                                         }
3561                                 }
3562                         }
3563                         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3564                         si->si_retrynum[j] = RETRYNUM_TAIL;
3565                         si->si_retryinterval[j] = 0;
3566                         
3567                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3568                                 ch_free( retry_list[k] );
3569                         }
3570                         ch_free( retry_list );
3571                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
3572                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
3573                 {
3574                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
3575                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
3576                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
3577                         {
3578                                 snprintf( c->msg, sizeof( c->msg ),
3579                                         "invalid manageDSAit value \"%s\".\n",
3580                                         val );
3581                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3582                                 return 1;
3583                         }
3584                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
3585                                         STRLENOF( SLIMITSTR "=") ) )
3586                 {
3587                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
3588                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3589                                 si->si_slimit = 0;
3590
3591                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
3592                                 snprintf( c->msg, sizeof( c->msg ),
3593                                         "invalid size limit value \"%s\".\n",
3594                                         val );
3595                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3596                                 return 1;
3597                         }
3598                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
3599                                         STRLENOF( TLIMITSTR "=" ) ) )
3600                 {
3601                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
3602                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3603                                 si->si_tlimit = 0;
3604
3605                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
3606                                 snprintf( c->msg, sizeof( c->msg ),
3607                                         "invalid time limit value \"%s\".\n",
3608                                         val );
3609                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3610                                 return 1;
3611                         }
3612                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
3613                                         STRLENOF( SYNCDATASTR "=" ) ) )
3614                 {
3615                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
3616                         si->si_syncdata = verb_to_mask( val, datamodes );
3617                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
3618                         snprintf( c->msg, sizeof( c->msg ),
3619                                 "Error: parse_syncrepl_line: "
3620                                 "unable to parse \"%s\"\n", c->argv[ i ] );
3621                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3622                         return -1;
3623                 }
3624         }
3625
3626         if ( gots != GOT_ALL ) {
3627                 snprintf( c->msg, sizeof( c->msg ),
3628                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
3629                         gots & GOT_ID ? "" : " "IDSTR,
3630                         gots & GOT_PROVIDER ? "" : " "PROVIDERSTR,
3631                         gots & GOT_BASE ? "" : " "SEARCHBASESTR );
3632                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3633                 return -1;
3634         }
3635
3636         return 0;
3637 }
3638
3639 static int
3640 add_syncrepl(
3641         ConfigArgs *c )
3642 {
3643         syncinfo_t *si;
3644         int     rc = 0;
3645
3646         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
3647                 snprintf( c->msg, sizeof(c->msg), "database %s does not support "
3648                         "operations required for syncrepl", c->be->be_type );
3649                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3650                 return 1;
3651         }
3652         if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
3653                 strcpy( c->msg, "rootDN must be defined before syncrepl may be used" );
3654                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3655                 return 1;
3656         }
3657         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
3658
3659         if ( si == NULL ) {
3660                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
3661                 return 1;
3662         }
3663
3664         si->si_bindconf.sb_tls = SB_TLS_OFF;
3665         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
3666         si->si_schemachecking = 0;
3667         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
3668                 &si->si_filterstr );
3669         si->si_base.bv_val = NULL;
3670         si->si_scope = LDAP_SCOPE_SUBTREE;
3671         si->si_attrsonly = 0;
3672         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
3673         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
3674         si->si_attrs = NULL;
3675         si->si_allattrs = 0;
3676         si->si_allopattrs = 0;
3677         si->si_exattrs = NULL;
3678         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3679         si->si_interval = 86400;
3680         si->si_retryinterval = NULL;
3681         si->si_retrynum_init = NULL;
3682         si->si_retrynum = NULL;
3683         si->si_manageDSAit = 0;
3684         si->si_tlimit = 0;
3685         si->si_slimit = 0;
3686         si->si_conn_setup = 0;
3687
3688         si->si_presentlist = NULL;
3689         LDAP_LIST_INIT( &si->si_nonpresentlist );
3690         ldap_pvt_thread_mutex_init( &si->si_mutex );
3691
3692         rc = parse_syncrepl_line( c, si );
3693
3694         if ( rc == 0 ) {
3695                 /* Must be LDAPv3 because we need controls */
3696                 switch ( si->si_bindconf.sb_version ) {
3697                 case 0:
3698                         /* not explicitly set */
3699                         si->si_bindconf.sb_version = LDAP_VERSION3;
3700                         break;
3701                 case 3:
3702                         /* explicitly set */
3703                         break;
3704                 default:
3705                         Debug( LDAP_DEBUG_ANY,
3706                                 "version %d incompatible with syncrepl\n",
3707                                 si->si_bindconf.sb_version, 0, 0 );
3708                         syncinfo_free( si );    
3709                         return 1;
3710                 }
3711
3712                 si->si_be = c->be;
3713                 if ( slapMode & SLAP_SERVER_MODE ) {
3714                         Listener **l = slapd_get_listeners();
3715                         int isMe = 0;
3716
3717                         /* check if URL points to current server. If so, ignore
3718                          * this configuration. We require an exact match. Just
3719                          * in case they really want to do this, they can vary
3720                          * the case of the URL to allow it.
3721                          */
3722                         if ( l && !SLAP_DBHIDDEN( c->be ) ) {
3723                                 int i;
3724                                 for ( i=0; l[i]; i++ ) {
3725                                         if ( bvmatch( &l[i]->sl_url, &si->si_bindconf.sb_uri ) ) {
3726                                                 isMe = 1;
3727                                                 break;
3728                                         }
3729                                 }
3730                         }
3731
3732                         if ( !isMe ) {
3733                                 init_syncrepl( si );
3734                                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
3735                                         si->si_interval, do_syncrepl, si, "do_syncrepl",
3736                                         si->si_ridtxt );
3737                                 if ( si->si_re )
3738                                         rc = config_sync_shadow( c ) ? -1 : 0;
3739                                 else
3740                                         rc = -1;
3741                         }
3742                 }
3743         }
3744
3745 #ifdef HAVE_TLS
3746         /* Use main slapd defaults */
3747         bindconf_tls_defaults( &si->si_bindconf );
3748 #endif
3749         if ( rc < 0 ) {
3750                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
3751                 syncinfo_free( si );    
3752                 return 1;
3753         } else {
3754                 Debug( LDAP_DEBUG_CONFIG,
3755                         "Config: ** successfully added syncrepl \"%s\"\n",
3756                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
3757                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
3758                 if ( !si->si_schemachecking ) {
3759                         SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3760                 }
3761                 if ( c->be->be_syncinfo ) {
3762                         si->si_cookieState = c->be->be_syncinfo->si_cookieState;
3763                 } else {
3764                         si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
3765                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
3766                 }
3767                 si->si_next = c->be->be_syncinfo;
3768                 c->be->be_syncinfo = si;
3769                 return 0;
3770         }
3771 }
3772
3773 static void
3774 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
3775 {
3776         struct berval bc, uri;
3777         char buf[BUFSIZ*2], *ptr;
3778         int i;
3779
3780 #define WHATSLEFT       ( sizeof( buf ) - ( ptr - buf ) )
3781
3782         BER_BVZERO( bv );
3783
3784         /* temporarily inhibit bindconf from printing URI */
3785         uri = si->si_bindconf.sb_uri;
3786         BER_BVZERO( &si->si_bindconf.sb_uri );
3787         si->si_bindconf.sb_version = 0;
3788         bindconf_unparse( &si->si_bindconf, &bc );
3789         si->si_bindconf.sb_uri = uri;
3790         si->si_bindconf.sb_version = LDAP_VERSION3;
3791
3792         ptr = buf;
3793         ptr += snprintf( ptr, WHATSLEFT, IDSTR "=%03ld " PROVIDERSTR "=%s",
3794                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
3795         if ( ptr - buf >= sizeof( buf ) ) return;
3796         if ( !BER_BVISNULL( &bc ) ) {
3797                 if ( WHATSLEFT <= bc.bv_len ) {
3798                         free( bc.bv_val );
3799                         return;
3800                 }
3801                 ptr = lutil_strcopy( ptr, bc.bv_val );
3802                 free( bc.bv_val );
3803         }
3804         if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
3805                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
3806                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
3807                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
3808                 *ptr++ = '"';
3809         }
3810         if ( !BER_BVISNULL( &si->si_base ) ) {
3811                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
3812                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
3813                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
3814                 *ptr++ = '"';
3815         }
3816         if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
3817                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
3818                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
3819                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
3820                 *ptr++ = '"';
3821         }
3822         if ( !BER_BVISNULL( &si->si_logbase ) ) {
3823                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
3824                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
3825                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
3826                 *ptr++ = '"';
3827         }
3828         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
3829                 if ( si->si_scope == scopes[i].val ) {
3830                         if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + scopes[i].key.bv_len ) return;
3831                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
3832                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
3833                         break;
3834                 }
3835         }
3836         if ( si->si_attrsonly ) {
3837                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3838                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
3839         }
3840         if ( si->si_anfile ) {
3841                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
3842                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
3843                 ptr = lutil_strcopy( ptr, si->si_anfile );
3844                 *ptr++ = '"';
3845         } else if ( si->si_allattrs || si->si_allopattrs ||
3846                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
3847         {
3848                 char *old;
3849
3850                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3851                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
3852                 old = ptr;
3853                 /* FIXME: add check for overflow */
3854                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
3855                 if ( si->si_allattrs ) {
3856                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
3857                         if ( old != ptr ) *ptr++ = ',';
3858                         *ptr++ = '*';
3859                 }
3860                 if ( si->si_allopattrs ) {
3861                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
3862                         if ( old != ptr ) *ptr++ = ',';
3863                         *ptr++ = '+';
3864                 }
3865                 *ptr++ = '"';
3866         }
3867         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3868                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
3869                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3870                 /* FIXME: add check for overflow */
3871                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
3872         }
3873         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
3874         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3875         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3876         
3877         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
3878         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3879         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3880                 "refreshAndPersist" : "refreshOnly" );
3881
3882         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
3883                 int dd, hh, mm, ss;
3884
3885                 dd = si->si_interval;
3886                 ss = dd % 60;
3887                 dd /= 60;
3888                 mm = dd % 60;
3889                 dd /= 60;
3890                 hh = dd % 24;
3891                 dd /= 24;
3892                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
3893                 ptr += snprintf( ptr, WHATSLEFT, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
3894                 if ( ptr - buf >= sizeof( buf ) ) return;
3895         } else if ( si->si_retryinterval ) {
3896                 int space=0;
3897                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
3898                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
3899                 for (i=0; si->si_retryinterval[i]; i++) {
3900                         if ( space ) *ptr++ = ' ';
3901                         space = 1;
3902                         ptr += snprintf( ptr, WHATSLEFT, "%ld ", (long) si->si_retryinterval[i] );
3903                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
3904                                 *ptr++ = '+';
3905                         else
3906                                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
3907                 }
3908                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
3909                 *ptr++ = '"';
3910         }
3911
3912         if ( si->si_slimit ) {
3913                 if ( WHATSLEFT <= STRLENOF( " " SLIMITSTR "=" ) ) return;
3914                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
3915                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_slimit );
3916         }
3917
3918         if ( si->si_tlimit ) {
3919                 if ( WHATSLEFT <= STRLENOF( " " TLIMITSTR "=" ) ) return;
3920                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
3921                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_tlimit );
3922         }
3923
3924         if ( si->si_syncdata ) {
3925                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
3926                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
3927                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
3928                         ptr = lutil_strcopy( ptr, bc.bv_val );
3929                 }
3930         }
3931         bc.bv_len = ptr - buf;
3932         bc.bv_val = buf;
3933         ber_dupbv( bv, &bc );
3934 }
3935
3936 int
3937 syncrepl_config( ConfigArgs *c )
3938 {
3939         if (c->op == SLAP_CONFIG_EMIT) {
3940                 if ( c->be->be_syncinfo ) {
3941                         struct berval bv;
3942                         syncinfo_t *si;
3943
3944                         for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
3945                                 syncrepl_unparse( si, &bv ); 
3946                                 ber_bvarray_add( &c->rvalue_vals, &bv );
3947                         }
3948                         return 0;
3949                 }
3950                 return 1;
3951         } else if ( c->op == LDAP_MOD_DELETE ) {
3952                 cookie_state *cs = NULL;
3953                 if ( c->be->be_syncinfo ) {
3954                         syncinfo_t *si, **sip;
3955                         int i;
3956
3957                         cs = c->be->be_syncinfo->si_cookieState;
3958                         for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
3959                                 si = *sip;
3960                                 if ( c->valx == -1 || i == c->valx ) {
3961                                         *sip = si->si_next;
3962                                         /* If the task is currently active, we have to leave
3963                                          * it running. It will exit on its own. This will only
3964                                          * happen when running on the cn=config DB.
3965                                          */
3966                                         if ( si->si_re &&
3967                                                 ldap_pvt_runqueue_isrunning( &slapd_rq, si->si_re ) ) {
3968                                                 si->si_ctype = 0;
3969                                         } else {
3970                                                 syncinfo_free( si );
3971                                         }
3972                                         if ( i == c->valx )
3973                                                 break;
3974                                 } else {
3975                                         sip = &si->si_next;
3976                                 }
3977                         }
3978                 }
3979                 if ( !c->be->be_syncinfo ) {
3980                         SLAP_DBFLAGS( c->be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
3981                         if ( cs ) {
3982                                 ber_bvarray_free( cs->cs_vals );
3983                                 ldap_pvt_thread_mutex_destroy( &cs->cs_mutex );
3984                                 ch_free( cs );
3985                         }
3986                 }
3987                 return 0;
3988         }
3989         if ( SLAP_SLURP_SHADOW( c->be ) ) {
3990                 Debug(LDAP_DEBUG_ANY, "%s: "
3991                         "syncrepl: database already shadowed.\n",
3992                         c->log, 0, 0);
3993                 return(1);
3994         } else {
3995                 return add_syncrepl( c );
3996         }
3997 }