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