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