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