]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
coverity scan, ch_realloc won't return NULL
[openldap] / servers / slapd / syncrepl.c
1 /* syncrepl.c -- Replication Engine which uses the LDAP Sync protocol */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2003-2007 The OpenLDAP Foundation.
6  * Portions Copyright 2003 by IBM Corporation.
7  * Portions Copyright 2003 by Howard Chu, Symas Corporation.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in the file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18
19 #include "portable.h"
20
21 #include <stdio.h>
22
23 #include <ac/string.h>
24 #include <ac/socket.h>
25
26 #include "lutil.h"
27 #include "slap.h"
28 #include "lutil_ldap.h"
29
30 #include "config.h"
31
32 #include "ldap_rq.h"
33
34 struct nonpresent_entry {
35         struct berval *npe_name;
36         struct berval *npe_nname;
37         LDAP_LIST_ENTRY(nonpresent_entry) npe_link;
38 };
39
40 typedef struct cookie_state {
41         ldap_pvt_thread_mutex_t cs_mutex;
42         int     cs_num;
43         int cs_age;
44         struct berval *cs_vals;
45         int *cs_sids;
46 } cookie_state;
47         
48 #define SYNCDATA_DEFAULT        0       /* entries are plain LDAP entries */
49 #define SYNCDATA_ACCESSLOG      1       /* entries are accesslog format */
50 #define SYNCDATA_CHANGELOG      2       /* entries are changelog format */
51
52 #define SYNCLOG_LOGGING         0       /* doing a log-based update */
53 #define SYNCLOG_FALLBACK        1       /* doing a full refresh */
54
55 #define RETRYNUM_FOREVER        (-1)    /* retry forever */
56 #define RETRYNUM_TAIL           (-2)    /* end of retrynum array */
57 #define RETRYNUM_VALID(n)       ((n) >= RETRYNUM_FOREVER)       /* valid retrynum */
58 #define RETRYNUM_FINITE(n)      ((n) > RETRYNUM_FOREVER)        /* not forever */
59
60 typedef struct syncinfo_s {
61         struct syncinfo_s       *si_next;
62         BackendDB               *si_be;
63         BackendDB               *si_wbe;
64         struct re_s             *si_re;
65         int                     si_rid;
66         char                    si_ridtxt[8];
67         slap_bindconf           si_bindconf;
68         struct berval           si_base;
69         struct berval           si_logbase;
70         struct berval           si_filterstr;
71         struct berval           si_logfilterstr;
72         int                     si_scope;
73         int                     si_attrsonly;
74         char                    *si_anfile;
75         AttributeName           *si_anlist;
76         AttributeName           *si_exanlist;
77         char                    **si_attrs;
78         char                    **si_exattrs;
79         int                     si_allattrs;
80         int                     si_allopattrs;
81         int                     si_schemachecking;
82         int                     si_type;        /* the active type */
83         int                     si_ctype;       /* the configured type */
84         time_t                  si_interval;
85         time_t                  *si_retryinterval;
86         int                     *si_retrynum_init;
87         int                     *si_retrynum;
88         struct sync_cookie      si_syncCookie;
89         cookie_state            *si_cookieState;
90         int                     si_cookieAge;
91         int                     si_manageDSAit;
92         int                     si_slimit;
93         int                     si_tlimit;
94         int                     si_refreshDelete;
95         int                     si_refreshPresent;
96         int                     si_syncdata;
97         int                     si_logstate;
98         int                     si_conn_setup;
99         Avlnode                 *si_presentlist;
100         LDAP                    *si_ld;
101         LDAP_LIST_HEAD(np, nonpresent_entry)    si_nonpresentlist;
102         ldap_pvt_thread_mutex_t si_mutex;
103 } syncinfo_t;
104
105 static int syncuuid_cmp( const void *, const void * );
106 static void avl_ber_bvfree( void * );
107 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray, struct berval * );
108 static int syncrepl_message_to_op(
109                                         syncinfo_t *, Operation *, LDAPMessage * );
110 static int syncrepl_message_to_entry(
111                                         syncinfo_t *, Operation *, LDAPMessage *,
112                                         Modifications **, Entry **, int );
113 static int syncrepl_entry(
114                                         syncinfo_t *, Operation*, Entry*,
115                                         Modifications**,int, struct berval* );
116 static int syncrepl_updateCookie(
117                                         syncinfo_t *, Operation *, struct berval *,
118                                         struct sync_cookie * );
119 static struct berval * slap_uuidstr_from_normalized(
120                                         struct berval *, struct berval *, void * );
121
122 /* callback functions */
123 static int dn_callback( Operation *, SlapReply * );
124 static int nonpresent_callback( Operation *, SlapReply * );
125 static int null_callback( Operation *, SlapReply * );
126
127 static AttributeDescription *sync_descs[4];
128
129 static void
130 init_syncrepl(syncinfo_t *si)
131 {
132         int i, j, k, l, n;
133         char **attrs, **exattrs;
134
135         if ( !sync_descs[0] ) {
136                 sync_descs[0] = slap_schema.si_ad_objectClass;
137                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
138                 sync_descs[2] = slap_schema.si_ad_entryCSN;
139                 sync_descs[3] = NULL;
140         }
141
142         if ( si->si_allattrs && si->si_allopattrs )
143                 attrs = NULL;
144         else
145                 attrs = anlist2attrs( si->si_anlist );
146
147         if ( attrs ) {
148                 if ( si->si_allattrs ) {
149                         i = 0;
150                         while ( attrs[i] ) {
151                                 if ( !is_at_operational( at_find( attrs[i] ) ) ) {
152                                         for ( j = i; attrs[j] != NULL; j++ ) {
153                                                 if ( j == i )
154                                                         ch_free( attrs[i] );
155                                                 attrs[j] = attrs[j+1];
156                                         }
157                                 } else {
158                                         i++;
159                                 }
160                         }
161                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
162                         attrs[i] = ch_strdup("*");
163                         attrs[i + 1] = NULL;
164
165                 } else if ( si->si_allopattrs ) {
166                         i = 0;
167                         while ( attrs[i] ) {
168                                 if ( is_at_operational( at_find( attrs[i] ) ) ) {
169                                         for ( j = i; attrs[j] != NULL; j++ ) {
170                                                 if ( j == i )
171                                                         ch_free( attrs[i] );
172                                                 attrs[j] = attrs[j+1];
173                                         }
174                                 } else {
175                                         i++;
176                                 }
177                         }
178                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
179                         attrs[i] = ch_strdup("+");
180                         attrs[i + 1] = NULL;
181                 }
182
183                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
184                         j = 0;
185                         while ( attrs[j] ) {
186                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
187                                         for ( k = j; attrs[k] != NULL; k++ ) {
188                                                 if ( k == j )
189                                                         ch_free( attrs[k] );
190                                                 attrs[k] = attrs[k+1];
191                                         }
192                                 } else {
193                                         j++;
194                                 }
195                         }
196                 }
197
198                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
199
200                 if ( si->si_allopattrs ) {
201                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ) );
202                 } else {
203                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ) );
204                 }
205
206                 /* Add Attributes */
207                 if ( si->si_allopattrs ) {
208                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
209                 } else {
210                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
211                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
212                         }
213                 }
214                 attrs[ n ] = NULL;
215
216         } else {
217
218                 i = 0;
219                 if ( si->si_allattrs == si->si_allopattrs ) {
220                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
221                         attrs[i++] = ch_strdup( "*" );
222                         attrs[i++] = ch_strdup( "+" );
223                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
224                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
225                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
226                         attrs[i++] = ch_strdup( "*" );
227                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
228                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
229                         }
230                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
231                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
232                         attrs[i++] = ch_strdup( "+" );
233                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
234                 }
235                 attrs[i] = NULL;
236         }
237         
238         si->si_attrs = attrs;
239
240         exattrs = anlist2attrs( si->si_exanlist );
241
242         if ( exattrs ) {
243                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
244
245                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
246                         j = 0;
247                         while ( exattrs[j] != NULL ) {
248                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
249                                         ch_free( exattrs[j] );
250                                         for ( k = j; exattrs[k] != NULL; k++ ) {
251                                                 exattrs[k] = exattrs[k+1];
252                                         }
253                                 } else {
254                                         j++;
255                                 }
256                         }
257                 }
258
259                 for ( i = 0; exattrs[i] != NULL; i++ ) {
260                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
261                                 ObjectClass     *oc;
262                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
263                                         k = 0;
264                                         while ( oc->soc_required[k] ) {
265                                                 if ( !strcmp( exattrs[i],
266                                                          oc->soc_required[k]->sat_cname.bv_val ) ) {
267                                                         ch_free( exattrs[i] );
268                                                         for ( l = i; exattrs[l]; l++ ) {
269                                                                 exattrs[l] = exattrs[l+1];
270                                                         }
271                                                 } else {
272                                                         k++;
273                                                 }
274                                         }
275                                 }
276                         }
277                 }
278
279                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
280
281                 if ( i != n )
282                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *) );
283         }
284
285         si->si_exattrs = exattrs;       
286 }
287
288 typedef struct logschema {
289         struct berval ls_dn;
290         struct berval ls_req;
291         struct berval ls_mod;
292         struct berval ls_newRdn;
293         struct berval ls_delRdn;
294         struct berval ls_newSup;
295 } logschema;
296
297 static logschema changelog_sc = {
298         BER_BVC("targetDN"),
299         BER_BVC("changeType"),
300         BER_BVC("changes"),
301         BER_BVC("newRDN"),
302         BER_BVC("deleteOldRDN"),
303         BER_BVC("newSuperior")
304 };
305
306 static logschema accesslog_sc = {
307         BER_BVC("reqDN"),
308         BER_BVC("reqType"),
309         BER_BVC("reqMod"),
310         BER_BVC("reqNewRDN"),
311         BER_BVC("reqDeleteOldRDN"),
312         BER_BVC("reqNewSuperior")
313 };
314
315 static int
316 ldap_sync_search(
317         syncinfo_t *si,
318         void *ctx )
319 {
320         BerElementBuffer berbuf;
321         BerElement *ber = (BerElement *)&berbuf;
322         LDAPControl c[2], *ctrls[3];
323         struct timeval timeout;
324         ber_int_t       msgid;
325         int rc;
326         int rhint;
327         char *base;
328         char **attrs, *lattrs[8];
329         char *filter;
330         int attrsonly;
331         int scope;
332
333         /* setup LDAP SYNC control */
334         ber_init2( ber, NULL, LBER_USE_DER );
335         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
336
337         /* If we're using a log but we have no state, then fallback to
338          * normal mode for a full refresh.
339          */
340         if ( si->si_syncdata && !si->si_syncCookie.numcsns ) {
341                 si->si_logstate = SYNCLOG_FALLBACK;
342         }
343
344         /* Use the log parameters if we're in log mode */
345         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
346                 logschema *ls;
347                 if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
348                         ls = &accesslog_sc;
349                 else
350                         ls = &changelog_sc;
351                 lattrs[0] = ls->ls_dn.bv_val;
352                 lattrs[1] = ls->ls_req.bv_val;
353                 lattrs[2] = ls->ls_mod.bv_val;
354                 lattrs[3] = ls->ls_newRdn.bv_val;
355                 lattrs[4] = ls->ls_delRdn.bv_val;
356                 lattrs[5] = ls->ls_newSup.bv_val;
357                 lattrs[6] = slap_schema.si_ad_entryCSN->ad_cname.bv_val;
358                 lattrs[7] = NULL;
359
360                 rhint = 0;
361                 base = si->si_logbase.bv_val;
362                 filter = si->si_logfilterstr.bv_val;
363                 attrs = lattrs;
364                 attrsonly = 0;
365                 scope = LDAP_SCOPE_SUBTREE;
366         } else {
367                 rhint = 1;
368                 base = si->si_base.bv_val;
369                 filter = si->si_filterstr.bv_val;
370                 attrs = si->si_attrs;
371                 attrsonly = si->si_attrsonly;
372                 scope = si->si_scope;
373         }
374         if ( si->si_syncdata && si->si_logstate == SYNCLOG_FALLBACK ) {
375                 si->si_type = LDAP_SYNC_REFRESH_ONLY;
376         } else {
377                 si->si_type = si->si_ctype;
378         }
379
380         if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
381         {
382                 ber_printf( ber, "{eOb}",
383                         abs(si->si_type), &si->si_syncCookie.octet_str, rhint );
384         } else {
385                 ber_printf( ber, "{eb}",
386                         abs(si->si_type), rhint );
387         }
388
389         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 ) ) == LBER_ERROR ) {
390                 ber_free_buf( ber );
391                 return rc;
392         }
393
394         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
395         c[0].ldctl_iscritical = si->si_type < 0;
396         ctrls[0] = &c[0];
397
398         if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
399                 c[1].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
400                 c[1].ldctl_value = si->si_bindconf.sb_authzId;
401                 c[1].ldctl_iscritical = 1;
402                 ctrls[1] = &c[1];
403                 ctrls[2] = NULL;
404         } else {
405                 ctrls[1] = NULL;
406         }
407
408         timeout.tv_sec = si->si_tlimit;
409         timeout.tv_usec = 0;
410
411         rc = ldap_search_ext( si->si_ld, base, scope, filter, attrs, attrsonly,
412                 ctrls, NULL, si->si_tlimit > 0 ? &timeout : NULL,
413                 si->si_slimit, &msgid );
414         ber_free_buf( ber );
415         return rc;
416 }
417
418 static int
419 do_syncrep1(
420         Operation *op,
421         syncinfo_t *si )
422 {
423         int     rc;
424         int cmdline_cookie_found = 0;
425
426         struct sync_cookie      *sc = NULL;
427 #ifdef HAVE_TLS
428         void    *ssl;
429 #endif
430
431         rc = slap_client_connect( &si->si_ld, &si->si_bindconf );
432         if ( rc != LDAP_SUCCESS ) {
433                 goto done;
434         }
435         op->o_protocol = LDAP_VERSION3;
436
437         /* Set SSF to strongest of TLS, SASL SSFs */
438         op->o_sasl_ssf = 0;
439         op->o_tls_ssf = 0;
440         op->o_transport_ssf = 0;
441 #ifdef HAVE_TLS
442         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
443                 == LDAP_SUCCESS && ssl != NULL )
444         {
445                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
446         }
447 #endif /* HAVE_TLS */
448         ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &op->o_sasl_ssf );
449         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
450                 ?  op->o_sasl_ssf : op->o_tls_ssf;
451
452         /* We've just started up, or the remote server hasn't sent us
453          * any meaningful state.
454          */
455         if ( BER_BVISNULL( &si->si_syncCookie.octet_str ) ) {
456                 int i;
457
458                 si->si_syncCookie.rid = si->si_rid;
459                 si->si_syncCookie.sid = SLAP_SINGLE_SHADOW( si->si_be ) ? -1 :
460                         slap_serverID;
461
462                 LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
463                         if ( si->si_rid == sc->rid ) {
464                                 cmdline_cookie_found = 1;
465                                 break;
466                         }
467                 }
468
469                 if ( cmdline_cookie_found ) {
470                         /* cookie is supplied in the command line */
471
472                         LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
473
474                         /* ctxcsn wasn't parsed yet, do it now */
475                         slap_parse_sync_cookie( sc, op->o_tmpmemctx );
476                         slap_sync_cookie_free( &si->si_syncCookie, 0 );
477                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
478                         slap_sync_cookie_free( sc, 1 );
479                 } else {
480                         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
481                         if ( !si->si_cookieState->cs_num ) {
482                                 /* get contextCSN shadow replica from database */
483                                 BerVarray csn = NULL;
484                                 void *ctx = op->o_tmpmemctx;
485
486                                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
487                                 op->o_req_dn = op->o_req_ndn;
488
489                                 /* try to read stored contextCSN */
490                                 op->o_tmpmemctx = NULL;
491                                 backend_attribute( op, NULL, &op->o_req_ndn,
492                                         slap_schema.si_ad_contextCSN, &csn, ACL_READ );
493                                 op->o_tmpmemctx = ctx;
494                                 if ( csn ) {
495                                         si->si_cookieState->cs_vals = csn;
496                                         for (i=0; !BER_BVISNULL( &csn[i] ); i++);
497                                         si->si_cookieState->cs_num = i;
498                                         si->si_cookieState->cs_sids = slap_parse_csn_sids( csn, i, NULL );
499                                 }
500                         }
501                         if ( si->si_cookieState->cs_num ) {
502                                 ber_bvarray_free( si->si_syncCookie.ctxcsn );
503                                 if ( ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
504                                         si->si_cookieState->cs_vals, NULL )) {
505                                         rc = LDAP_NO_MEMORY;
506                                         goto done;
507                                 }
508                                 si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
509                                 si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num *
510                                         sizeof(int) );
511                                 for ( i=0; i<si->si_syncCookie.numcsns; i++ )
512                                         si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
513                         }
514                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
515                 }
516
517                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
518                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
519                         si->si_syncCookie.sid );
520         } else {
521                 AttributeName at[2];
522                 Attribute a = { slap_schema.si_ad_contextCSN };
523                 Entry e = {0};
524                 SlapReply rs = {0};
525                 int i, j, changed = 0;
526
527                 /* Look for contextCSN from syncprov overlay. If
528                  * there's no overlay, this will be a no-op. That means
529                  * this is a pure consumer, so local changes will not be
530                  * allowed, and all changes will already be reflected in
531                  * the cookieState.
532                  */
533                 e.e_attrs = &a;
534                 e.e_name = si->si_wbe->be_suffix[0];
535                 e.e_nname = si->si_wbe->be_nsuffix[0];
536                 rs.sr_entry = &e;
537                 rs.sr_flags = REP_ENTRY_MODIFIABLE;
538                 at[0].an_name = a.a_desc->ad_cname;
539                 at[0].an_desc = a.a_desc;
540                 BER_BVZERO( &at[1].an_name );
541
542                 ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
543                 rc = backend_operational( op, &rs );
544                 if ( rc == LDAP_SUCCESS && a.a_vals ) {
545                         int num;
546                         for (i=0; !BER_BVISNULL( &a.a_vals[i] ); i++) ;
547                         num = i;
548                         /* check for differences */
549                         if ( num != si->si_cookieState->cs_num ) {
550                                 changed = 1;
551                         } else {
552                                 for ( i=0; i<num; i++ ) {
553                                         if ( ber_bvcmp( &a.a_vals[i],
554                                                 &si->si_cookieState->cs_vals[i] )) {
555                                                 changed =1;
556                                                 break;
557                                         }
558                                 }
559                         }
560                         if ( changed ) {
561                                 ber_bvarray_free( si->si_cookieState->cs_vals );
562                                 ch_free( si->si_cookieState->cs_sids );
563                                 si->si_cookieState->cs_num = num;
564                                 si->si_cookieState->cs_vals = a.a_vals;
565                                 si->si_cookieState->cs_sids = slap_parse_csn_sids( a.a_vals,
566                                         num, NULL );
567                                 si->si_cookieState->cs_age++;
568                         } else {
569                                 ber_bvarray_free( a.a_vals );
570                         }
571                         changed = 0;
572                 }
573                 /* See if the cookieState has changed due to anything outside
574                  * this particular consumer. That includes other consumers in
575                  * the same context, or local changes detected above.
576                  */
577                 if ( si->si_cookieState->cs_num > 1 && si->si_cookieAge !=
578                         si->si_cookieState->cs_age ) {
579
580                         for (i=0; !BER_BVISNULL( &si->si_syncCookie.ctxcsn[i] ); i++) {
581                                 /* bogus, just dup everything */
582                                 if ( si->si_syncCookie.sids[i] == -1 ) {
583                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
584                                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
585                                                 si->si_cookieState->cs_vals, NULL );
586                                         changed = 1;
587                                         break;
588                                 }
589                                 for (j=0; j<si->si_cookieState->cs_num; j++) {
590                                         if ( si->si_syncCookie.sids[i] !=
591                                                 si->si_cookieState->cs_sids[j] )
592                                                 continue;
593                                         if ( bvmatch( &si->si_syncCookie.ctxcsn[i],
594                                                 &si->si_cookieState->cs_vals[j] ))
595                                                 break;
596                                         ber_bvreplace( &si->si_syncCookie.ctxcsn[i],
597                                                 &si->si_cookieState->cs_vals[j] );
598                                         changed = 1;
599                                         break;
600                                 }
601                         }
602                         if ( changed ) {
603                                 ch_free( si->si_syncCookie.octet_str.bv_val );
604                                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
605                                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
606                                         SLAP_SINGLE_SHADOW( si->si_be ) ? -1 : slap_serverID );
607                         }
608                 }
609                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
610         }
611
612         rc = ldap_sync_search( si, op->o_tmpmemctx );
613
614         if( rc != LDAP_SUCCESS ) {
615                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s "
616                         "ldap_search_ext: %s (%d)\n",
617                         si->si_ridtxt, ldap_err2string( rc ), rc );
618         }
619
620 done:
621         if ( rc ) {
622                 if ( si->si_ld ) {
623                         ldap_unbind_ext( si->si_ld, NULL, NULL );
624                         si->si_ld = NULL;
625                 }
626         }
627
628         return rc;
629 }
630
631 static int
632 compare_csns( struct sync_cookie *sc1, struct sync_cookie *sc2, int *which )
633 {
634         int i, j, match = 0;
635         const char *text;
636
637         *which = 0;
638
639         if ( sc1->numcsns < sc2->numcsns ) {
640                 *which = sc1->numcsns;
641                 return -1;
642         }
643
644         for (i=0; !BER_BVISNULL( &sc1->ctxcsn[i] ); i++) {
645                 for (j=0; !BER_BVISNULL( &sc2->ctxcsn[j] ); j++) {
646                         if ( sc1->sids[i] != sc2->sids[j] )
647                                 continue;
648                         value_match( &match, slap_schema.si_ad_entryCSN,
649                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
650                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
651                                 &sc1->ctxcsn[i], &sc2->ctxcsn[i], &text );
652                         if ( match < 0 ) {
653                                 *which = j;
654                                 return match;
655                         }
656                         break;
657                 }
658         }
659         return match;
660 }
661
662 static int
663 do_syncrep2(
664         Operation *op,
665         syncinfo_t *si )
666 {
667         LDAPControl     **rctrls = NULL;
668         LDAPControl     *rctrlp;
669
670         BerElementBuffer berbuf;
671         BerElement      *ber = (BerElement *)&berbuf;
672
673         LDAPMessage     *res = NULL;
674         LDAPMessage     *msg = NULL;
675
676         char            *retoid = NULL;
677         struct berval   *retdata = NULL;
678
679         Entry           *entry = NULL;
680
681         int             syncstate;
682         struct berval   syncUUID = BER_BVNULL;
683         struct sync_cookie      syncCookie = { NULL };
684         struct sync_cookie      syncCookie_req = { NULL };
685         struct berval           cookie = BER_BVNULL;
686
687         int     rc, err;
688         ber_len_t       len;
689
690         struct berval   *psub;
691         Modifications   *modlist = NULL;
692
693         int                             match, m;
694
695         struct timeval *tout_p = NULL;
696         struct timeval tout = { 0, 0 };
697
698         int             refreshDeletes = 0;
699         int             refreshDone = 1;
700         BerVarray syncUUIDs = NULL;
701         ber_tag_t si_tag;
702
703         if ( slapd_shutdown ) {
704                 rc = -2;
705                 goto done;
706         }
707
708         ber_init2( ber, NULL, LBER_USE_DER );
709         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
710
711         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2 %s\n", si->si_ridtxt, 0, 0 );
712
713         psub = &si->si_be->be_nsuffix[0];
714
715         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
716
717         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
718                 tout_p = &tout;
719         } else {
720                 tout_p = NULL;
721         }
722
723         while ( ( rc = ldap_result( si->si_ld, LDAP_RES_ANY, LDAP_MSG_ONE,
724                 tout_p, &res ) ) > 0 )
725         {
726                 if ( slapd_shutdown ) {
727                         rc = -2;
728                         goto done;
729                 }
730                 for( msg = ldap_first_message( si->si_ld, res );
731                         msg != NULL;
732                         msg = ldap_next_message( si->si_ld, msg ) )
733                 {
734                         if ( slapd_shutdown ) {
735                                 rc = -2;
736                                 goto done;
737                         }
738                         switch( ldap_msgtype( msg ) ) {
739                         case LDAP_RES_SEARCH_ENTRY:
740                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
741                                 /* we can't work without the control */
742                                 rctrlp = NULL;
743                                 if ( rctrls ) {
744                                         /* NOTE: make sure we use the right one;
745                                          * a better approach would be to run thru
746                                          * the whole list and take care of all */
747                                         rctrlp = ldap_find_control( LDAP_CONTROL_SYNC_STATE, rctrls );
748                                 }
749                                 if ( rctrlp == NULL ) {
750                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
751                                                 "got search entry without "
752                                                 "Sync State control\n", si->si_ridtxt, 0, 0 );
753                                         rc = -1;
754                                         goto done;
755                                 }
756                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
757                                 ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
758                                 /* FIXME: what if syncUUID is NULL or empty?
759                                  * (happens with back-sql...) */
760                                 if ( BER_BVISEMPTY( &syncUUID ) ) {
761                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
762                                                 "got empty syncUUID\n", si->si_ridtxt, 0, 0 );
763                                         ldap_controls_free( rctrls );
764                                         rc = -1;
765                                         goto done;
766                                 }
767                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
768                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
769                                         if ( !BER_BVISNULL( &cookie ) ) {
770                                                 ch_free( syncCookie.octet_str.bv_val );
771                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
772                                         }
773                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
774                                         {
775                                                 slap_parse_sync_cookie( &syncCookie, NULL );
776                                         }
777                                 }
778                                 rc = 0;
779                                 if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
780                                         modlist = NULL;
781                                         if ( ( rc = syncrepl_message_to_op( si, op, msg ) ) == LDAP_SUCCESS &&
782                                                 syncCookie.ctxcsn )
783                                         {
784                                                 rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
785                                         }
786                                 } else if ( ( rc = syncrepl_message_to_entry( si, op, msg,
787                                         &modlist, &entry, syncstate ) ) == LDAP_SUCCESS )
788                                 {
789                                         if ( ( rc = syncrepl_entry( si, op, entry, &modlist,
790                                                 syncstate, &syncUUID ) ) == LDAP_SUCCESS &&
791                                                 syncCookie.ctxcsn )
792                                         {
793                                                 rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
794                                         }
795                                 }
796                                 ldap_controls_free( rctrls );
797                                 if ( modlist ) {
798                                         slap_mods_free( modlist, 1 );
799                                 }
800                                 if ( rc )
801                                         goto done;
802                                 break;
803
804                         case LDAP_RES_SEARCH_REFERENCE:
805                                 Debug( LDAP_DEBUG_ANY,
806                                         "do_syncrep2: %s reference received error\n",
807                                         si->si_ridtxt, 0, 0 );
808                                 break;
809
810                         case LDAP_RES_SEARCH_RESULT:
811                                 Debug( LDAP_DEBUG_SYNC,
812                                         "do_syncrep2: %s LDAP_RES_SEARCH_RESULT\n",
813                                         si->si_ridtxt, 0, 0 );
814                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
815                                         &rctrls, 0 );
816 #ifdef LDAP_X_SYNC_REFRESH_REQUIRED
817                                 if ( err == LDAP_X_SYNC_REFRESH_REQUIRED ) {
818                                         /* map old result code to registered code */
819                                         err = LDAP_SYNC_REFRESH_REQUIRED;
820                                 }
821 #endif
822                                 if ( err == LDAP_SYNC_REFRESH_REQUIRED ) {
823                                         if ( si->si_logstate == SYNCLOG_LOGGING ) {
824                                                 si->si_logstate = SYNCLOG_FALLBACK;
825                                         }
826                                         rc = err;
827                                         goto done;
828                                 }
829                                 if ( rctrls ) {
830                                         rctrlp = *rctrls;
831                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
832
833                                         ber_scanf( ber, "{" /*"}"*/);
834                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
835                                                 ber_scanf( ber, "m", &cookie );
836                                                 if ( !BER_BVISNULL( &cookie ) ) {
837                                                         ch_free( syncCookie.octet_str.bv_val );
838                                                         ber_dupbv( &syncCookie.octet_str, &cookie);
839                                                 }
840                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
841                                                 {
842                                                         slap_parse_sync_cookie( &syncCookie, NULL );
843                                                 }
844                                         }
845                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
846                                         {
847                                                 ber_scanf( ber, "b", &refreshDeletes );
848                                         }
849                                         ber_scanf( ber, /*"{"*/ "}" );
850                                 }
851                                 if ( !syncCookie.ctxcsn ) {
852                                         match = 1;
853                                 } else if ( !syncCookie_req.ctxcsn ) {
854                                         match = -1;
855                                         m = 0;
856                                 } else {
857                                         match = compare_csns( &syncCookie_req, &syncCookie, &m );
858                                 }
859                                 if ( rctrls ) {
860                                         ldap_controls_free( rctrls );
861                                 }
862                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
863                                         /* FIXME : different error behaviors according to
864                                          *      1) err code : LDAP_BUSY ...
865                                          *      2) on err policy : stop service, stop sync, retry
866                                          */
867                                         if ( refreshDeletes == 0 && match < 0 &&
868                                                 err == LDAP_SUCCESS )
869                                         {
870                                                 syncrepl_del_nonpresent( op, si, NULL,
871                                                         &syncCookie.ctxcsn[m] );
872                                         } else {
873                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
874                                                 si->si_presentlist = NULL;
875                                         }
876                                 }
877                                 if ( syncCookie.ctxcsn && match < 0 && err == LDAP_SUCCESS )
878                                 {
879                                         rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
880                                 }
881                                 if ( err == LDAP_SUCCESS
882                                         && si->si_logstate == SYNCLOG_FALLBACK ) {
883                                         si->si_logstate = SYNCLOG_LOGGING;
884                                         rc = LDAP_SYNC_REFRESH_REQUIRED;
885                                 } else {
886                                         rc = -2;
887                                 }
888                                 goto done;
889                                 break;
890
891                         case LDAP_RES_INTERMEDIATE:
892                                 rc = ldap_parse_intermediate( si->si_ld, msg,
893                                         &retoid, &retdata, NULL, 0 );
894                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
895                                         ber_init2( ber, retdata, LBER_USE_DER );
896
897                                         switch ( si_tag = ber_peek_tag( ber, &len ) ) {
898                                         ber_tag_t tag;
899                                         case LDAP_TAG_SYNC_NEW_COOKIE:
900                                                 Debug( LDAP_DEBUG_SYNC,
901                                                         "do_syncrep2: %s %s - %s\n", 
902                                                         si->si_ridtxt,
903                                                         "LDAP_RES_INTERMEDIATE", 
904                                                         "NEW_COOKIE" );
905                                                 ber_scanf( ber, "tm", &tag, &cookie );
906                                                 break;
907                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
908                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
909                                                 Debug( LDAP_DEBUG_SYNC,
910                                                         "do_syncrep2: %s %s - %s\n", 
911                                                         si->si_ridtxt,
912                                                         "LDAP_RES_INTERMEDIATE", 
913                                                         si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
914                                                         "REFRESH_PRESENT" : "REFRESH_DELETE" );
915                                                 if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
916                                                         si->si_refreshDelete = 1;
917                                                 } else {
918                                                         si->si_refreshPresent = 1;
919                                                 }
920                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
921                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
922                                                 {
923                                                         ber_scanf( ber, "m", &cookie );
924                                                         if ( !BER_BVISNULL( &cookie ) ) {
925                                                                 ch_free( syncCookie.octet_str.bv_val );
926                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
927                                                         }
928                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
929                                                         {
930                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
931                                                         }
932                                                 }
933                                                 if ( ber_peek_tag( ber, &len ) ==
934                                                         LDAP_TAG_REFRESHDONE )
935                                                 {
936                                                         ber_scanf( ber, "b", &refreshDone );
937                                                 }
938                                                 ber_scanf( ber, /*"{"*/ "}" );
939                                                 break;
940                                         case LDAP_TAG_SYNC_ID_SET:
941                                                 Debug( LDAP_DEBUG_SYNC,
942                                                         "do_syncrep2: %s %s - %s\n", 
943                                                         si->si_ridtxt,
944                                                         "LDAP_RES_INTERMEDIATE", 
945                                                         "SYNC_ID_SET" );
946                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
947                                                 if ( ber_peek_tag( ber, &len ) ==
948                                                         LDAP_TAG_SYNC_COOKIE )
949                                                 {
950                                                         ber_scanf( ber, "m", &cookie );
951                                                         if ( !BER_BVISNULL( &cookie ) ) {
952                                                                 ch_free( syncCookie.octet_str.bv_val );
953                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
954                                                         }
955                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
956                                                         {
957                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
958                                                                 compare_csns( &syncCookie_req, &syncCookie, &m );
959                                                         }
960                                                 }
961                                                 if ( ber_peek_tag( ber, &len ) ==
962                                                         LDAP_TAG_REFRESHDELETES )
963                                                 {
964                                                         ber_scanf( ber, "b", &refreshDeletes );
965                                                 }
966                                                 ber_scanf( ber, "[W]", &syncUUIDs );
967                                                 ber_scanf( ber, /*"{"*/ "}" );
968                                                 if ( refreshDeletes ) {
969                                                         syncrepl_del_nonpresent( op, si, syncUUIDs,
970                                                                 &syncCookie.ctxcsn[m] );
971                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
972                                                 } else {
973                                                         int i;
974                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
975                                                                 struct berval *syncuuid_bv;
976                                                                 syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
977                                                                 slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
978                                                                 if ( avl_insert( &si->si_presentlist,
979                                                                         (caddr_t) syncuuid_bv,
980                                                                         syncuuid_cmp, avl_dup_error ) )
981                                                                 {
982                                                                         ber_bvfree( syncuuid_bv );
983                                                                 }
984                                                         }
985                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
986                                                 }
987                                                 slap_sync_cookie_free( &syncCookie, 0 );
988                                                 break;
989                                         default:
990                                                 Debug( LDAP_DEBUG_ANY,
991                                                         "do_syncrep2: %s unknown syncinfo tag (%ld)\n",
992                                                         si->si_ridtxt, (long) si_tag, 0 );
993                                                 ldap_memfree( retoid );
994                                                 ber_bvfree( retdata );
995                                                 continue;
996                                         }
997
998                                         if ( !syncCookie.ctxcsn ) {
999                                                 match = 1;
1000                                         } else if ( !syncCookie_req.ctxcsn ) {
1001                                                 match = -1;
1002                                                 m = 0;
1003                                         } else {
1004                                                 match = compare_csns( &syncCookie_req, &syncCookie, &m );
1005                                         }
1006
1007                                         if ( match < 0 ) {
1008                                                 if ( si->si_refreshPresent == 1 ) {
1009                                                         syncrepl_del_nonpresent( op, si, NULL,
1010                                                                 &syncCookie.ctxcsn[m] );
1011                                                 }
1012
1013                                                 if ( syncCookie.ctxcsn )
1014                                                 {
1015                                                         rc = syncrepl_updateCookie( si, op, psub, &syncCookie);
1016                                                 }
1017                                         } 
1018
1019                                         ldap_memfree( retoid );
1020                                         ber_bvfree( retdata );
1021                                         break;
1022
1023                                 } else {
1024                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1025                                                 "unknown intermediate response (%d)\n",
1026                                                 si->si_ridtxt, rc, 0 );
1027                                         ldap_memfree( retoid );
1028                                         ber_bvfree( retdata );
1029                                         break;
1030                                 }
1031                                 break;
1032
1033                         default:
1034                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1035                                         "unknown message\n", si->si_ridtxt, 0, 0 );
1036                                 break;
1037
1038                         }
1039                         if ( !BER_BVISNULL( &syncCookie.octet_str ) ) {
1040                                 slap_sync_cookie_free( &syncCookie_req, 0 );
1041                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
1042                                 slap_sync_cookie_free( &syncCookie, 0 );
1043                         }
1044                 }
1045                 ldap_msgfree( res );
1046                 res = NULL;
1047         }
1048
1049         if ( rc == -1 ) {
1050                 const char *errstr;
1051
1052                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
1053                 errstr = ldap_err2string( rc );
1054                 
1055                 Debug( LDAP_DEBUG_ANY,
1056                         "do_syncrep2: %s %s\n", si->si_ridtxt, errstr, 0 );
1057         }
1058
1059 done:
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         op = (Operation *) &opbuf;
1126         connection_fake_init( &conn, op, ctx );
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                                 AttributeDescription *opattrs[] = {
2085                                         slap_schema.si_ad_entryCSN,
2086                                         slap_schema.si_ad_modifiersName,
2087                                         slap_schema.si_ad_modifyTimestamp,
2088                                         NULL
2089                                 };
2090                                 Modifications *mod, **modtail, **ml;
2091                                 int i;
2092
2093                                 for ( mod = op->orr_modlist;
2094                                         mod->sml_next;
2095                                         mod = mod->sml_next )
2096                                         ;
2097                                 modtail = &mod->sml_next;
2098
2099                                 /* pull mod off incoming modlist, append to orr_modlist */
2100                                 for ( i = 0; opattrs[i]; i++ ) {
2101                                         for ( ml = modlist; *ml; ml = &(*ml)->sml_next )
2102                                         {
2103                                                 if ( (*ml)->sml_desc == opattrs[i] ) {
2104                                                         mod = *ml;
2105                                                         *ml = mod->sml_next;
2106                                                         mod->sml_next = NULL;
2107                                                         *modtail = mod;
2108                                                         modtail = &mod->sml_next;
2109                                                         break;
2110                                                 }
2111                                         }
2112                                 }
2113                         }
2114                         op->o_bd = si->si_wbe;
2115                         rc = op->o_bd->be_modrdn( op, &rs_modify );
2116                         op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
2117                         op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
2118
2119                         slap_mods_free( op->orr_modlist, 1 );
2120                         Debug( LDAP_DEBUG_SYNC,
2121                                         "syncrepl_entry: %s be_modrdn (%d)\n", 
2122                                         si->si_ridtxt, rc, 0 );
2123                         op->o_bd = be;
2124                         goto done;
2125                 }
2126                 if ( dni.mods ) {
2127                         op->o_tag = LDAP_REQ_MODIFY;
2128                         op->orm_modlist = dni.mods;
2129                         op->orm_no_opattrs = 1;
2130                         op->o_bd = si->si_wbe;
2131
2132                         rc = op->o_bd->be_modify( op, &rs_modify );
2133                         slap_mods_free( op->orm_modlist, 1 );
2134                         Debug( LDAP_DEBUG_SYNC,
2135                                         "syncrepl_entry: %s be_modify (%d)\n", 
2136                                         si->si_ridtxt, rc, 0 );
2137                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2138                                 Debug( LDAP_DEBUG_ANY,
2139                                         "syncrepl_entry: %s be_modify failed (%d)\n",
2140                                         si->si_ridtxt, rs_modify.sr_err, 0 );
2141                         }
2142                         op->o_bd = be;
2143                 } else {
2144                         Debug( LDAP_DEBUG_SYNC,
2145                                         "syncrepl_entry: %s entry unchanged, ignored (%s)\n", 
2146                                         si->si_ridtxt, op->o_req_dn.bv_val, 0 );
2147                 }
2148                 goto done;
2149         case LDAP_SYNC_DELETE :
2150                 if ( !BER_BVISNULL( &dni.dn ) ) {
2151                         op->o_req_dn = dni.dn;
2152                         op->o_req_ndn = dni.ndn;
2153                         op->o_tag = LDAP_REQ_DELETE;
2154                         op->o_bd = si->si_wbe;
2155                         rc = op->o_bd->be_delete( op, &rs_delete );
2156                         Debug( LDAP_DEBUG_SYNC,
2157                                         "syncrepl_entry: %s be_delete (%d)\n", 
2158                                         si->si_ridtxt, rc, 0 );
2159
2160                         while ( rs_delete.sr_err == LDAP_SUCCESS
2161                                 && op->o_delete_glue_parent ) {
2162                                 op->o_delete_glue_parent = 0;
2163                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2164                                         slap_callback cb = { NULL };
2165                                         cb.sc_response = slap_null_cb;
2166                                         dnParent( &op->o_req_ndn, &pdn );
2167                                         op->o_req_dn = pdn;
2168                                         op->o_req_ndn = pdn;
2169                                         op->o_callback = &cb;
2170                                         op->o_bd->be_delete( op, &rs_delete );
2171                                 } else {
2172                                         break;
2173                                 }
2174                         }
2175                         op->o_bd = be;
2176                 }
2177                 goto done;
2178
2179         default :
2180                 Debug( LDAP_DEBUG_ANY,
2181                         "syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
2182                 goto done;
2183         }
2184
2185 done:
2186         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2187                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2188                 BER_BVZERO( &syncUUID_strrep );
2189         }
2190         if ( !BER_BVISNULL( &dni.ndn ) ) {
2191                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2192         }
2193         if ( !BER_BVISNULL( &dni.dn ) ) {
2194                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2195         }
2196         if ( entry )
2197                 entry_free( entry );
2198         BER_BVZERO( &op->o_csn );
2199         return rc;
2200 }
2201
2202 static struct berval gcbva[] = {
2203         BER_BVC("top"),
2204         BER_BVC("glue"),
2205         BER_BVNULL
2206 };
2207
2208 #define NP_DELETE_ONE   2
2209
2210 static void
2211 syncrepl_del_nonpresent(
2212         Operation *op,
2213         syncinfo_t *si,
2214         BerVarray uuids,
2215         struct berval *cookiecsn )
2216 {
2217         Backend* be = op->o_bd;
2218         slap_callback   cb = { NULL };
2219         SlapReply       rs_search = {REP_RESULT};
2220         SlapReply       rs_delete = {REP_RESULT};
2221         SlapReply       rs_modify = {REP_RESULT};
2222         struct nonpresent_entry *np_list, *np_prev;
2223         int rc;
2224         AttributeName   an[2];
2225
2226         struct berval pdn = BER_BVNULL;
2227         struct berval csn;
2228
2229         op->o_req_dn = si->si_base;
2230         op->o_req_ndn = si->si_base;
2231
2232         cb.sc_response = nonpresent_callback;
2233         cb.sc_private = si;
2234
2235         op->o_callback = &cb;
2236         op->o_tag = LDAP_REQ_SEARCH;
2237         op->ors_scope = si->si_scope;
2238         op->ors_deref = LDAP_DEREF_NEVER;
2239         op->o_time = slap_get_time();
2240         op->ors_tlimit = SLAP_NO_LIMIT;
2241
2242
2243         if ( uuids ) {
2244                 Filter uf;
2245 #ifdef LDAP_COMP_MATCH
2246                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
2247 #else
2248                 AttributeAssertion eq = { NULL, BER_BVNULL };
2249 #endif
2250                 int i;
2251
2252                 op->ors_attrsonly = 1;
2253                 op->ors_attrs = slap_anlist_no_attrs;
2254                 op->ors_limit = NULL;
2255                 op->ors_filter = &uf;
2256
2257                 uf.f_ava = &eq;
2258                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2259                 uf.f_next = NULL;
2260                 uf.f_choice = LDAP_FILTER_EQUALITY;
2261                 si->si_refreshDelete |= NP_DELETE_ONE;
2262
2263                 for (i=0; uuids[i].bv_val; i++) {
2264                         op->ors_slimit = 1;
2265                         slap_uuidstr_from_normalized( &uf.f_av_value, &uuids[i],
2266                                 op->o_tmpmemctx );
2267                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2268                         op->o_tmpfree( uf.f_av_value.bv_val, op->o_tmpmemctx );
2269                         uf.f_av_value = uuids[i];
2270                         rc = be->be_search( op, &rs_search );
2271                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2272                 }
2273                 si->si_refreshDelete ^= NP_DELETE_ONE;
2274         } else {
2275                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2276                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2277                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2278                 op->ors_attrs = an;
2279                 op->ors_slimit = SLAP_NO_LIMIT;
2280                 op->ors_attrsonly = 0;
2281                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2282                 op->ors_filterstr = si->si_filterstr;
2283                 op->o_nocaching = 1;
2284
2285                 if ( limits_check( op, &rs_search ) == 0 ) {
2286                         rc = be->be_search( op, &rs_search );
2287                 }
2288                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
2289         }
2290
2291         op->o_nocaching = 0;
2292
2293         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2294
2295                 if ( cookiecsn && !BER_BVISNULL( cookiecsn ) ) {
2296                         csn = *cookiecsn;
2297                 } else {
2298                         csn = si->si_syncCookie.ctxcsn[0];
2299                 }
2300
2301                 op->o_bd = si->si_wbe;
2302                 slap_queue_csn( op, &csn );
2303
2304                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2305                 while ( np_list != NULL ) {
2306                         LDAP_LIST_REMOVE( np_list, npe_link );
2307                         np_prev = np_list;
2308                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2309                         op->o_tag = LDAP_REQ_DELETE;
2310                         op->o_callback = &cb;
2311                         cb.sc_response = null_callback;
2312                         cb.sc_private = si;
2313                         op->o_req_dn = *np_prev->npe_name;
2314                         op->o_req_ndn = *np_prev->npe_nname;
2315                         rc = op->o_bd->be_delete( op, &rs_delete );
2316                         Debug( LDAP_DEBUG_SYNC,
2317                                 "syncrepl_del_nonpresent: %s be_delete %s (%d)\n", 
2318                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
2319
2320                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2321                                 Modifications mod1, mod2;
2322                                 mod1.sml_op = LDAP_MOD_REPLACE;
2323                                 mod1.sml_flags = 0;
2324                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2325                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2326                                 mod1.sml_values = &gcbva[0];
2327                                 mod1.sml_nvalues = NULL;
2328                                 mod1.sml_next = &mod2;
2329
2330                                 mod2.sml_op = LDAP_MOD_REPLACE;
2331                                 mod2.sml_flags = 0;
2332                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2333                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2334                                 mod2.sml_values = &gcbva[1];
2335                                 mod2.sml_nvalues = NULL;
2336                                 mod2.sml_next = NULL;
2337
2338                                 op->o_tag = LDAP_REQ_MODIFY;
2339                                 op->orm_modlist = &mod1;
2340
2341                                 rc = op->o_bd->be_modify( op, &rs_modify );
2342                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2343                         }
2344
2345                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2346                                         op->o_delete_glue_parent ) {
2347                                 op->o_delete_glue_parent = 0;
2348                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2349                                         slap_callback cb = { NULL };
2350                                         cb.sc_response = slap_null_cb;
2351                                         dnParent( &op->o_req_ndn, &pdn );
2352                                         op->o_req_dn = pdn;
2353                                         op->o_req_ndn = pdn;
2354                                         op->o_callback = &cb;
2355                                         /* give it a root privil ? */
2356                                         op->o_bd->be_delete( op, &rs_delete );
2357                                 } else {
2358                                         break;
2359                                 }
2360                         }
2361
2362                         op->o_delete_glue_parent = 0;
2363
2364                         ber_bvfree( np_prev->npe_name );
2365                         ber_bvfree( np_prev->npe_nname );
2366                         ch_free( np_prev );
2367                 }
2368
2369                 slap_graduate_commit_csn( op );
2370                 op->o_bd = be;
2371
2372                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2373                 BER_BVZERO( &op->o_csn );
2374         }
2375
2376         return;
2377 }
2378
2379 int
2380 syncrepl_add_glue(
2381         Operation* op,
2382         Entry *e )
2383 {
2384         Backend *be = op->o_bd;
2385         slap_callback cb = { NULL };
2386         Attribute       *a;
2387         int     rc;
2388         int suffrdns;
2389         int i;
2390         struct berval dn = BER_BVNULL;
2391         struct berval ndn = BER_BVNULL;
2392         Entry   *glue;
2393         SlapReply       rs_add = {REP_RESULT};
2394         struct berval   ptr, nptr;
2395         char            *comma;
2396
2397         op->o_tag = LDAP_REQ_ADD;
2398         op->o_callback = &cb;
2399         cb.sc_response = null_callback;
2400         cb.sc_private = NULL;
2401
2402         dn = e->e_name;
2403         ndn = e->e_nname;
2404
2405         /* count RDNs in suffix */
2406         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2407                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2408                         comma++;
2409                         ptr.bv_len -= comma - ptr.bv_val;
2410                         ptr.bv_val = comma;
2411                         i++;
2412                 }
2413                 suffrdns = i;
2414         } else {
2415                 /* suffix is "" */
2416                 suffrdns = 0;
2417         }
2418
2419         /* Start with BE suffix */
2420         ptr = dn;
2421         for ( i = 0; i < suffrdns; i++ ) {
2422                 comma = ber_bvrchr( &ptr, ',' );
2423                 if ( comma != NULL ) {
2424                         ptr.bv_len = comma - ptr.bv_val;
2425                 } else {
2426                         ptr.bv_len = 0;
2427                         break;
2428                 }
2429         }
2430         
2431         if ( !BER_BVISEMPTY( &ptr ) ) {
2432                 dn.bv_len -= ptr.bv_len + 1;
2433                 dn.bv_val += ptr.bv_len + 1;
2434         }
2435
2436         /* the normalizedDNs are always the same length, no counting
2437          * required.
2438          */
2439         nptr = ndn;
2440         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2441                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2442                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2443
2444                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2445
2446         } else {
2447                 nptr.bv_len = 0;
2448         }
2449
2450         while ( ndn.bv_val > e->e_nname.bv_val ) {
2451                 glue = entry_alloc();
2452                 ber_dupbv( &glue->e_name, &dn );
2453                 ber_dupbv( &glue->e_nname, &ndn );
2454
2455                 a = attr_alloc( slap_schema.si_ad_objectClass );
2456
2457                 a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
2458                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2459                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2460                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2461
2462                 a->a_nvals = a->a_vals;
2463
2464                 a->a_next = glue->e_attrs;
2465                 glue->e_attrs = a;
2466
2467                 a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
2468
2469                 a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
2470                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2471                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2472
2473                 a->a_nvals = a->a_vals;
2474
2475                 a->a_next = glue->e_attrs;
2476                 glue->e_attrs = a;
2477
2478                 op->o_req_dn = glue->e_name;
2479                 op->o_req_ndn = glue->e_nname;
2480                 op->ora_e = glue;
2481                 rc = be->be_add ( op, &rs_add );
2482                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2483                         if ( op->ora_e == glue )
2484                                 be_entry_release_w( op, glue );
2485                 } else {
2486                 /* incl. ALREADY EXIST */
2487                         entry_free( glue );
2488                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
2489                                 entry_free( e );
2490                                 return rc;
2491                         }
2492                 }
2493
2494                 /* Move to next child */
2495                 comma = ber_bvrchr( &ptr, ',' );
2496                 if ( comma == NULL ) {
2497                         break;
2498                 }
2499                 ptr.bv_len = comma - ptr.bv_val;
2500                 
2501                 dn.bv_val = ++comma;
2502                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2503
2504                 comma = ber_bvrchr( &nptr, ',' );
2505                 assert( comma != NULL );
2506                 nptr.bv_len = comma - nptr.bv_val;
2507
2508                 ndn.bv_val = ++comma;
2509                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2510         }
2511
2512         op->o_req_dn = e->e_name;
2513         op->o_req_ndn = e->e_nname;
2514         op->ora_e = e;
2515         rc = be->be_add ( op, &rs_add );
2516         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2517                 if ( op->ora_e == e )
2518                         be_entry_release_w( op, e );
2519         } else {
2520                 entry_free( e );
2521         }
2522
2523         return rc;
2524 }
2525
2526 static int
2527 syncrepl_updateCookie(
2528         syncinfo_t *si,
2529         Operation *op,
2530         struct berval *pdn,
2531         struct sync_cookie *syncCookie )
2532 {
2533         Backend *be = op->o_bd;
2534         Modifications mod[2];
2535         struct berval first = BER_BVNULL;
2536
2537         int rc, i, j;
2538
2539         slap_callback cb = { NULL };
2540         SlapReply       rs_modify = {REP_RESULT};
2541
2542         mod[0].sml_op = LDAP_MOD_DELETE;
2543         mod[0].sml_desc = slap_schema.si_ad_contextCSN;
2544         mod[0].sml_type = mod[0].sml_desc->ad_cname;
2545         mod[0].sml_values = NULL;
2546         mod[0].sml_nvalues = NULL;
2547         mod[0].sml_next = &mod[1];
2548
2549         mod[1].sml_op = LDAP_MOD_ADD;
2550         mod[1].sml_desc = slap_schema.si_ad_contextCSN;
2551         mod[1].sml_type = mod[0].sml_desc->ad_cname;
2552         mod[1].sml_values = NULL;
2553         mod[1].sml_nvalues = NULL;
2554         mod[1].sml_next = NULL;
2555
2556         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
2557
2558         for ( i=0; i<syncCookie->numcsns; i++ ) {
2559                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
2560                         if ( syncCookie->sids[i] != si->si_cookieState->cs_sids[j] )
2561                                 continue;
2562                         if ( ber_bvcmp( &syncCookie->ctxcsn[i],
2563                                 &si->si_cookieState->cs_vals[j] ) > 0 ) {
2564                                 ber_bvarray_add_x( &mod[0].sml_values,
2565                                         &si->si_cookieState->cs_vals[j], op->o_tmpmemctx );
2566                                 ber_bvarray_add_x( &mod[1].sml_values,
2567                                         &syncCookie->ctxcsn[i], op->o_tmpmemctx );
2568                                 if ( BER_BVISNULL( &first ))
2569                                         first = syncCookie->ctxcsn[i];
2570                         }
2571                         break;
2572                 }
2573                 /* there was no match for this SID, it's a new CSN */
2574                 if ( j == si->si_cookieState->cs_num ) {
2575                         ber_bvarray_add_x( &mod[1].sml_values,
2576                                 &syncCookie->ctxcsn[i], op->o_tmpmemctx );
2577                         if ( BER_BVISNULL( &first ))
2578                                 first = syncCookie->ctxcsn[i];
2579                 }
2580         }
2581         op->o_bd = si->si_wbe;
2582         slap_queue_csn( op, &first );
2583
2584         op->o_tag = LDAP_REQ_MODIFY;
2585
2586         cb.sc_response = null_callback;
2587         cb.sc_private = si;
2588
2589         op->o_callback = &cb;
2590         op->o_req_dn = op->o_bd->be_suffix[0];
2591         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2592
2593         /* update contextCSN */
2594         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2595
2596         if ( mod[0].sml_values )
2597                 op->orm_modlist = mod;
2598         else
2599                 op->orm_modlist = &mod[1];
2600
2601         op->orm_no_opattrs = 1;
2602         rc = op->o_bd->be_modify( op, &rs_modify );
2603         op->o_msgid = 0;
2604
2605         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
2606                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
2607                 slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2608                 /* If we replaced any old values */
2609                 if ( mod[0].sml_values ) {
2610                         for ( i=0; !BER_BVISNULL( &mod[0].sml_values[i] ); i++ ) {
2611                                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
2612                                         if ( mod[0].sml_values[i].bv_val !=
2613                                                 si->si_cookieState->cs_vals[j].bv_val )
2614                                                 continue;
2615                                         ber_bvreplace( &si->si_cookieState->cs_vals[j],
2616                                                 &mod[1].sml_values[i] );
2617                                         break;
2618                                 }
2619                         }
2620                 } else {
2621                         /* Else we just added */
2622                         si->si_cookieState->cs_num += syncCookie->numcsns;
2623                         value_add( &si->si_cookieState->cs_vals, syncCookie->ctxcsn );
2624                         free( si->si_cookieState->cs_sids );
2625                         si->si_cookieState->cs_sids = slap_parse_csn_sids(
2626                                 si->si_cookieState->cs_vals, si->si_cookieState->cs_num, NULL );
2627                 }
2628
2629                 si->si_cookieState->cs_age++;
2630                 si->si_cookieAge = si->si_cookieState->cs_age;
2631         } else {
2632                 Debug( LDAP_DEBUG_ANY,
2633                         "syncrepl_updateCookie: %s be_modify failed (%d)\n",
2634                         si->si_ridtxt, rs_modify.sr_err, 0 );
2635         }
2636         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
2637
2638         slap_graduate_commit_csn( op );
2639         op->o_bd = be;
2640         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2641         BER_BVZERO( &op->o_csn );
2642         if ( mod[1].sml_next ) slap_mods_free( mod[1].sml_next, 1 );
2643         op->o_tmpfree( mod[1].sml_values, op->o_tmpmemctx );
2644         op->o_tmpfree( mod[0].sml_values, op->o_tmpmemctx );
2645
2646         return rc;
2647 }
2648
2649 static void
2650 attr_cmp( Operation *op, Attribute *old, Attribute *new,
2651         Modifications ***mret, Modifications ***mcur )
2652 {
2653         int i, j;
2654         Modifications *mod, **modtail;
2655
2656         modtail = *mret;
2657
2658         if ( old ) {
2659                 int n, o, d, a, *adds, *dels;
2660                 /* count old and new */
2661                 for ( o=0; old->a_vals[o].bv_val; o++ ) ;
2662                 for ( n=0; new->a_vals[n].bv_val; n++ ) ;
2663
2664                 adds = op->o_tmpalloc( sizeof(int) * n, op->o_tmpmemctx );
2665                 dels = op->o_tmpalloc( sizeof(int) * o, op->o_tmpmemctx );
2666                 d = 0;
2667                 a = 0;
2668                 i = 0;
2669                 j = 0;
2670
2671                 while ( i < o && j < n ) {
2672                         int k;
2673                         if ( bvmatch( &old->a_vals[i], &new->a_vals[j] ) ) {
2674                                 i++;
2675                                 j++;
2676                                 continue;
2677                         }
2678                         for ( k = j + 1; k<n; k++ ) {
2679                                 if ( bvmatch( &old->a_vals[i], &new->a_vals[k] ) ) {
2680                                         break;
2681                                 }
2682                         }
2683                         /* an old value was deleted */
2684                         if ( k == n ) {
2685                                 dels[d++] = i++;
2686                                 continue;
2687                         }
2688                         for ( k = i + 1; k < o; k++ ) {
2689                                 if ( bvmatch( &old->a_vals[k], &new->a_vals[j] ) ) {
2690                                         break;
2691                                 }
2692                         }
2693                         if ( k == o ) {
2694                                 adds[a++] = j++;
2695                         }
2696                 }
2697                 while ( i < o )
2698                         dels[d++] = i++;
2699                 while ( j < n )
2700                         adds[a++] = j++;
2701
2702                 /* all old values were deleted, just use the replace op */
2703                 if ( d == o ) {
2704                         i = j-1;
2705                 } else if ( d ) {
2706                 /* delete some values */
2707                         mod = ch_malloc( sizeof( Modifications ) );
2708                         mod->sml_op = LDAP_MOD_DELETE;
2709                         mod->sml_flags = 0;
2710                         mod->sml_desc = old->a_desc;
2711                         mod->sml_type = mod->sml_desc->ad_cname;
2712                         mod->sml_values = ch_malloc( ( d + 1 ) * sizeof(struct berval) );
2713                         if ( old->a_vals != old->a_nvals ) {
2714                                 mod->sml_nvalues = ch_malloc( ( d + 1 ) * sizeof(struct berval) );
2715                         } else {
2716                                 mod->sml_nvalues = NULL;
2717                         }
2718                         for ( i = 0; i < d; i++ ) {
2719                                 ber_dupbv( &mod->sml_values[i], &old->a_vals[dels[i]] );
2720                                 if ( mod->sml_nvalues ) {
2721                                         ber_dupbv( &mod->sml_nvalues[i], &old->a_nvals[dels[i]] );
2722                                 }
2723                         }
2724                         BER_BVZERO( &mod->sml_values[i] );
2725                         if ( mod->sml_nvalues ) {
2726                                 BER_BVZERO( &mod->sml_nvalues[i] );
2727                         }
2728                         *modtail = mod;
2729                         modtail = &mod->sml_next;
2730                         i = j;
2731                 }
2732                 op->o_tmpfree( dels, op->o_tmpmemctx );
2733                 /* some values were added */
2734                 if ( a && d < o ) {
2735                         mod = ch_malloc( sizeof( Modifications ) );
2736                         mod->sml_op = LDAP_MOD_ADD;
2737                         mod->sml_flags = 0;
2738                         mod->sml_desc = old->a_desc;
2739                         mod->sml_type = mod->sml_desc->ad_cname;
2740                         mod->sml_values = ch_malloc( ( a + 1 ) * sizeof(struct berval) );
2741                         if ( old->a_vals != old->a_nvals ) {
2742                                 mod->sml_nvalues = ch_malloc( ( a + 1 ) * sizeof(struct berval) );
2743                         } else {
2744                                 mod->sml_nvalues = NULL;
2745                         }
2746                         for ( i = 0; i < a; i++ ) {
2747                                 ber_dupbv( &mod->sml_values[i], &new->a_vals[adds[i]] );
2748                                 if ( mod->sml_nvalues ) {
2749                                         ber_dupbv( &mod->sml_nvalues[i], &new->a_nvals[adds[i]] );
2750                                 }
2751                         }
2752                         BER_BVZERO( &mod->sml_values[i] );
2753                         if ( mod->sml_nvalues ) {
2754                                 BER_BVZERO( &mod->sml_nvalues[i] );
2755                         }
2756                         *modtail = mod;
2757                         modtail = &mod->sml_next;
2758                         i = j;
2759                 }
2760                 op->o_tmpfree( adds, op->o_tmpmemctx );
2761         } else {
2762                 /* new attr, just use the new mod */
2763                 i = 0;
2764                 j = 1;
2765         }
2766         /* advance to next element */
2767         mod = **mcur;
2768         if ( mod ) {
2769                 if ( i != j ) {
2770                         **mcur = mod->sml_next;
2771                         *modtail = mod;
2772                         modtail = &mod->sml_next;
2773                 } else {
2774                         *mcur = &mod->sml_next;
2775                 }
2776         }
2777         *mret = modtail;
2778 }
2779
2780 static int
2781 dn_callback(
2782         Operation*      op,
2783         SlapReply*      rs )
2784 {
2785         dninfo *dni = op->o_callback->sc_private;
2786
2787         if ( rs->sr_type == REP_SEARCH ) {
2788                 if ( !BER_BVISNULL( &dni->dn ) ) {
2789                         Debug( LDAP_DEBUG_ANY,
2790                                 "dn_callback : consistency error - "
2791                                 "entryUUID is not unique\n", 0, 0, 0 );
2792                 } else {
2793                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2794                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2795                         /* If there is a new entry, see if it differs from the old.
2796                          * We compare the non-normalized values so that cosmetic changes
2797                          * in the provider are always propagated.
2798                          */
2799                         if ( dni->new_entry ) {
2800                                 Modifications **modtail, **ml;
2801                                 Attribute *old, *new;
2802                                 int i, is_ctx;
2803
2804                                 is_ctx = dn_match( &rs->sr_entry->e_nname,
2805                                         &op->o_bd->be_nsuffix[0] );
2806
2807                                 /* Did the DN change?
2808                                  */
2809                                 if ( !dn_match( &rs->sr_entry->e_name,
2810                                                 &dni->new_entry->e_name ) )
2811                                 {
2812                                         struct berval oldRDN, oldVal;
2813                                         AttributeDescription *ad = NULL;
2814                                         Attribute *a;
2815
2816                                         dni->renamed = 1;
2817                                         /* See if the oldRDN was deleted */
2818                                         dnRdn( &rs->sr_entry->e_nname, &oldRDN );
2819                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
2820                                         oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
2821                                                 oldRDN.bv_val );
2822                                         oldRDN.bv_len -= oldVal.bv_len + 2;
2823                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
2824                                         a = attr_find( dni->new_entry->e_attrs, ad );
2825                                         if ( !a || value_find_ex( ad,
2826                                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
2827                                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
2828                                                 SLAP_MR_VALUE_OF_SYNTAX, a->a_nvals,
2829                                                 &oldVal, op->o_tmpmemctx ) != LDAP_SUCCESS )
2830                                         {
2831                                                 dni->delOldRDN = 1;
2832                                         }
2833                                         /* OK, this was just a modDN, we're done */
2834                                         return LDAP_SUCCESS;
2835                                 }
2836
2837                                 modtail = &dni->mods;
2838                                 ml = dni->modlist;
2839
2840                                 /* Make sure new entry is actually newer than old entry */
2841                                 old = attr_find( rs->sr_entry->e_attrs,
2842                                         slap_schema.si_ad_entryCSN );
2843                                 new = attr_find( dni->new_entry->e_attrs,
2844                                         slap_schema.si_ad_entryCSN );
2845                                 if ( new && old && ber_bvcmp( &old->a_vals[0],
2846                                         &new->a_vals[0] ) >= 0 ) {
2847                                         Debug( LDAP_DEBUG_SYNC,
2848                                                 "dn_callback : new entry is older than ours "
2849                                                 "%s ours %s, new %s\n",
2850                                                 rs->sr_entry->e_name.bv_val,
2851                                                 old->a_vals[0].bv_val,
2852                                                 new->a_vals[0].bv_val );
2853                                         return LDAP_SUCCESS;
2854                                 }
2855
2856                                 /* We assume that attributes are saved in the same order
2857                                  * in the remote and local databases. So if we walk through
2858                                  * the attributeDescriptions one by one they should match in
2859                                  * lock step. If not, look for an add or delete.
2860                                  */
2861                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2862                                                 old && new; )
2863                                 {
2864                                         /* If we've seen this before, use its mod now */
2865                                         if ( new->a_flags & SLAP_ATTR_IXADD ) {
2866                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2867                                                 new = new->a_next;
2868                                                 continue;
2869                                         }
2870                                         /* Skip contextCSN */
2871                                         if ( is_ctx && old->a_desc ==
2872                                                 slap_schema.si_ad_contextCSN ) {
2873                                                 old = old->a_next;
2874                                                 continue;
2875                                         }
2876
2877                                         if ( old->a_desc != new->a_desc ) {
2878                                                 Modifications *mod;
2879                                                 Attribute *tmp;
2880
2881                                                 /* If it's just been re-added later,
2882                                                  * remember that we've seen it.
2883                                                  */
2884                                                 tmp = attr_find( new, old->a_desc );
2885                                                 if ( tmp ) {
2886                                                         tmp->a_flags |= SLAP_ATTR_IXADD;
2887                                                 } else {
2888                                                         /* If it's a new attribute, pull it in.
2889                                                          */
2890                                                         tmp = attr_find( old, new->a_desc );
2891                                                         if ( !tmp ) {
2892                                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2893                                                                 new = new->a_next;
2894                                                                 continue;
2895                                                         }
2896                                                         /* Delete old attr */
2897                                                         mod = ch_malloc( sizeof( Modifications ) );
2898                                                         mod->sml_op = LDAP_MOD_DELETE;
2899                                                         mod->sml_flags = 0;
2900                                                         mod->sml_desc = old->a_desc;
2901                                                         mod->sml_type = mod->sml_desc->ad_cname;
2902                                                         mod->sml_values = NULL;
2903                                                         mod->sml_nvalues = NULL;
2904                                                         *modtail = mod;
2905                                                         modtail = &mod->sml_next;
2906                                                 }
2907                                                 old = old->a_next;
2908                                                 continue;
2909                                         }
2910                                         /* kludge - always update modifiersName so that it
2911                                          * stays co-located with the other mod opattrs. But only
2912                                          * if we know there are other valid mods.
2913                                          */
2914                                         if ( old->a_desc == slap_schema.si_ad_modifiersName &&
2915                                                 dni->mods )
2916                                                 attr_cmp( op, NULL, new, &modtail, &ml );
2917                                         else
2918                                                 attr_cmp( op, old, new, &modtail, &ml );
2919                                         new = new->a_next;
2920                                         old = old->a_next;
2921                                 }
2922                                 *modtail = *ml;
2923                                 *ml = NULL;
2924                         }
2925                 }
2926         } else if ( rs->sr_type == REP_RESULT ) {
2927                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2928                         Debug( LDAP_DEBUG_ANY,
2929                                 "dn_callback : consistency error - "
2930                                 "entryUUID is not unique\n", 0, 0, 0 );
2931                 }
2932         }
2933
2934         return LDAP_SUCCESS;
2935 }
2936
2937 static int
2938 nonpresent_callback(
2939         Operation*      op,
2940         SlapReply*      rs )
2941 {
2942         syncinfo_t *si = op->o_callback->sc_private;
2943         Attribute *a;
2944         int count = 0;
2945         struct berval* present_uuid = NULL;
2946         struct nonpresent_entry *np_entry;
2947
2948         if ( rs->sr_type == REP_RESULT ) {
2949                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2950                 si->si_presentlist = NULL;
2951
2952         } else if ( rs->sr_type == REP_SEARCH ) {
2953                 if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
2954                         char buf[sizeof("rid=000 not")];
2955
2956                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2957
2958                         if ( a ) {
2959                                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2960                                         syncuuid_cmp );
2961                         }
2962
2963                         if ( slap_debug & LDAP_DEBUG_SYNC ) {
2964                                 sprintf( buf, "%s %s", si->si_ridtxt,
2965                                         present_uuid ? "got" : "not" );
2966                         }
2967
2968                         Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %s UUID %s, dn %s\n",
2969                                 buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
2970
2971                         if ( a == NULL ) return 0;
2972                 }
2973
2974                 if ( present_uuid == NULL ) {
2975                         np_entry = (struct nonpresent_entry *)
2976                                 ch_calloc( 1, sizeof( struct nonpresent_entry ) );
2977                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2978                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2979                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2980
2981                 } else {
2982                         avl_delete( &si->si_presentlist,
2983                                         &a->a_nvals[0], syncuuid_cmp );
2984                         ch_free( present_uuid->bv_val );
2985                         ch_free( present_uuid );
2986                 }
2987         }
2988         return LDAP_SUCCESS;
2989 }
2990
2991 static int
2992 null_callback(
2993         Operation*      op,
2994         SlapReply*      rs )
2995 {
2996         if ( rs->sr_err != LDAP_SUCCESS &&
2997                 rs->sr_err != LDAP_REFERRAL &&
2998                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2999                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
3000                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
3001         {
3002                 Debug( LDAP_DEBUG_ANY,
3003                         "null_callback : error code 0x%x\n",
3004                         rs->sr_err, 0, 0 );
3005         }
3006         return LDAP_SUCCESS;
3007 }
3008
3009 static struct berval *
3010 slap_uuidstr_from_normalized(
3011         struct berval* uuidstr,
3012         struct berval* normalized,
3013         void *ctx )
3014 {
3015         struct berval *new;
3016         unsigned char nibble;
3017         int i, d = 0;
3018
3019         if ( normalized == NULL ) return NULL;
3020         if ( normalized->bv_len != 16 ) return NULL;
3021
3022         if ( uuidstr ) {
3023                 new = uuidstr;
3024         } else {
3025                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3026                 if ( new == NULL ) {
3027                         return NULL;
3028                 }
3029         }
3030
3031         new->bv_len = 36;
3032
3033         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3034                 if ( new != uuidstr ) {
3035                         slap_sl_free( new, ctx );
3036                 }
3037                 return NULL;
3038         }
3039
3040         for ( i = 0; i < 16; i++ ) {
3041                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
3042                         new->bv_val[(i<<1)+d] = '-';
3043                         d += 1;
3044                 }
3045
3046                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
3047                 if ( nibble < 10 ) {
3048                         new->bv_val[(i<<1)+d] = nibble + '0';
3049                 } else {
3050                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
3051                 }
3052
3053                 nibble = (normalized->bv_val[i]) & 0xF;
3054                 if ( nibble < 10 ) {
3055                         new->bv_val[(i<<1)+d+1] = nibble + '0';
3056                 } else {
3057                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
3058                 }
3059         }
3060
3061         new->bv_val[new->bv_len] = '\0';
3062         return new;
3063 }
3064
3065 static int
3066 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
3067 {
3068         const struct berval *uuid1 = v_uuid1;
3069         const struct berval *uuid2 = v_uuid2;
3070         int rc = uuid1->bv_len - uuid2->bv_len;
3071         if ( rc ) return rc;
3072         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
3073 }
3074
3075 static void
3076 avl_ber_bvfree( void *v_bv )
3077 {
3078         struct berval   *bv = (struct berval *)v_bv;
3079         
3080         if( v_bv == NULL ) return;
3081         if ( !BER_BVISNULL( bv ) ) {
3082                 ch_free( bv->bv_val );
3083         }
3084         ch_free( (char *) bv );
3085 }
3086
3087 void
3088 syncinfo_free( syncinfo_t *sie, int free_all )
3089 {
3090         syncinfo_t *si_next;
3091
3092         if ( free_all && sie->si_cookieState ) {
3093                 ch_free( sie->si_cookieState->cs_sids );
3094                 ber_bvarray_free( sie->si_cookieState->cs_vals );
3095                 ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_mutex );
3096                 ch_free( sie->si_cookieState );
3097         }
3098         do {
3099                 si_next = sie->si_next;
3100
3101                 if ( sie->si_ld ) {
3102                         if ( sie->si_conn_setup ) {
3103                                 ber_socket_t s;
3104                                 ldap_get_option( sie->si_ld, LDAP_OPT_DESC, &s );
3105                                 connection_client_stop( s );
3106                                 sie->si_conn_setup = 0;
3107                         }
3108                         ldap_unbind_ext( sie->si_ld, NULL, NULL );
3109                 }
3110         
3111                 /* re-fetch it, in case it was already removed */
3112                 sie->si_re = ldap_pvt_runqueue_find( &slapd_rq, do_syncrepl, sie );
3113                 if ( sie->si_re ) {
3114                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, sie->si_re ) )
3115                                 ldap_pvt_runqueue_stoptask( &slapd_rq, sie->si_re );
3116                         ldap_pvt_runqueue_remove( &slapd_rq, sie->si_re );
3117                 }
3118         
3119                 ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
3120         
3121                 bindconf_free( &sie->si_bindconf );
3122         
3123                 if ( sie->si_filterstr.bv_val ) {
3124                         ch_free( sie->si_filterstr.bv_val );
3125                 }
3126                 if ( sie->si_logfilterstr.bv_val ) {
3127                         ch_free( sie->si_logfilterstr.bv_val );
3128                 }
3129                 if ( sie->si_base.bv_val ) {
3130                         ch_free( sie->si_base.bv_val );
3131                 }
3132                 if ( sie->si_logbase.bv_val ) {
3133                         ch_free( sie->si_logbase.bv_val );
3134                 }
3135                 if ( sie->si_attrs ) {
3136                         int i = 0;
3137                         while ( sie->si_attrs[i] != NULL ) {
3138                                 ch_free( sie->si_attrs[i] );
3139                                 i++;
3140                         }
3141                         ch_free( sie->si_attrs );
3142                 }
3143                 if ( sie->si_exattrs ) {
3144                         int i = 0;
3145                         while ( sie->si_exattrs[i] != NULL ) {
3146                                 ch_free( sie->si_exattrs[i] );
3147                                 i++;
3148                         }
3149                         ch_free( sie->si_exattrs );
3150                 }
3151                 if ( sie->si_anlist ) {
3152                         int i = 0;
3153                         while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
3154                                 ch_free( sie->si_anlist[i].an_name.bv_val );
3155                                 i++;
3156                         }
3157                         ch_free( sie->si_anlist );
3158                 }
3159                 if ( sie->si_exanlist ) {
3160                         int i = 0;
3161                         while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
3162                                 ch_free( sie->si_exanlist[i].an_name.bv_val );
3163                                 i++;
3164                         }
3165                         ch_free( sie->si_exanlist );
3166                 }
3167                 if ( sie->si_retryinterval ) {
3168                         ch_free( sie->si_retryinterval );
3169                 }
3170                 if ( sie->si_retrynum ) {
3171                         ch_free( sie->si_retrynum );
3172                 }
3173                 if ( sie->si_retrynum_init ) {
3174                         ch_free( sie->si_retrynum_init );
3175                 }
3176                 slap_sync_cookie_free( &sie->si_syncCookie, 0 );
3177                 if ( sie->si_presentlist ) {
3178                     avl_free( sie->si_presentlist, avl_ber_bvfree );
3179                 }
3180                 while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
3181                         struct nonpresent_entry* npe;
3182                         npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
3183                         LDAP_LIST_REMOVE( npe, npe_link );
3184                         if ( npe->npe_name ) {
3185                                 if ( npe->npe_name->bv_val ) {
3186                                         ch_free( npe->npe_name->bv_val );
3187                                 }
3188                                 ch_free( npe->npe_name );
3189                         }
3190                         if ( npe->npe_nname ) {
3191                                 if ( npe->npe_nname->bv_val ) {
3192                                         ch_free( npe->npe_nname->bv_val );
3193                                 }
3194                                 ch_free( npe->npe_nname );
3195                         }
3196                         ch_free( npe );
3197                 }
3198                 ch_free( sie );
3199                 sie = si_next;
3200         } while ( free_all && si_next );
3201 }
3202
3203
3204
3205 /* NOTE: used & documented in slapd.conf(5) */
3206 #define IDSTR                   "rid"
3207 #define PROVIDERSTR             "provider"
3208 #define SCHEMASTR               "schemachecking"
3209 #define FILTERSTR               "filter"
3210 #define SEARCHBASESTR           "searchbase"
3211 #define SCOPESTR                "scope"
3212 #define ATTRSONLYSTR            "attrsonly"
3213 #define ATTRSSTR                "attrs"
3214 #define TYPESTR                 "type"
3215 #define INTERVALSTR             "interval"
3216 #define RETRYSTR                "retry"
3217 #define SLIMITSTR               "sizelimit"
3218 #define TLIMITSTR               "timelimit"
3219 #define SYNCDATASTR             "syncdata"
3220 #define LOGBASESTR              "logbase"
3221 #define LOGFILTERSTR    "logfilter"
3222
3223 /* FIXME: undocumented */
3224 #define EXATTRSSTR              "exattrs"
3225 #define MANAGEDSAITSTR          "manageDSAit"
3226
3227 /* mandatory */
3228 #define GOT_ID                  0x0001
3229 #define GOT_PROVIDER    0x0002
3230 #define GOT_BASE                0x0004
3231
3232 /* check */
3233 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER|GOT_BASE)
3234
3235 static struct {
3236         struct berval key;
3237         int val;
3238 } scopes[] = {
3239         { BER_BVC("base"), LDAP_SCOPE_BASE },
3240         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
3241         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
3242         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
3243         { BER_BVC("subord"), LDAP_SCOPE_SUBORDINATE },
3244         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
3245         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
3246         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
3247         { BER_BVNULL, 0 }
3248 };
3249
3250 static slap_verbmasks datamodes[] = {
3251         { BER_BVC("default"), SYNCDATA_DEFAULT },
3252         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
3253         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
3254         { BER_BVNULL, 0 }
3255 };
3256
3257 static int
3258 parse_syncrepl_line(
3259         ConfigArgs      *c,
3260         syncinfo_t      *si )
3261 {
3262         int     gots = 0;
3263         int     i;
3264         char    *val;
3265
3266         for ( i = 1; i < c->argc; i++ ) {
3267                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
3268                                         STRLENOF( IDSTR "=" ) ) )
3269                 {
3270                         int tmp;
3271                         /* '\0' string terminator accounts for '=' */
3272                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
3273                         if ( lutil_atoi( &tmp, val ) != 0 ) {
3274                                 snprintf( c->msg, sizeof( c->msg ),
3275                                         "Error: parse_syncrepl_line: "
3276                                         "unable to parse syncrepl id \"%s\"", val );
3277                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3278                                 return -1;
3279                         }
3280                         if ( tmp >= 1000 || tmp < 0 ) {
3281                                 snprintf( c->msg, sizeof( c->msg ),
3282                                         "Error: parse_syncrepl_line: "
3283                                         "syncrepl id %d is out of range [0..999]", tmp );
3284                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3285                                 return -1;
3286                         }
3287                         si->si_rid = tmp;
3288                         sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
3289                         gots |= GOT_ID;
3290                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
3291                                         STRLENOF( PROVIDERSTR "=" ) ) )
3292                 {
3293                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
3294                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
3295                         gots |= GOT_PROVIDER;
3296                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
3297                                         STRLENOF( SCHEMASTR "=" ) ) )
3298                 {
3299                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
3300                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
3301                                 si->si_schemachecking = 1;
3302                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
3303                                 si->si_schemachecking = 0;
3304                         } else {
3305                                 si->si_schemachecking = 1;
3306                         }
3307                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
3308                                         STRLENOF( FILTERSTR "=" ) ) )
3309                 {
3310                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
3311                         if ( si->si_filterstr.bv_val )
3312                                 ch_free( si->si_filterstr.bv_val );
3313                         ber_str2bv( val, 0, 1, &si->si_filterstr );
3314                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
3315                                         STRLENOF( LOGFILTERSTR "=" ) ) )
3316                 {
3317                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
3318                         if ( si->si_logfilterstr.bv_val )
3319                                 ch_free( si->si_logfilterstr.bv_val );
3320                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
3321                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
3322                                         STRLENOF( SEARCHBASESTR "=" ) ) )
3323                 {
3324                         struct berval   bv;
3325                         int             rc;
3326
3327                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
3328                         if ( si->si_base.bv_val ) {
3329                                 ch_free( si->si_base.bv_val );
3330                         }
3331                         ber_str2bv( val, 0, 0, &bv );
3332                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
3333                         if ( rc != LDAP_SUCCESS ) {
3334                                 snprintf( c->msg, sizeof( c->msg ),
3335                                         "Invalid base DN \"%s\": %d (%s)",
3336                                         val, rc, ldap_err2string( rc ) );
3337                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3338                                 return -1;
3339                         }
3340                         gots |= GOT_BASE;
3341                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
3342                                         STRLENOF( LOGBASESTR "=" ) ) )
3343                 {
3344                         struct berval   bv;
3345                         int             rc;
3346
3347                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
3348                         if ( si->si_logbase.bv_val ) {
3349                                 ch_free( si->si_logbase.bv_val );
3350                         }
3351                         ber_str2bv( val, 0, 0, &bv );
3352                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
3353                         if ( rc != LDAP_SUCCESS ) {
3354                                 snprintf( c->msg, sizeof( c->msg ),
3355                                         "Invalid logbase DN \"%s\": %d (%s)",
3356                                         val, rc, ldap_err2string( rc ) );
3357                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3358                                 return -1;
3359                         }
3360                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
3361                                         STRLENOF( SCOPESTR "=" ) ) )
3362                 {
3363                         int j;
3364                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
3365                         for ( j = 0; !BER_BVISNULL(&scopes[j].key); j++ ) {
3366                                 if (!strcasecmp( val, scopes[j].key.bv_val ) ) {
3367                                         si->si_scope = scopes[j].val;
3368                                         break;
3369                                 }
3370                         }
3371                         if ( BER_BVISNULL(&scopes[j].key) ) {
3372                                 snprintf( c->msg, sizeof( c->msg ),
3373                                         "Error: parse_syncrepl_line: "
3374                                         "unknown scope \"%s\"", val);
3375                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3376                                 return -1;
3377                         }
3378                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
3379                                         STRLENOF( ATTRSONLYSTR ) ) )
3380                 {
3381                         si->si_attrsonly = 1;
3382                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
3383                                         STRLENOF( ATTRSSTR "=" ) ) )
3384                 {
3385                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
3386                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
3387                                 char *attr_fname;
3388                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
3389                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
3390                                 if ( si->si_anlist == NULL ) {
3391                                         ch_free( attr_fname );
3392                                         return -1;
3393                                 }
3394                                 si->si_anfile = attr_fname;
3395                         } else {
3396                                 char *str, *s, *next;
3397                                 char delimstr[] = " ,\t";
3398                                 str = ch_strdup( val );
3399                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
3400                                                 s != NULL;
3401                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
3402                                 {
3403                                         if ( strlen(s) == 1 && *s == '*' ) {
3404                                                 si->si_allattrs = 1;
3405                                                 val[ s - str ] = delimstr[0];
3406                                         }
3407                                         if ( strlen(s) == 1 && *s == '+' ) {
3408                                                 si->si_allopattrs = 1;
3409                                                 val [ s - str ] = delimstr[0];
3410                                         }
3411                                 }
3412                                 ch_free( str );
3413                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
3414                                 if ( si->si_anlist == NULL ) {
3415                                         return -1;
3416                                 }
3417                         }
3418                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
3419                                         STRLENOF( EXATTRSSTR "=" ) ) )
3420                 {
3421                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
3422                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
3423                                 char *attr_fname;
3424                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
3425                                 si->si_exanlist = file2anlist(
3426                                         si->si_exanlist, attr_fname, " ,\t" );
3427                                 if ( si->si_exanlist == NULL ) {
3428                                         ch_free( attr_fname );
3429                                         return -1;
3430                                 }
3431                                 ch_free( attr_fname );
3432                         } else {
3433                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
3434                                 if ( si->si_exanlist == NULL ) {
3435                                         return -1;
3436                                 }
3437                         }
3438                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
3439                                         STRLENOF( TYPESTR "=" ) ) )
3440                 {
3441                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
3442                         if ( !strncasecmp( val, "refreshOnly",
3443                                                 STRLENOF("refreshOnly") ) )
3444                         {
3445                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3446                         } else if ( !strncasecmp( val, "refreshAndPersist",
3447                                                 STRLENOF("refreshAndPersist") ) )
3448                         {
3449                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
3450                                 si->si_interval = 60;
3451                         } else {
3452                                 snprintf( c->msg, sizeof( c->msg ),
3453                                         "Error: parse_syncrepl_line: "
3454                                         "unknown sync type \"%s\"", val);
3455                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3456                                 return -1;
3457                         }
3458                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
3459                                         STRLENOF( INTERVALSTR "=" ) ) )
3460                 {
3461                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
3462                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
3463                                 si->si_interval = 0;
3464                         } else if ( strchr( val, ':' ) != NULL ) {
3465                                 char *next, *ptr = val;
3466                                 unsigned dd, hh, mm, ss;
3467
3468                                 /* NOTE: the test for ptr[ 0 ] == '-'
3469                                  * should go before the call to strtoul() */
3470                                 dd = strtoul( ptr, &next, 10 );
3471                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' ) {
3472                                         snprintf( c->msg, sizeof( c->msg ),
3473                                                 "Error: parse_syncrepl_line: "
3474                                                 "invalid interval \"%s\", unable to parse days", val );
3475                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3476                                         return -1;
3477                                 }
3478                                 ptr = next + 1;
3479                                 hh = strtoul( ptr, &next, 10 );
3480                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || hh > 24 ) {
3481                                         snprintf( c->msg, sizeof( c->msg ),
3482                                                 "Error: parse_syncrepl_line: "
3483                                                 "invalid interval \"%s\", unable to parse hours", val );
3484                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3485                                         return -1;
3486                                 }
3487                                 ptr = next + 1;
3488                                 mm = strtoul( ptr, &next, 10 );
3489                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || mm > 60 ) {
3490                                         snprintf( c->msg, sizeof( c->msg ),
3491                                                 "Error: parse_syncrepl_line: "
3492                                                 "invalid interval \"%s\", unable to parse minutes", val );
3493                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3494                                         return -1;
3495                                 }
3496                                 ptr = next + 1;
3497                                 ss = strtoul( ptr, &next, 10 );
3498                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != '\0' || ss > 60 ) {
3499                                         snprintf( c->msg, sizeof( c->msg ),
3500                                                 "Error: parse_syncrepl_line: "
3501                                                 "invalid interval \"%s\", unable to parse seconds", val );
3502                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3503                                         return -1;
3504                                 }
3505                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
3506                         } else {
3507                                 unsigned long   t;
3508
3509                                 if ( lutil_parse_time( val, &t ) != 0 ) {
3510                                         snprintf( c->msg, sizeof( c->msg ),
3511                                                 "Error: parse_syncrepl_line: "
3512                                                 "invalid interval \"%s\"", val );
3513                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3514                                         return -1;
3515                                 }
3516                                 si->si_interval = (time_t)t;
3517                         }
3518                         if ( si->si_interval < 0 ) {
3519                                 snprintf( c->msg, sizeof( c->msg ),
3520                                         "Error: parse_syncrepl_line: "
3521                                         "invalid interval \"%ld\"",
3522                                         (long) si->si_interval);
3523                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3524                                 return -1;
3525                         }
3526                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
3527                                         STRLENOF( RETRYSTR "=" ) ) )
3528                 {
3529                         char **retry_list;
3530                         int j, k, n;
3531
3532                         val = c->argv[ i ] + STRLENOF( RETRYSTR "=" );
3533                         retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
3534                         retry_list[0] = NULL;
3535
3536                         slap_str2clist( &retry_list, val, " ,\t" );
3537
3538                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3539                         n = k / 2;
3540                         if ( k % 2 ) {
3541                                 snprintf( c->msg, sizeof( c->msg ),
3542                                         "Error: incomplete syncrepl retry list" );
3543                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3544                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3545                                         ch_free( retry_list[k] );
3546                                 }
3547                                 ch_free( retry_list );
3548                                 return 1;
3549                         }
3550                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
3551                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
3552                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
3553                         for ( j = 0; j < n; j++ ) {
3554                                 unsigned long   t;
3555                                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3556                                         snprintf( c->msg, sizeof( c->msg ),
3557                                                 "Error: invalid retry interval \"%s\" (#%d)",
3558                                                 retry_list[j*2], j );
3559                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3560                                         /* do some cleanup */
3561                                         return 1;
3562                                 }
3563                                 si->si_retryinterval[j] = (time_t)t;
3564                                 if ( *retry_list[j*2+1] == '+' ) {
3565                                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3566                                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3567                                         j++;
3568                                         break;
3569                                 } else {
3570                                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3571                                                         || si->si_retrynum_init[j] <= 0 )
3572                                         {
3573                                                 snprintf( c->msg, sizeof( c->msg ),
3574                                                         "Error: invalid initial retry number \"%s\" (#%d)",
3575                                                         retry_list[j*2+1], j );
3576                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3577                                                 /* do some cleanup */
3578                                                 return 1;
3579                                         }
3580                                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3581                                                         || si->si_retrynum[j] <= 0 )
3582                                         {
3583                                                 snprintf( c->msg, sizeof( c->msg ),
3584                                                         "Error: invalid retry number \"%s\" (#%d)",
3585                                                         retry_list[j*2+1], j );
3586                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3587                                                 /* do some cleanup */
3588                                                 return 1;
3589                                         }
3590                                 }
3591                         }
3592                         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3593                         si->si_retrynum[j] = RETRYNUM_TAIL;
3594                         si->si_retryinterval[j] = 0;
3595                         
3596                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3597                                 ch_free( retry_list[k] );
3598                         }
3599                         ch_free( retry_list );
3600                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
3601                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
3602                 {
3603                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
3604                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
3605                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
3606                         {
3607                                 snprintf( c->msg, sizeof( c->msg ),
3608                                         "invalid manageDSAit value \"%s\".\n",
3609                                         val );
3610                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3611                                 return 1;
3612                         }
3613                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
3614                                         STRLENOF( SLIMITSTR "=") ) )
3615                 {
3616                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
3617                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3618                                 si->si_slimit = 0;
3619
3620                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
3621                                 snprintf( c->msg, sizeof( c->msg ),
3622                                         "invalid size limit value \"%s\".\n",
3623                                         val );
3624                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3625                                 return 1;
3626                         }
3627                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
3628                                         STRLENOF( TLIMITSTR "=" ) ) )
3629                 {
3630                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
3631                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3632                                 si->si_tlimit = 0;
3633
3634                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
3635                                 snprintf( c->msg, sizeof( c->msg ),
3636                                         "invalid time limit value \"%s\".\n",
3637                                         val );
3638                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3639                                 return 1;
3640                         }
3641                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
3642                                         STRLENOF( SYNCDATASTR "=" ) ) )
3643                 {
3644                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
3645                         si->si_syncdata = verb_to_mask( val, datamodes );
3646                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
3647                         snprintf( c->msg, sizeof( c->msg ),
3648                                 "Error: parse_syncrepl_line: "
3649                                 "unable to parse \"%s\"\n", c->argv[ i ] );
3650                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3651                         return -1;
3652                 }
3653         }
3654
3655         if ( gots != GOT_ALL ) {
3656                 snprintf( c->msg, sizeof( c->msg ),
3657                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
3658                         gots & GOT_ID ? "" : " "IDSTR,
3659                         gots & GOT_PROVIDER ? "" : " "PROVIDERSTR,
3660                         gots & GOT_BASE ? "" : " "SEARCHBASESTR );
3661                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3662                 return -1;
3663         }
3664
3665         return 0;
3666 }
3667
3668 static int
3669 add_syncrepl(
3670         ConfigArgs *c )
3671 {
3672         syncinfo_t *si;
3673         int     rc = 0;
3674
3675         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
3676                 snprintf( c->msg, sizeof(c->msg), "database %s does not support "
3677                         "operations required for syncrepl", c->be->be_type );
3678                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3679                 return 1;
3680         }
3681         if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
3682                 strcpy( c->msg, "rootDN must be defined before syncrepl may be used" );
3683                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
3684                 return 1;
3685         }
3686         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
3687
3688         if ( si == NULL ) {
3689                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
3690                 return 1;
3691         }
3692
3693         si->si_bindconf.sb_tls = SB_TLS_OFF;
3694         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
3695         si->si_schemachecking = 0;
3696         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
3697                 &si->si_filterstr );
3698         si->si_base.bv_val = NULL;
3699         si->si_scope = LDAP_SCOPE_SUBTREE;
3700         si->si_attrsonly = 0;
3701         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
3702         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
3703         si->si_attrs = NULL;
3704         si->si_allattrs = 0;
3705         si->si_allopattrs = 0;
3706         si->si_exattrs = NULL;
3707         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3708         si->si_interval = 86400;
3709         si->si_retryinterval = NULL;
3710         si->si_retrynum_init = NULL;
3711         si->si_retrynum = NULL;
3712         si->si_manageDSAit = 0;
3713         si->si_tlimit = 0;
3714         si->si_slimit = 0;
3715         si->si_conn_setup = 0;
3716
3717         si->si_presentlist = NULL;
3718         LDAP_LIST_INIT( &si->si_nonpresentlist );
3719         ldap_pvt_thread_mutex_init( &si->si_mutex );
3720
3721         rc = parse_syncrepl_line( c, si );
3722
3723         if ( rc == 0 ) {
3724                 /* Must be LDAPv3 because we need controls */
3725                 switch ( si->si_bindconf.sb_version ) {
3726                 case 0:
3727                         /* not explicitly set */
3728                         si->si_bindconf.sb_version = LDAP_VERSION3;
3729                         break;
3730                 case 3:
3731                         /* explicitly set */
3732                         break;
3733                 default:
3734                         Debug( LDAP_DEBUG_ANY,
3735                                 "version %d incompatible with syncrepl\n",
3736                                 si->si_bindconf.sb_version, 0, 0 );
3737                         syncinfo_free( si, 0 ); 
3738                         return 1;
3739                 }
3740
3741                 si->si_be = c->be;
3742                 if ( slapMode & SLAP_SERVER_MODE ) {
3743                         Listener **l = slapd_get_listeners();
3744                         int isMe = 0;
3745
3746                         /* check if URL points to current server. If so, ignore
3747                          * this configuration. We require an exact match. Just
3748                          * in case they really want to do this, they can vary
3749                          * the case of the URL to allow it.
3750                          */
3751                         if ( l && !SLAP_DBHIDDEN( c->be ) ) {
3752                                 int i;
3753                                 for ( i=0; l[i]; i++ ) {
3754                                         if ( bvmatch( &l[i]->sl_url, &si->si_bindconf.sb_uri ) ) {
3755                                                 isMe = 1;
3756                                                 break;
3757                                         }
3758                                 }
3759                         }
3760
3761                         if ( !isMe ) {
3762                                 init_syncrepl( si );
3763                                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
3764                                         si->si_interval, do_syncrepl, si, "do_syncrepl",
3765                                         si->si_ridtxt );
3766                                 if ( si->si_re )
3767                                         rc = config_sync_shadow( c ) ? -1 : 0;
3768                                 else
3769                                         rc = -1;
3770                         }
3771                 }
3772         }
3773
3774 #ifdef HAVE_TLS
3775         /* Use main slapd defaults */
3776         bindconf_tls_defaults( &si->si_bindconf );
3777 #endif
3778         if ( rc < 0 ) {
3779                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
3780                 syncinfo_free( si, 0 ); 
3781                 return 1;
3782         } else {
3783                 Debug( LDAP_DEBUG_CONFIG,
3784                         "Config: ** successfully added syncrepl \"%s\"\n",
3785                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
3786                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
3787                 if ( !si->si_schemachecking ) {
3788                         SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3789                 }
3790                 if ( c->be->be_syncinfo ) {
3791                         si->si_cookieState = c->be->be_syncinfo->si_cookieState;
3792                 } else {
3793                         si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
3794                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
3795                 }
3796                 si->si_next = c->be->be_syncinfo;
3797                 c->be->be_syncinfo = si;
3798                 return 0;
3799         }
3800 }
3801
3802 static void
3803 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
3804 {
3805         struct berval bc, uri;
3806         char buf[BUFSIZ*2], *ptr;
3807         int i;
3808
3809 #define WHATSLEFT       ( sizeof( buf ) - ( ptr - buf ) )
3810
3811         BER_BVZERO( bv );
3812
3813         /* temporarily inhibit bindconf from printing URI */
3814         uri = si->si_bindconf.sb_uri;
3815         BER_BVZERO( &si->si_bindconf.sb_uri );
3816         si->si_bindconf.sb_version = 0;
3817         bindconf_unparse( &si->si_bindconf, &bc );
3818         si->si_bindconf.sb_uri = uri;
3819         si->si_bindconf.sb_version = LDAP_VERSION3;
3820
3821         ptr = buf;
3822         ptr += snprintf( ptr, WHATSLEFT, IDSTR "=%03d " PROVIDERSTR "=%s",
3823                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
3824         if ( ptr - buf >= sizeof( buf ) ) return;
3825         if ( !BER_BVISNULL( &bc ) ) {
3826                 if ( WHATSLEFT <= bc.bv_len ) {
3827                         free( bc.bv_val );
3828                         return;
3829                 }
3830                 ptr = lutil_strcopy( ptr, bc.bv_val );
3831                 free( bc.bv_val );
3832         }
3833         if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
3834                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
3835                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
3836                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
3837                 *ptr++ = '"';
3838         }
3839         if ( !BER_BVISNULL( &si->si_base ) ) {
3840                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
3841                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
3842                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
3843                 *ptr++ = '"';
3844         }
3845         if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
3846                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
3847                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
3848                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
3849                 *ptr++ = '"';
3850         }
3851         if ( !BER_BVISNULL( &si->si_logbase ) ) {
3852                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
3853                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
3854                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
3855                 *ptr++ = '"';
3856         }
3857         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
3858                 if ( si->si_scope == scopes[i].val ) {
3859                         if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + scopes[i].key.bv_len ) return;
3860                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
3861                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
3862                         break;
3863                 }
3864         }
3865         if ( si->si_attrsonly ) {
3866                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3867                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
3868         }
3869         if ( si->si_anfile ) {
3870                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
3871                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
3872                 ptr = lutil_strcopy( ptr, si->si_anfile );
3873                 *ptr++ = '"';
3874         } else if ( si->si_allattrs || si->si_allopattrs ||
3875                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
3876         {
3877                 char *old;
3878
3879                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3880                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
3881                 old = ptr;
3882                 /* FIXME: add check for overflow */
3883                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
3884                 if ( si->si_allattrs ) {
3885                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
3886                         if ( old != ptr ) *ptr++ = ',';
3887                         *ptr++ = '*';
3888                 }
3889                 if ( si->si_allopattrs ) {
3890                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
3891                         if ( old != ptr ) *ptr++ = ',';
3892                         *ptr++ = '+';
3893                 }
3894                 *ptr++ = '"';
3895         }
3896         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3897                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
3898                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3899                 /* FIXME: add check for overflow */
3900                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
3901         }
3902         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
3903         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3904         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3905         
3906         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
3907         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3908         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3909                 "refreshAndPersist" : "refreshOnly" );
3910
3911         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
3912                 int dd, hh, mm, ss;
3913
3914                 dd = si->si_interval;
3915                 ss = dd % 60;
3916                 dd /= 60;
3917                 mm = dd % 60;
3918                 dd /= 60;
3919                 hh = dd % 24;
3920                 dd /= 24;
3921                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
3922                 ptr += snprintf( ptr, WHATSLEFT, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
3923                 if ( ptr - buf >= sizeof( buf ) ) return;
3924         } else if ( si->si_retryinterval ) {
3925                 int space=0;
3926                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
3927                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
3928                 for (i=0; si->si_retryinterval[i]; i++) {
3929                         if ( space ) *ptr++ = ' ';
3930                         space = 1;
3931                         ptr += snprintf( ptr, WHATSLEFT, "%ld ", (long) si->si_retryinterval[i] );
3932                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
3933                                 *ptr++ = '+';
3934                         else
3935                                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
3936                 }
3937                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
3938                 *ptr++ = '"';
3939         }
3940
3941         if ( si->si_slimit ) {
3942                 if ( WHATSLEFT <= STRLENOF( " " SLIMITSTR "=" ) ) return;
3943                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
3944                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_slimit );
3945         }
3946
3947         if ( si->si_tlimit ) {
3948                 if ( WHATSLEFT <= STRLENOF( " " TLIMITSTR "=" ) ) return;
3949                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
3950                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_tlimit );
3951         }
3952
3953         if ( si->si_syncdata ) {
3954                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
3955                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
3956                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
3957                         ptr = lutil_strcopy( ptr, bc.bv_val );
3958                 }
3959         }
3960         bc.bv_len = ptr - buf;
3961         bc.bv_val = buf;
3962         ber_dupbv( bv, &bc );
3963 }
3964
3965 int
3966 syncrepl_config( ConfigArgs *c )
3967 {
3968         if (c->op == SLAP_CONFIG_EMIT) {
3969                 if ( c->be->be_syncinfo ) {
3970                         struct berval bv;
3971                         syncinfo_t *si;
3972
3973                         for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
3974                                 syncrepl_unparse( si, &bv ); 
3975                                 ber_bvarray_add( &c->rvalue_vals, &bv );
3976                         }
3977                         return 0;
3978                 }
3979                 return 1;
3980         } else if ( c->op == LDAP_MOD_DELETE ) {
3981                 cookie_state *cs = NULL;
3982                 if ( c->be->be_syncinfo ) {
3983                         syncinfo_t *si, **sip;
3984                         int i;
3985
3986                         cs = c->be->be_syncinfo->si_cookieState;
3987                         for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
3988                                 si = *sip;
3989                                 if ( c->valx == -1 || i == c->valx ) {
3990                                         *sip = si->si_next;
3991                                         /* If the task is currently active, we have to leave
3992                                          * it running. It will exit on its own. This will only
3993                                          * happen when running on the cn=config DB.
3994                                          */
3995                                         if ( si->si_re &&
3996                                                 ldap_pvt_runqueue_isrunning( &slapd_rq, si->si_re ) ) {
3997                                                 si->si_ctype = 0;
3998                                         } else {
3999                                                 syncinfo_free( si, 0 );
4000                                         }
4001                                         if ( i == c->valx )
4002                                                 break;
4003                                 } else {
4004                                         sip = &si->si_next;
4005                                 }
4006                         }
4007                 }
4008                 if ( !c->be->be_syncinfo ) {
4009                         SLAP_DBFLAGS( c->be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
4010                         if ( cs ) {
4011                                 ber_bvarray_free( cs->cs_vals );
4012                                 ldap_pvt_thread_mutex_destroy( &cs->cs_mutex );
4013                                 ch_free( cs );
4014                         }
4015                 }
4016                 return 0;
4017         }
4018         if ( SLAP_SLURP_SHADOW( c->be ) ) {
4019                 Debug(LDAP_DEBUG_ANY, "%s: "
4020                         "syncrepl: database already shadowed.\n",
4021                         c->log, 0, 0);
4022                 return(1);
4023         } else {
4024                 return add_syncrepl( c );
4025         }
4026 }