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